sia_tp_sample / Behappy123__market-maker.jsonl
shahp7575's picture
commit files to HF hub
3a7f06a
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.__init__","parameters":"(self, base_url=None, symbol=None, login=None, password=None, otpToken=None,\n apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_', shouldWSAuth=True)","argument_list":"","return_statement":"","docstring":"Init connector.","docstring_summary":"Init connector.","docstring_tokens":["Init","connector","."],"function":"def __init__(self, base_url=None, symbol=None, login=None, password=None, otpToken=None,\n apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_', shouldWSAuth=True):\n \"\"\"Init connector.\"\"\"\n self.logger = logging.getLogger('root')\n self.base_url = base_url\n self.symbol = symbol\n self.token = None\n # User\/pass auth is no longer supported\n if (login or password or otpToken):\n raise Exception(\"User\/password authentication is no longer supported via the API. Please use \" +\n \"an API key. You can generate one at https:\/\/www.bitmex.com\/app\/apiKeys\")\n self.apiKey = apiKey\n self.apiSecret = apiSecret\n if len(orderIDPrefix) > 13:\n raise ValueError(\"settings.ORDERID_PREFIX must be at most 13 characters long!\")\n self.orderIDPrefix = orderIDPrefix\n\n # Prepare HTTPS session\n self.session = requests.Session()\n # These headers are always sent\n self.session.headers.update({'user-agent': 'liquidbot-' + constants.VERSION})\n self.session.headers.update({'content-type': 'application\/json'})\n self.session.headers.update({'accept': 'application\/json'})\n\n # Create websocket for streaming data\n self.ws = BitMEXWebsocket()\n self.ws.connect(base_url, symbol, shouldAuth=shouldWSAuth)","function_tokens":["def","__init__","(","self",",","base_url","=","None",",","symbol","=","None",",","login","=","None",",","password","=","None",",","otpToken","=","None",",","apiKey","=","None",",","apiSecret","=","None",",","orderIDPrefix","=","'mm_bitmex_'",",","shouldWSAuth","=","True",")",":","self",".","logger","=","logging",".","getLogger","(","'root'",")","self",".","base_url","=","base_url","self",".","symbol","=","symbol","self",".","token","=","None","# User\/pass auth is no longer supported","if","(","login","or","password","or","otpToken",")",":","raise","Exception","(","\"User\/password authentication is no longer supported via the API. Please use \"","+","\"an API key. You can generate one at https:\/\/www.bitmex.com\/app\/apiKeys\"",")","self",".","apiKey","=","apiKey","self",".","apiSecret","=","apiSecret","if","len","(","orderIDPrefix",")",">","13",":","raise","ValueError","(","\"settings.ORDERID_PREFIX must be at most 13 characters long!\"",")","self",".","orderIDPrefix","=","orderIDPrefix","# Prepare HTTPS session","self",".","session","=","requests",".","Session","(",")","# These headers are always sent","self",".","session",".","headers",".","update","(","{","'user-agent'",":","'liquidbot-'","+","constants",".","VERSION","}",")","self",".","session",".","headers",".","update","(","{","'content-type'",":","'application\/json'","}",")","self",".","session",".","headers",".","update","(","{","'accept'",":","'application\/json'","}",")","# Create websocket for streaming data","self",".","ws","=","BitMEXWebsocket","(",")","self",".","ws",".","connect","(","base_url",",","symbol",",","shouldAuth","=","shouldWSAuth",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L19-L45"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.ticker_data","parameters":"(self, symbol)","argument_list":"","return_statement":"return self.ws.get_ticker(symbol)","docstring":"Get ticker data.","docstring_summary":"Get ticker data.","docstring_tokens":["Get","ticker","data","."],"function":"def ticker_data(self, symbol):\n \"\"\"Get ticker data.\"\"\"\n return self.ws.get_ticker(symbol)","function_tokens":["def","ticker_data","(","self",",","symbol",")",":","return","self",".","ws",".","get_ticker","(","symbol",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L50-L52"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.instrument","parameters":"(self, symbol)","argument_list":"","return_statement":"return self.ws.get_instrument(symbol)","docstring":"Get an instrument's details.","docstring_summary":"Get an instrument's details.","docstring_tokens":["Get","an","instrument","s","details","."],"function":"def instrument(self, symbol):\n \"\"\"Get an instrument's details.\"\"\"\n return self.ws.get_instrument(symbol)","function_tokens":["def","instrument","(","self",",","symbol",")",":","return","self",".","ws",".","get_instrument","(","symbol",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L54-L56"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.market_depth","parameters":"(self, symbol)","argument_list":"","return_statement":"return self.ws.market_depth(symbol)","docstring":"Get market depth \/ orderbook.","docstring_summary":"Get market depth \/ orderbook.","docstring_tokens":["Get","market","depth","\/","orderbook","."],"function":"def market_depth(self, symbol):\n \"\"\"Get market depth \/ orderbook.\"\"\"\n return self.ws.market_depth(symbol)","function_tokens":["def","market_depth","(","self",",","symbol",")",":","return","self",".","ws",".","market_depth","(","symbol",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L58-L60"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.recent_trades","parameters":"(self, symbol)","argument_list":"","return_statement":"return self.ws.recent_trades(symbol)","docstring":"Get recent trades.\n\n Returns\n -------\n A list of dicts:\n {u'amount': 60,\n u'date': 1306775375,\n u'price': 8.7401099999999996,\n u'tid': u'93842'},","docstring_summary":"Get recent trades.","docstring_tokens":["Get","recent","trades","."],"function":"def recent_trades(self, symbol):\n \"\"\"Get recent trades.\n\n Returns\n -------\n A list of dicts:\n {u'amount': 60,\n u'date': 1306775375,\n u'price': 8.7401099999999996,\n u'tid': u'93842'},\n\n \"\"\"\n return self.ws.recent_trades(symbol)","function_tokens":["def","recent_trades","(","self",",","symbol",")",":","return","self",".","ws",".","recent_trades","(","symbol",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L62-L74"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.authentication_required","parameters":"(function)","argument_list":"","return_statement":"return wrapped","docstring":"Annotation for methods that require auth.","docstring_summary":"Annotation for methods that require auth.","docstring_tokens":["Annotation","for","methods","that","require","auth","."],"function":"def authentication_required(function):\n \"\"\"Annotation for methods that require auth.\"\"\"\n def wrapped(self, *args, **kwargs):\n if not (self.apiKey):\n msg = \"You must be authenticated to use this method\"\n raise errors.AuthenticationError(msg)\n else:\n return function(self, *args, **kwargs)\n return wrapped","function_tokens":["def","authentication_required","(","function",")",":","def","wrapped","(","self",",","*","args",",","*","*","kwargs",")",":","if","not","(","self",".","apiKey",")",":","msg","=","\"You must be authenticated to use this method\"","raise","errors",".","AuthenticationError","(","msg",")","else",":","return","function","(","self",",","*","args",",","*","*","kwargs",")","return","wrapped"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L79-L87"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.funds","parameters":"(self)","argument_list":"","return_statement":"return self.ws.funds()","docstring":"Get your current balance.","docstring_summary":"Get your current balance.","docstring_tokens":["Get","your","current","balance","."],"function":"def funds(self):\n \"\"\"Get your current balance.\"\"\"\n return self.ws.funds()","function_tokens":["def","funds","(","self",")",":","return","self",".","ws",".","funds","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L90-L92"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.position","parameters":"(self, symbol)","argument_list":"","return_statement":"return self.ws.position(symbol)","docstring":"Get your open position.","docstring_summary":"Get your open position.","docstring_tokens":["Get","your","open","position","."],"function":"def position(self, symbol):\n \"\"\"Get your open position.\"\"\"\n return self.ws.position(symbol)","function_tokens":["def","position","(","self",",","symbol",")",":","return","self",".","ws",".","position","(","symbol",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L95-L97"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.buy","parameters":"(self, quantity, price)","argument_list":"","return_statement":"return self.place_order(quantity, price)","docstring":"Place a buy order.\n\n Returns order object. ID: orderID","docstring_summary":"Place a buy order.","docstring_tokens":["Place","a","buy","order","."],"function":"def buy(self, quantity, price):\n \"\"\"Place a buy order.\n\n Returns order object. ID: orderID\n \"\"\"\n return self.place_order(quantity, price)","function_tokens":["def","buy","(","self",",","quantity",",","price",")",":","return","self",".","place_order","(","quantity",",","price",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L100-L105"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.sell","parameters":"(self, quantity, price)","argument_list":"","return_statement":"return self.place_order(-quantity, price)","docstring":"Place a sell order.\n\n Returns order object. ID: orderID","docstring_summary":"Place a sell order.","docstring_tokens":["Place","a","sell","order","."],"function":"def sell(self, quantity, price):\n \"\"\"Place a sell order.\n\n Returns order object. ID: orderID\n \"\"\"\n return self.place_order(-quantity, price)","function_tokens":["def","sell","(","self",",","quantity",",","price",")",":","return","self",".","place_order","(","-","quantity",",","price",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L108-L113"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.place_order","parameters":"(self, quantity, price)","argument_list":"","return_statement":"return self._curl_bitmex(api=endpoint, postdict=postdict, verb=\"POST\")","docstring":"Place an order.","docstring_summary":"Place an order.","docstring_tokens":["Place","an","order","."],"function":"def place_order(self, quantity, price):\n \"\"\"Place an order.\"\"\"\n if price < 0:\n raise Exception(\"Price must be positive.\")\n\n endpoint = \"order\"\n # Generate a unique clOrdID with our prefix so we can identify it.\n clOrdID = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=\\n')\n postdict = {\n 'symbol': self.symbol,\n 'orderQty': quantity,\n 'price': price,\n 'clOrdID': clOrdID,\n 'execInst': 'ParticipateDoNotInitiate'\n }\n return self._curl_bitmex(api=endpoint, postdict=postdict, verb=\"POST\")","function_tokens":["def","place_order","(","self",",","quantity",",","price",")",":","if","price","<","0",":","raise","Exception","(","\"Price must be positive.\"",")","endpoint","=","\"order\"","# Generate a unique clOrdID with our prefix so we can identify it.","clOrdID","=","self",".","orderIDPrefix","+","base64",".","b64encode","(","uuid",".","uuid4","(",")",".","bytes",")",".","decode","(","'utf-8'",")",".","rstrip","(","'=\\n'",")","postdict","=","{","'symbol'",":","self",".","symbol",",","'orderQty'",":","quantity",",","'price'",":","price",",","'clOrdID'",":","clOrdID",",","'execInst'",":","'ParticipateDoNotInitiate'","}","return","self",".","_curl_bitmex","(","api","=","endpoint",",","postdict","=","postdict",",","verb","=","\"POST\"",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L116-L131"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.amend_bulk_orders","parameters":"(self, orders)","argument_list":"","return_statement":"return self._curl_bitmex(api='order\/bulk', postdict={'orders': orders}, verb='PUT', rethrow_errors=True)","docstring":"Amend multiple orders.","docstring_summary":"Amend multiple orders.","docstring_tokens":["Amend","multiple","orders","."],"function":"def amend_bulk_orders(self, orders):\n \"\"\"Amend multiple orders.\"\"\"\n return self._curl_bitmex(api='order\/bulk', postdict={'orders': orders}, verb='PUT', rethrow_errors=True)","function_tokens":["def","amend_bulk_orders","(","self",",","orders",")",":","return","self",".","_curl_bitmex","(","api","=","'order\/bulk'",",","postdict","=","{","'orders'",":","orders","}",",","verb","=","'PUT'",",","rethrow_errors","=","True",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L134-L136"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.create_bulk_orders","parameters":"(self, orders)","argument_list":"","return_statement":"return self._curl_bitmex(api='order\/bulk', postdict={'orders': orders}, verb='POST')","docstring":"Create multiple orders.","docstring_summary":"Create multiple orders.","docstring_tokens":["Create","multiple","orders","."],"function":"def create_bulk_orders(self, orders):\n \"\"\"Create multiple orders.\"\"\"\n for order in orders:\n order['clOrdID'] = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=\\n')\n order['symbol'] = self.symbol\n order['execInst'] = 'ParticipateDoNotInitiate'\n return self._curl_bitmex(api='order\/bulk', postdict={'orders': orders}, verb='POST')","function_tokens":["def","create_bulk_orders","(","self",",","orders",")",":","for","order","in","orders",":","order","[","'clOrdID'","]","=","self",".","orderIDPrefix","+","base64",".","b64encode","(","uuid",".","uuid4","(",")",".","bytes",")",".","decode","(","'utf-8'",")",".","rstrip","(","'=\\n'",")","order","[","'symbol'","]","=","self",".","symbol","order","[","'execInst'","]","=","'ParticipateDoNotInitiate'","return","self",".","_curl_bitmex","(","api","=","'order\/bulk'",",","postdict","=","{","'orders'",":","orders","}",",","verb","=","'POST'",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L139-L145"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.open_orders","parameters":"(self)","argument_list":"","return_statement":"return self.ws.open_orders(self.orderIDPrefix)","docstring":"Get open orders.","docstring_summary":"Get open orders.","docstring_tokens":["Get","open","orders","."],"function":"def open_orders(self):\n \"\"\"Get open orders.\"\"\"\n return self.ws.open_orders(self.orderIDPrefix)","function_tokens":["def","open_orders","(","self",")",":","return","self",".","ws",".","open_orders","(","self",".","orderIDPrefix",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L148-L150"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.http_open_orders","parameters":"(self)","argument_list":"","return_statement":"return [o for o in orders if str(o['clOrdID']).startswith(self.orderIDPrefix)]","docstring":"Get open orders via HTTP. Used on close to ensure we catch them all.","docstring_summary":"Get open orders via HTTP. Used on close to ensure we catch them all.","docstring_tokens":["Get","open","orders","via","HTTP",".","Used","on","close","to","ensure","we","catch","them","all","."],"function":"def http_open_orders(self):\n \"\"\"Get open orders via HTTP. Used on close to ensure we catch them all.\"\"\"\n api = \"order\"\n orders = self._curl_bitmex(\n api=api,\n query={'filter': json.dumps({'ordStatus.isTerminated': False, 'symbol': self.symbol})},\n verb=\"GET\"\n )\n # Only return orders that start with our clOrdID prefix.\n return [o for o in orders if str(o['clOrdID']).startswith(self.orderIDPrefix)]","function_tokens":["def","http_open_orders","(","self",")",":","api","=","\"order\"","orders","=","self",".","_curl_bitmex","(","api","=","api",",","query","=","{","'filter'",":","json",".","dumps","(","{","'ordStatus.isTerminated'",":","False",",","'symbol'",":","self",".","symbol","}",")","}",",","verb","=","\"GET\"",")","# Only return orders that start with our clOrdID prefix.","return","[","o","for","o","in","orders","if","str","(","o","[","'clOrdID'","]",")",".","startswith","(","self",".","orderIDPrefix",")","]"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L153-L162"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX.cancel","parameters":"(self, orderID)","argument_list":"","return_statement":"return self._curl_bitmex(api=api, postdict=postdict, verb=\"DELETE\")","docstring":"Cancel an existing order.","docstring_summary":"Cancel an existing order.","docstring_tokens":["Cancel","an","existing","order","."],"function":"def cancel(self, orderID):\n \"\"\"Cancel an existing order.\"\"\"\n api = \"order\"\n postdict = {\n 'orderID': orderID,\n }\n return self._curl_bitmex(api=api, postdict=postdict, verb=\"DELETE\")","function_tokens":["def","cancel","(","self",",","orderID",")",":","api","=","\"order\"","postdict","=","{","'orderID'",":","orderID",",","}","return","self",".","_curl_bitmex","(","api","=","api",",","postdict","=","postdict",",","verb","=","\"DELETE\"",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L165-L171"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/bitmex.py","language":"python","identifier":"BitMEX._curl_bitmex","parameters":"(self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False)","argument_list":"","return_statement":"return response.json()","docstring":"Send a request to BitMEX Servers.","docstring_summary":"Send a request to BitMEX Servers.","docstring_tokens":["Send","a","request","to","BitMEX","Servers","."],"function":"def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postdict else 'GET'\n\n # Auth: Use Access Token by default, API Key\/Secret if provided\n auth = AccessTokenAuth(self.token)\n if self.apiKey:\n auth = APIKeyAuthWithExpires(self.apiKey, self.apiSecret)\n\n def maybe_exit(e):\n if rethrow_errors:\n raise e\n else:\n exit(1)\n\n # Make the request\n try:\n req = requests.Request(verb, url, json=postdict, auth=auth, params=query)\n prepped = self.session.prepare_request(req)\n response = self.session.send(prepped, timeout=timeout)\n # Make non-200s throw\n response.raise_for_status()\n\n except requests.exceptions.HTTPError as e:\n # 401 - Auth error. This is fatal with API keys.\n if response.status_code == 401:\n self.logger.error(\"Login information or API Key incorrect, please check and restart.\")\n self.logger.error(\"Error: \" + response.text)\n if postdict:\n self.logger.error(postdict)\n # Always exit, even if rethrow_errors, because this is fatal\n exit(1)\n return self._curl_bitmex(api, query, postdict, timeout, verb)\n\n # 404, can be thrown if order canceled does not exist.\n elif response.status_code == 404:\n if verb == 'DELETE':\n self.logger.error(\"Order not found: %s\" % postdict['orderID'])\n return\n self.logger.error(\"Unable to contact the BitMEX API (404). \" +\n \"Request: %s \\n %s\" % (url, json.dumps(postdict)))\n maybe_exit(e)\n\n # 429, ratelimit\n elif response.status_code == 429:\n self.logger.error(\"Ratelimited on current request. Sleeping, then trying again. Try fewer \" +\n \"order pairs or contact support@bitmex.com to raise your limits. \" +\n \"Request: %s \\n %s\" % (url, json.dumps(postdict)))\n sleep(1)\n return self._curl_bitmex(api, query, postdict, timeout, verb)\n\n # 503 - BitMEX temporary downtime, likely due to a deploy. Try again\n elif response.status_code == 503:\n self.logger.warning(\"Unable to contact the BitMEX API (503), retrying. \" +\n \"Request: %s \\n %s\" % (url, json.dumps(postdict)))\n sleep(1)\n return self._curl_bitmex(api, query, postdict, timeout, verb)\n\n # Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it\n elif (response.status_code == 400 and\n response.json()['error'] and\n response.json()['error']['message'] == 'Duplicate clOrdID'):\n\n order = self._curl_bitmex('\/order',\n query={'filter': json.dumps({'clOrdID': postdict['clOrdID']})},\n verb='GET')[0]\n if (\n order['orderQty'] != postdict['quantity'] or\n order['price'] != postdict['price'] or\n order['symbol'] != postdict['symbol']):\n raise Exception('Attempted to recover from duplicate clOrdID, but order returned from API ' +\n 'did not match POST.\\nPOST data: %s\\nReturned order: %s' % (\n json.dumps(postdict), json.dumps(order)))\n # All good\n return order\n\n # Unknown Error\n else:\n self.logger.error(\"Unhandled Error: %s: %s\" % (e, response.text))\n self.logger.error(\"Endpoint was: %s %s: %s\" % (verb, api, json.dumps(postdict)))\n maybe_exit(e)\n\n except requests.exceptions.Timeout as e:\n # Timeout, re-run this request\n self.logger.warning(\"Timed out, retrying...\")\n return self._curl_bitmex(api, query, postdict, timeout, verb)\n\n except requests.exceptions.ConnectionError as e:\n self.logger.warning(\"Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. \" +\n \"Request: %s \\n %s\" % (url, json.dumps(postdict)))\n sleep(1)\n return self._curl_bitmex(api, query, postdict, timeout, verb)\n\n return response.json()","function_tokens":["def","_curl_bitmex","(","self",",","api",",","query","=","None",",","postdict","=","None",",","timeout","=","3",",","verb","=","None",",","rethrow_errors","=","False",")",":","# Handle URL","url","=","self",".","base_url","+","api","# Default to POST if data is attached, GET otherwise","if","not","verb",":","verb","=","'POST'","if","postdict","else","'GET'","# Auth: Use Access Token by default, API Key\/Secret if provided","auth","=","AccessTokenAuth","(","self",".","token",")","if","self",".","apiKey",":","auth","=","APIKeyAuthWithExpires","(","self",".","apiKey",",","self",".","apiSecret",")","def","maybe_exit","(","e",")",":","if","rethrow_errors",":","raise","e","else",":","exit","(","1",")","# Make the request","try",":","req","=","requests",".","Request","(","verb",",","url",",","json","=","postdict",",","auth","=","auth",",","params","=","query",")","prepped","=","self",".","session",".","prepare_request","(","req",")","response","=","self",".","session",".","send","(","prepped",",","timeout","=","timeout",")","# Make non-200s throw","response",".","raise_for_status","(",")","except","requests",".","exceptions",".","HTTPError","as","e",":","# 401 - Auth error. This is fatal with API keys.","if","response",".","status_code","==","401",":","self",".","logger",".","error","(","\"Login information or API Key incorrect, please check and restart.\"",")","self",".","logger",".","error","(","\"Error: \"","+","response",".","text",")","if","postdict",":","self",".","logger",".","error","(","postdict",")","# Always exit, even if rethrow_errors, because this is fatal","exit","(","1",")","return","self",".","_curl_bitmex","(","api",",","query",",","postdict",",","timeout",",","verb",")","# 404, can be thrown if order canceled does not exist.","elif","response",".","status_code","==","404",":","if","verb","==","'DELETE'",":","self",".","logger",".","error","(","\"Order not found: %s\"","%","postdict","[","'orderID'","]",")","return","self",".","logger",".","error","(","\"Unable to contact the BitMEX API (404). \"","+","\"Request: %s \\n %s\"","%","(","url",",","json",".","dumps","(","postdict",")",")",")","maybe_exit","(","e",")","# 429, ratelimit","elif","response",".","status_code","==","429",":","self",".","logger",".","error","(","\"Ratelimited on current request. Sleeping, then trying again. Try fewer \"","+","\"order pairs or contact support@bitmex.com to raise your limits. \"","+","\"Request: %s \\n %s\"","%","(","url",",","json",".","dumps","(","postdict",")",")",")","sleep","(","1",")","return","self",".","_curl_bitmex","(","api",",","query",",","postdict",",","timeout",",","verb",")","# 503 - BitMEX temporary downtime, likely due to a deploy. Try again","elif","response",".","status_code","==","503",":","self",".","logger",".","warning","(","\"Unable to contact the BitMEX API (503), retrying. \"","+","\"Request: %s \\n %s\"","%","(","url",",","json",".","dumps","(","postdict",")",")",")","sleep","(","1",")","return","self",".","_curl_bitmex","(","api",",","query",",","postdict",",","timeout",",","verb",")","# Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it","elif","(","response",".","status_code","==","400","and","response",".","json","(",")","[","'error'","]","and","response",".","json","(",")","[","'error'","]","[","'message'","]","==","'Duplicate clOrdID'",")",":","order","=","self",".","_curl_bitmex","(","'\/order'",",","query","=","{","'filter'",":","json",".","dumps","(","{","'clOrdID'",":","postdict","[","'clOrdID'","]","}",")","}",",","verb","=","'GET'",")","[","0","]","if","(","order","[","'orderQty'","]","!=","postdict","[","'quantity'","]","or","order","[","'price'","]","!=","postdict","[","'price'","]","or","order","[","'symbol'","]","!=","postdict","[","'symbol'","]",")",":","raise","Exception","(","'Attempted to recover from duplicate clOrdID, but order returned from API '","+","'did not match POST.\\nPOST data: %s\\nReturned order: %s'","%","(","json",".","dumps","(","postdict",")",",","json",".","dumps","(","order",")",")",")","# All good","return","order","# Unknown Error","else",":","self",".","logger",".","error","(","\"Unhandled Error: %s: %s\"","%","(","e",",","response",".","text",")",")","self",".","logger",".","error","(","\"Endpoint was: %s %s: %s\"","%","(","verb",",","api",",","json",".","dumps","(","postdict",")",")",")","maybe_exit","(","e",")","except","requests",".","exceptions",".","Timeout","as","e",":","# Timeout, re-run this request","self",".","logger",".","warning","(","\"Timed out, retrying...\"",")","return","self",".","_curl_bitmex","(","api",",","query",",","postdict",",","timeout",",","verb",")","except","requests",".","exceptions",".","ConnectionError","as","e",":","self",".","logger",".","warning","(","\"Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. \"","+","\"Request: %s \\n %s\"","%","(","url",",","json",".","dumps","(","postdict",")",")",")","sleep","(","1",")","return","self",".","_curl_bitmex","(","api",",","query",",","postdict",",","timeout",",","verb",")","return","response",".","json","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/bitmex.py#L184-L282"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"ExchangeInterface.calc_delta","parameters":"(self)","argument_list":"","return_statement":"return delta","docstring":"Calculate currency delta for portfolio","docstring_summary":"Calculate currency delta for portfolio","docstring_tokens":["Calculate","currency","delta","for","portfolio"],"function":"def calc_delta(self):\n \"\"\"Calculate currency delta for portfolio\"\"\"\n portfolio = self.get_portfolio()\n spot_delta = 0\n mark_delta = 0\n for symbol in portfolio:\n item = portfolio[symbol]\n if item['futureType'] == \"Quanto\":\n spot_delta += item['currentQty'] * item['multiplier'] * item['spot']\n mark_delta += item['currentQty'] * item['multiplier'] * item['markPrice']\n elif item['futureType'] == \"Inverse\":\n spot_delta += (item['multiplier'] \/ item['spot']) * item['currentQty']\n mark_delta += (item['multiplier'] \/ item['markPrice']) * item['currentQty']\n basis_delta = mark_delta - spot_delta\n delta = {\n \"spot\": spot_delta,\n \"mark_price\": mark_delta,\n \"basis\": basis_delta\n }\n return delta","function_tokens":["def","calc_delta","(","self",")",":","portfolio","=","self",".","get_portfolio","(",")","spot_delta","=","0","mark_delta","=","0","for","symbol","in","portfolio",":","item","=","portfolio","[","symbol","]","if","item","[","'futureType'","]","==","\"Quanto\"",":","spot_delta","+=","item","[","'currentQty'","]","*","item","[","'multiplier'","]","*","item","[","'spot'","]","mark_delta","+=","item","[","'currentQty'","]","*","item","[","'multiplier'","]","*","item","[","'markPrice'","]","elif","item","[","'futureType'","]","==","\"Inverse\"",":","spot_delta","+=","(","item","[","'multiplier'","]","\/","item","[","'spot'","]",")","*","item","[","'currentQty'","]","mark_delta","+=","(","item","[","'multiplier'","]","\/","item","[","'markPrice'","]",")","*","item","[","'currentQty'","]","basis_delta","=","mark_delta","-","spot_delta","delta","=","{","\"spot\"",":","spot_delta",",","\"mark_price\"",":","mark_delta",",","\"basis\"",":","basis_delta","}","return","delta"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L95-L114"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"ExchangeInterface.is_open","parameters":"(self)","argument_list":"","return_statement":"return not self.bitmex.ws.exited","docstring":"Check that websockets are still open.","docstring_summary":"Check that websockets are still open.","docstring_tokens":["Check","that","websockets","are","still","open","."],"function":"def is_open(self):\n \"\"\"Check that websockets are still open.\"\"\"\n return not self.bitmex.ws.exited","function_tokens":["def","is_open","(","self",")",":","return","not","self",".","bitmex",".","ws",".","exited"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L165-L167"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"ExchangeInterface.check_if_orderbook_empty","parameters":"(self)","argument_list":"","return_statement":"","docstring":"This function checks whether the order book is empty","docstring_summary":"This function checks whether the order book is empty","docstring_tokens":["This","function","checks","whether","the","order","book","is","empty"],"function":"def check_if_orderbook_empty(self):\n \"\"\"This function checks whether the order book is empty\"\"\"\n instrument = self.get_instrument()\n if instrument['midPrice'] is None:\n raise errors.MarketEmptyError(\"Orderbook is empty, cannot quote\")\n sys.exit()","function_tokens":["def","check_if_orderbook_empty","(","self",")",":","instrument","=","self",".","get_instrument","(",")","if","instrument","[","'midPrice'","]","is","None",":","raise","errors",".","MarketEmptyError","(","\"Orderbook is empty, cannot quote\"",")","sys",".","exit","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L176-L181"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.print_status","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Print the current MM status.","docstring_summary":"Print the current MM status.","docstring_tokens":["Print","the","current","MM","status","."],"function":"def print_status(self):\n \"\"\"Print the current MM status.\"\"\"\n\n margin = self.exchange.get_margin()\n position = self.exchange.get_position()\n self.running_qty = self.exchange.get_delta()\n self.start_XBt = margin[\"marginBalance\"]\n\n logger.info(\"Current XBT Balance: %.6f\" % XBt_to_XBT(self.start_XBt))\n logger.info(\"Current Contract Position: %d\" % self.running_qty)\n if settings.CHECK_POSITION_LIMITS:\n logger.info(\"Position limits: %d\/%d\" % (settings.MIN_POSITION, settings.MAX_POSITION))\n if position['currentQty'] != 0:\n logger.info(\"Avg Cost Price: %.2f\" % float(position['avgCostPrice']))\n logger.info(\"Avg Entry Price: %.2f\" % float(position['avgEntryPrice']))\n logger.info(\"Contracts Traded This Run: %d\" % (self.running_qty - self.starting_qty))\n logger.info(\"Total Contract Delta: %.4f XBT\" % self.exchange.calc_delta()['spot'])","function_tokens":["def","print_status","(","self",")",":","margin","=","self",".","exchange",".","get_margin","(",")","position","=","self",".","exchange",".","get_position","(",")","self",".","running_qty","=","self",".","exchange",".","get_delta","(",")","self",".","start_XBt","=","margin","[","\"marginBalance\"","]","logger",".","info","(","\"Current XBT Balance: %.6f\"","%","XBt_to_XBT","(","self",".","start_XBt",")",")","logger",".","info","(","\"Current Contract Position: %d\"","%","self",".","running_qty",")","if","settings",".","CHECK_POSITION_LIMITS",":","logger",".","info","(","\"Position limits: %d\/%d\"","%","(","settings",".","MIN_POSITION",",","settings",".","MAX_POSITION",")",")","if","position","[","'currentQty'","]","!=","0",":","logger",".","info","(","\"Avg Cost Price: %.2f\"","%","float","(","position","[","'avgCostPrice'","]",")",")","logger",".","info","(","\"Avg Entry Price: %.2f\"","%","float","(","position","[","'avgEntryPrice'","]",")",")","logger",".","info","(","\"Contracts Traded This Run: %d\"","%","(","self",".","running_qty","-","self",".","starting_qty",")",")","logger",".","info","(","\"Total Contract Delta: %.4f XBT\"","%","self",".","exchange",".","calc_delta","(",")","[","'spot'","]",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L232-L248"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.get_price_offset","parameters":"(self, index)","argument_list":"","return_statement":"return round(start_position * (1 + settings.INTERVAL) ** index, self.instrument['tickLog'])","docstring":"Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.\n Negative is a buy, positive is a sell.","docstring_summary":"Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.\n Negative is a buy, positive is a sell.","docstring_tokens":["Given","an","index","(","1","-","1","2","-","2","etc",".",")","return","the","price","for","that","side","of","the","book",".","Negative","is","a","buy","positive","is","a","sell","."],"function":"def get_price_offset(self, index):\n \"\"\"Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.\n Negative is a buy, positive is a sell.\"\"\"\n # Maintain existing spreads for max profit\n if settings.MAINTAIN_SPREADS:\n start_position = self.start_position_buy if index < 0 else self.start_position_sell\n # First positions (index 1, -1) should start right at start_position, others should branch from there\n index = index + 1 if index < 0 else index - 1\n else:\n # Offset mode: ticker comes from a reference exchange and we define an offset.\n start_position = self.start_position_buy if index < 0 else self.start_position_sell\n\n # If we're attempting to sell, but our sell price is actually lower than the buy,\n # move over to the sell side.\n if index > 0 and start_position < self.start_position_buy:\n start_position = self.start_position_sell\n # Same for buys.\n if index < 0 and start_position > self.start_position_sell:\n start_position = self.start_position_buy\n\n return round(start_position * (1 + settings.INTERVAL) ** index, self.instrument['tickLog'])","function_tokens":["def","get_price_offset","(","self",",","index",")",":","# Maintain existing spreads for max profit","if","settings",".","MAINTAIN_SPREADS",":","start_position","=","self",".","start_position_buy","if","index","<","0","else","self",".","start_position_sell","# First positions (index 1, -1) should start right at start_position, others should branch from there","index","=","index","+","1","if","index","<","0","else","index","-","1","else",":","# Offset mode: ticker comes from a reference exchange and we define an offset.","start_position","=","self",".","start_position_buy","if","index","<","0","else","self",".","start_position_sell","# If we're attempting to sell, but our sell price is actually lower than the buy,","# move over to the sell side.","if","index",">","0","and","start_position","<","self",".","start_position_buy",":","start_position","=","self",".","start_position_sell","# Same for buys.","if","index","<","0","and","start_position",">","self",".","start_position_sell",":","start_position","=","self",".","start_position_buy","return","round","(","start_position","*","(","1","+","settings",".","INTERVAL",")","**","index",",","self",".","instrument","[","'tickLog'","]",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L299-L319"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.place_orders","parameters":"(self)","argument_list":"","return_statement":"return self.converge_orders(buy_orders, sell_orders)","docstring":"Create order items for use in convergence.","docstring_summary":"Create order items for use in convergence.","docstring_tokens":["Create","order","items","for","use","in","convergence","."],"function":"def place_orders(self):\n \"\"\"Create order items for use in convergence.\"\"\"\n\n buy_orders = []\n sell_orders = []\n # Create orders from the outside in. This is intentional - let's say the inner order gets taken;\n # then we match orders from the outside in, ensuring the fewest number of orders are amended and only\n # a new order is created in the inside. If we did it inside-out, all orders would be amended\n # down and a new order would be created at the outside.\n if self.enough_liquidity():\n for i in reversed(range(1, settings.ORDER_PAIRS + 1)):\n if not self.long_position_limit_exceeded():\n buy_orders.append(self.prepare_order(-i))\n if not self.short_position_limit_exceeded():\n sell_orders.append(self.prepare_order(i))\n\n return self.converge_orders(buy_orders, sell_orders)","function_tokens":["def","place_orders","(","self",")",":","buy_orders","=","[","]","sell_orders","=","[","]","# Create orders from the outside in. This is intentional - let's say the inner order gets taken;","# then we match orders from the outside in, ensuring the fewest number of orders are amended and only","# a new order is created in the inside. If we did it inside-out, all orders would be amended","# down and a new order would be created at the outside.","if","self",".","enough_liquidity","(",")",":","for","i","in","reversed","(","range","(","1",",","settings",".","ORDER_PAIRS","+","1",")",")",":","if","not","self",".","long_position_limit_exceeded","(",")",":","buy_orders",".","append","(","self",".","prepare_order","(","-","i",")",")","if","not","self",".","short_position_limit_exceeded","(",")",":","sell_orders",".","append","(","self",".","prepare_order","(","i",")",")","return","self",".","converge_orders","(","buy_orders",",","sell_orders",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L325-L341"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.prepare_order","parameters":"(self, index)","argument_list":"","return_statement":"return {'price': price, 'orderQty': quantity, 'side': \"Buy\" if index < 0 else \"Sell\"}","docstring":"Create an order object.","docstring_summary":"Create an order object.","docstring_tokens":["Create","an","order","object","."],"function":"def prepare_order(self, index):\n \"\"\"Create an order object.\"\"\"\n\n if settings.RANDOM_ORDER_SIZE is True:\n quantity = random.randint(settings.MIN_ORDER_SIZE, settings.MAX_ORDER_SIZE)\n else:\n quantity = settings.ORDER_START_SIZE + ((abs(index) - 1) * settings.ORDER_STEP_SIZE)\n\n price = self.get_price_offset(index)\n\n return {'price': price, 'orderQty': quantity, 'side': \"Buy\" if index < 0 else \"Sell\"}","function_tokens":["def","prepare_order","(","self",",","index",")",":","if","settings",".","RANDOM_ORDER_SIZE","is","True",":","quantity","=","random",".","randint","(","settings",".","MIN_ORDER_SIZE",",","settings",".","MAX_ORDER_SIZE",")","else",":","quantity","=","settings",".","ORDER_START_SIZE","+","(","(","abs","(","index",")","-","1",")","*","settings",".","ORDER_STEP_SIZE",")","price","=","self",".","get_price_offset","(","index",")","return","{","'price'",":","price",",","'orderQty'",":","quantity",",","'side'",":","\"Buy\"","if","index","<","0","else","\"Sell\"","}"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L343-L353"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.converge_orders","parameters":"(self, buy_orders, sell_orders)","argument_list":"","return_statement":"","docstring":"Converge the orders we currently have in the book with what we want to be in the book.\n This involves amending any open orders and creating new ones if any have filled completely.\n We start from the closest orders outward.","docstring_summary":"Converge the orders we currently have in the book with what we want to be in the book.\n This involves amending any open orders and creating new ones if any have filled completely.\n We start from the closest orders outward.","docstring_tokens":["Converge","the","orders","we","currently","have","in","the","book","with","what","we","want","to","be","in","the","book",".","This","involves","amending","any","open","orders","and","creating","new","ones","if","any","have","filled","completely",".","We","start","from","the","closest","orders","outward","."],"function":"def converge_orders(self, buy_orders, sell_orders):\n \"\"\"Converge the orders we currently have in the book with what we want to be in the book.\n This involves amending any open orders and creating new ones if any have filled completely.\n We start from the closest orders outward.\"\"\"\n\n tickLog = self.exchange.get_instrument()['tickLog']\n to_amend = []\n to_create = []\n to_cancel = []\n buys_matched = 0\n sells_matched = 0\n existing_orders = self.exchange.get_orders()\n\n # Check all existing orders and match them up with what we want to place.\n # If there's an open one, we might be able to amend it to fit what we want.\n for order in existing_orders:\n try:\n if order['side'] == 'Buy':\n desired_order = buy_orders[buys_matched]\n buys_matched += 1\n else:\n desired_order = sell_orders[sells_matched]\n sells_matched += 1\n\n # Found an existing order. Do we need to amend it?\n if desired_order['orderQty'] != order['leavesQty'] or (\n # If price has changed, and the change is more than our RELIST_INTERVAL, amend.\n desired_order['price'] != order['price'] and\n abs((desired_order['price'] \/ order['price']) - 1) > settings.RELIST_INTERVAL):\n to_amend.append({'orderID': order['orderID'], 'leavesQty': desired_order['orderQty'],\n 'price': desired_order['price'], 'side': order['side']})\n except IndexError:\n # Will throw if there isn't a desired order to match. In that case, cancel it.\n to_cancel.append(order)\n\n while buys_matched < len(buy_orders):\n to_create.append(buy_orders[buys_matched])\n buys_matched += 1\n\n while sells_matched < len(sell_orders):\n to_create.append(sell_orders[sells_matched])\n sells_matched += 1\n\n if len(to_amend) > 0:\n for amended_order in reversed(to_amend):\n reference_order = [o for o in existing_orders if o['orderID'] == amended_order['orderID']][0]\n logger.info(\"Amending %4s: %d @ %.*f to %d @ %.*f (%+.*f)\" % (\n amended_order['side'],\n reference_order['leavesQty'], tickLog, reference_order['price'],\n amended_order['leavesQty'], tickLog, amended_order['price'],\n tickLog, (amended_order['price'] - reference_order['price'])\n ))\n # This can fail if an order has closed in the time we were processing.\n # The API will send us `invalid ordStatus`, which means that the order's status (Filled\/Canceled)\n # made it not amendable.\n # If that happens, we need to catch it and re-tick.\n try:\n self.exchange.amend_bulk_orders(to_amend)\n except requests.exceptions.HTTPError as e:\n errorObj = e.response.json()\n if errorObj['error']['message'] == 'Invalid ordStatus':\n logger.warn(\"Amending failed. Waiting for order data to converge and retrying.\")\n sleep(0.5)\n return self.place_orders()\n else:\n logger.error(\"Unknown error on amend: %s. Exiting\" % errorObj)\n sys.exit(1)\n\n if len(to_create) > 0:\n logger.info(\"Creating %d orders:\" % (len(to_create)))\n for order in reversed(to_create):\n logger.info(\"%4s %d @ %.*f\" % (order['side'], order['orderQty'], tickLog, order['price']))\n self.exchange.create_bulk_orders(to_create)\n\n # Could happen if we exceed a delta limit\n if len(to_cancel) > 0:\n logger.info(\"Canceling %d orders:\" % (len(to_cancel)))\n for order in reversed(to_cancel):\n logger.info(\"%4s %d @ %.*f\" % (order['side'], order['leavesQty'], tickLog, order['price']))\n self.exchange.cancel_bulk_orders(to_cancel)","function_tokens":["def","converge_orders","(","self",",","buy_orders",",","sell_orders",")",":","tickLog","=","self",".","exchange",".","get_instrument","(",")","[","'tickLog'","]","to_amend","=","[","]","to_create","=","[","]","to_cancel","=","[","]","buys_matched","=","0","sells_matched","=","0","existing_orders","=","self",".","exchange",".","get_orders","(",")","# Check all existing orders and match them up with what we want to place.","# If there's an open one, we might be able to amend it to fit what we want.","for","order","in","existing_orders",":","try",":","if","order","[","'side'","]","==","'Buy'",":","desired_order","=","buy_orders","[","buys_matched","]","buys_matched","+=","1","else",":","desired_order","=","sell_orders","[","sells_matched","]","sells_matched","+=","1","# Found an existing order. Do we need to amend it?","if","desired_order","[","'orderQty'","]","!=","order","[","'leavesQty'","]","or","(","# If price has changed, and the change is more than our RELIST_INTERVAL, amend.","desired_order","[","'price'","]","!=","order","[","'price'","]","and","abs","(","(","desired_order","[","'price'","]","\/","order","[","'price'","]",")","-","1",")",">","settings",".","RELIST_INTERVAL",")",":","to_amend",".","append","(","{","'orderID'",":","order","[","'orderID'","]",",","'leavesQty'",":","desired_order","[","'orderQty'","]",",","'price'",":","desired_order","[","'price'","]",",","'side'",":","order","[","'side'","]","}",")","except","IndexError",":","# Will throw if there isn't a desired order to match. In that case, cancel it.","to_cancel",".","append","(","order",")","while","buys_matched","<","len","(","buy_orders",")",":","to_create",".","append","(","buy_orders","[","buys_matched","]",")","buys_matched","+=","1","while","sells_matched","<","len","(","sell_orders",")",":","to_create",".","append","(","sell_orders","[","sells_matched","]",")","sells_matched","+=","1","if","len","(","to_amend",")",">","0",":","for","amended_order","in","reversed","(","to_amend",")",":","reference_order","=","[","o","for","o","in","existing_orders","if","o","[","'orderID'","]","==","amended_order","[","'orderID'","]","]","[","0","]","logger",".","info","(","\"Amending %4s: %d @ %.*f to %d @ %.*f (%+.*f)\"","%","(","amended_order","[","'side'","]",",","reference_order","[","'leavesQty'","]",",","tickLog",",","reference_order","[","'price'","]",",","amended_order","[","'leavesQty'","]",",","tickLog",",","amended_order","[","'price'","]",",","tickLog",",","(","amended_order","[","'price'","]","-","reference_order","[","'price'","]",")",")",")","# This can fail if an order has closed in the time we were processing.","# The API will send us `invalid ordStatus`, which means that the order's status (Filled\/Canceled)","# made it not amendable.","# If that happens, we need to catch it and re-tick.","try",":","self",".","exchange",".","amend_bulk_orders","(","to_amend",")","except","requests",".","exceptions",".","HTTPError","as","e",":","errorObj","=","e",".","response",".","json","(",")","if","errorObj","[","'error'","]","[","'message'","]","==","'Invalid ordStatus'",":","logger",".","warn","(","\"Amending failed. Waiting for order data to converge and retrying.\"",")","sleep","(","0.5",")","return","self",".","place_orders","(",")","else",":","logger",".","error","(","\"Unknown error on amend: %s. Exiting\"","%","errorObj",")","sys",".","exit","(","1",")","if","len","(","to_create",")",">","0",":","logger",".","info","(","\"Creating %d orders:\"","%","(","len","(","to_create",")",")",")","for","order","in","reversed","(","to_create",")",":","logger",".","info","(","\"%4s %d @ %.*f\"","%","(","order","[","'side'","]",",","order","[","'orderQty'","]",",","tickLog",",","order","[","'price'","]",")",")","self",".","exchange",".","create_bulk_orders","(","to_create",")","# Could happen if we exceed a delta limit","if","len","(","to_cancel",")",">","0",":","logger",".","info","(","\"Canceling %d orders:\"","%","(","len","(","to_cancel",")",")",")","for","order","in","reversed","(","to_cancel",")",":","logger",".","info","(","\"%4s %d @ %.*f\"","%","(","order","[","'side'","]",",","order","[","'leavesQty'","]",",","tickLog",",","order","[","'price'","]",")",")","self",".","exchange",".","cancel_bulk_orders","(","to_cancel",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L355-L434"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.short_position_limit_exceeded","parameters":"(self)","argument_list":"","return_statement":"return position <= settings.MIN_POSITION","docstring":"Returns True if the short position limit is exceeded","docstring_summary":"Returns True if the short position limit is exceeded","docstring_tokens":["Returns","True","if","the","short","position","limit","is","exceeded"],"function":"def short_position_limit_exceeded(self):\n \"Returns True if the short position limit is exceeded\"\n if not settings.CHECK_POSITION_LIMITS:\n return False\n position = self.exchange.get_delta()\n return position <= settings.MIN_POSITION","function_tokens":["def","short_position_limit_exceeded","(","self",")",":","if","not","settings",".","CHECK_POSITION_LIMITS",":","return","False","position","=","self",".","exchange",".","get_delta","(",")","return","position","<=","settings",".","MIN_POSITION"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L440-L445"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.long_position_limit_exceeded","parameters":"(self)","argument_list":"","return_statement":"return position >= settings.MAX_POSITION","docstring":"Returns True if the long position limit is exceeded","docstring_summary":"Returns True if the long position limit is exceeded","docstring_tokens":["Returns","True","if","the","long","position","limit","is","exceeded"],"function":"def long_position_limit_exceeded(self):\n \"Returns True if the long position limit is exceeded\"\n if not settings.CHECK_POSITION_LIMITS:\n return False\n position = self.exchange.get_delta()\n return position >= settings.MAX_POSITION","function_tokens":["def","long_position_limit_exceeded","(","self",")",":","if","not","settings",".","CHECK_POSITION_LIMITS",":","return","False","position","=","self",".","exchange",".","get_delta","(",")","return","position",">=","settings",".","MAX_POSITION"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L447-L452"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.enough_liquidity","parameters":"(self)","argument_list":"","return_statement":"return enough_liquidity","docstring":"Returns true if there is enough liquidity on each side of the order book","docstring_summary":"Returns true if there is enough liquidity on each side of the order book","docstring_tokens":["Returns","true","if","there","is","enough","liquidity","on","each","side","of","the","order","book"],"function":"def enough_liquidity(self):\n \"Returns true if there is enough liquidity on each side of the order book\"\n enough_liquidity = False\n ticker = self.exchange.get_ticker()\n order_book = self.exchange.market_depth()\n highest_buy = self.exchange.get_highest_buy()\n lowest_sell = self.exchange.get_lowest_sell()\n\n bid_depth = sum([x[\"bidSize\"] for x in filter(lambda x: x[\"bidSize\"]!=None, order_book)])\n ask_depth = sum([x[\"askSize\"] for x in filter(lambda x: x[\"askSize\"]!=None, order_book)])\n\n bid_liquid = bid_depth - highest_buy[\"orderQty\"]\n logger.info(\"Bid Liquidity: \"+str(bid_liquid)+\" Contracts\")\n ask_liquid = ask_depth - lowest_sell[\"orderQty\"]\n logger.info(\"Ask Liquidity: \"+str(ask_liquid)+\" Contracts\")\n enough_ask_liquidity = ask_liquid >= settings.MIN_CONTRACTS\n enough_bid_liquidity = bid_liquid >= settings.MIN_CONTRACTS\n enough_liquidity = (enough_ask_liquidity and enough_bid_liquidity)\n if not enough_liquidity:\n if (not enough_bid_liquidity) and (not enough_ask_liquidity):\n logger.info(\"Neither side has enough liquidity\")\n elif not enough_bid_liquidity:\n logger.info(\"Bid side is not liquid enough\")\n else:\n logger.info(\"Ask side is not liquid enough\")\n return enough_liquidity","function_tokens":["def","enough_liquidity","(","self",")",":","enough_liquidity","=","False","ticker","=","self",".","exchange",".","get_ticker","(",")","order_book","=","self",".","exchange",".","market_depth","(",")","highest_buy","=","self",".","exchange",".","get_highest_buy","(",")","lowest_sell","=","self",".","exchange",".","get_lowest_sell","(",")","bid_depth","=","sum","(","[","x","[","\"bidSize\"","]","for","x","in","filter","(","lambda","x",":","x","[","\"bidSize\"","]","!=","None",",","order_book",")","]",")","ask_depth","=","sum","(","[","x","[","\"askSize\"","]","for","x","in","filter","(","lambda","x",":","x","[","\"askSize\"","]","!=","None",",","order_book",")","]",")","bid_liquid","=","bid_depth","-","highest_buy","[","\"orderQty\"","]","logger",".","info","(","\"Bid Liquidity: \"","+","str","(","bid_liquid",")","+","\" Contracts\"",")","ask_liquid","=","ask_depth","-","lowest_sell","[","\"orderQty\"","]","logger",".","info","(","\"Ask Liquidity: \"","+","str","(","ask_liquid",")","+","\" Contracts\"",")","enough_ask_liquidity","=","ask_liquid",">=","settings",".","MIN_CONTRACTS","enough_bid_liquidity","=","bid_liquid",">=","settings",".","MIN_CONTRACTS","enough_liquidity","=","(","enough_ask_liquidity","and","enough_bid_liquidity",")","if","not","enough_liquidity",":","if","(","not","enough_bid_liquidity",")","and","(","not","enough_ask_liquidity",")",":","logger",".","info","(","\"Neither side has enough liquidity\"",")","elif","not","enough_bid_liquidity",":","logger",".","info","(","\"Bid side is not liquid enough\"",")","else",":","logger",".","info","(","\"Ask side is not liquid enough\"",")","return","enough_liquidity"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L457-L482"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.sanity_check","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Perform checks before placing orders.","docstring_summary":"Perform checks before placing orders.","docstring_tokens":["Perform","checks","before","placing","orders","."],"function":"def sanity_check(self):\n \"\"\"Perform checks before placing orders.\"\"\"\n\n # Check if OB is empty - if so, can't quote.\n self.exchange.check_if_orderbook_empty()\n\n # Ensure market is still open.\n self.exchange.check_market_open()\n\n # Get ticker, which sets price offsets and prints some debugging info.\n ticker = self.get_ticker()\n\n # Sanity check:\n if self.get_price_offset(-1) >= ticker[\"sell\"] or self.get_price_offset(1) <= ticker[\"buy\"]:\n logger.error(self.start_position_buy, self.start_position_sell)\n logger.error(\"%s %s %s %s\" % (self.get_price_offset(-1), ticker[\"sell\"], self.get_price_offset(1), ticker[\"buy\"]))\n logger.error(\"Sanity check failed, exchange data is inconsistent\")\n sys.exit()\n\n # Messanging if the position limits are reached\n if self.long_position_limit_exceeded():\n logger.info(\"Long delta limit exceeded\")\n logger.info(\"Current Position: %.f, Maximum Position: %.f\" %\n (self.exchange.get_delta(), settings.MAX_POSITION))\n\n if self.short_position_limit_exceeded():\n logger.info(\"Short delta limit exceeded\")\n logger.info(\"Current Position: %.f, Minimum Position: %.f\" %\n (self.exchange.get_delta(), settings.MIN_POSITION))","function_tokens":["def","sanity_check","(","self",")",":","# Check if OB is empty - if so, can't quote.","self",".","exchange",".","check_if_orderbook_empty","(",")","# Ensure market is still open.","self",".","exchange",".","check_market_open","(",")","# Get ticker, which sets price offsets and prints some debugging info.","ticker","=","self",".","get_ticker","(",")","# Sanity check:","if","self",".","get_price_offset","(","-","1",")",">=","ticker","[","\"sell\"","]","or","self",".","get_price_offset","(","1",")","<=","ticker","[","\"buy\"","]",":","logger",".","error","(","self",".","start_position_buy",",","self",".","start_position_sell",")","logger",".","error","(","\"%s %s %s %s\"","%","(","self",".","get_price_offset","(","-","1",")",",","ticker","[","\"sell\"","]",",","self",".","get_price_offset","(","1",")",",","ticker","[","\"buy\"","]",")",")","logger",".","error","(","\"Sanity check failed, exchange data is inconsistent\"",")","sys",".","exit","(",")","# Messanging if the position limits are reached","if","self",".","long_position_limit_exceeded","(",")",":","logger",".","info","(","\"Long delta limit exceeded\"",")","logger",".","info","(","\"Current Position: %.f, Maximum Position: %.f\"","%","(","self",".","exchange",".","get_delta","(",")",",","settings",".","MAX_POSITION",")",")","if","self",".","short_position_limit_exceeded","(",")",":","logger",".","info","(","\"Short delta limit exceeded\"",")","logger",".","info","(","\"Current Position: %.f, Minimum Position: %.f\"","%","(","self",".","exchange",".","get_delta","(",")",",","settings",".","MIN_POSITION",")",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L488-L516"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.check_file_change","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Restart if any files we're watching have changed.","docstring_summary":"Restart if any files we're watching have changed.","docstring_tokens":["Restart","if","any","files","we","re","watching","have","changed","."],"function":"def check_file_change(self):\n \"\"\"Restart if any files we're watching have changed.\"\"\"\n for f, mtime in watched_files_mtimes:\n if getmtime(f) > mtime:\n self.restart()","function_tokens":["def","check_file_change","(","self",")",":","for","f",",","mtime","in","watched_files_mtimes",":","if","getmtime","(","f",")",">","mtime",":","self",".","restart","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L522-L526"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/market_maker.py","language":"python","identifier":"OrderManager.check_connection","parameters":"(self)","argument_list":"","return_statement":"return self.exchange.is_open()","docstring":"Ensure the WS connections are still open.","docstring_summary":"Ensure the WS connections are still open.","docstring_tokens":["Ensure","the","WS","connections","are","still","open","."],"function":"def check_connection(self):\n \"\"\"Ensure the WS connections are still open.\"\"\"\n return self.exchange.is_open()","function_tokens":["def","check_connection","(","self",")",":","return","self",".","exchange",".","is_open","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/market_maker.py#L528-L530"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/settings.py","language":"python","identifier":"import_path","parameters":"(fullpath)","argument_list":"","return_statement":"return module","docstring":"Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do.","docstring_summary":"Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do.","docstring_tokens":["Import","a","file","with","full","path","specification",".","Allows","one","to","import","from","anywhere","something","__import__","does","not","do","."],"function":"def import_path(fullpath):\n \"\"\"\n Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do.\n \"\"\"\n path, filename = os.path.split(fullpath)\n filename, ext = os.path.splitext(filename)\n sys.path.insert(0, path)\n module = __import__(filename)\n reload(module) # Might be out of date\n del sys.path[0]\n return module","function_tokens":["def","import_path","(","fullpath",")",":","path",",","filename","=","os",".","path",".","split","(","fullpath",")","filename",",","ext","=","os",".","path",".","splitext","(","filename",")","sys",".","path",".","insert","(","0",",","path",")","module","=","__import__","(","filename",")","reload","(","module",")","# Might be out of date","del","sys",".","path","[","0","]","return","module"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/settings.py#L9-L20"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.connect","parameters":"(self, endpoint=\"\", symbol=\"XBTN15\", shouldAuth=True)","argument_list":"","return_statement":"","docstring":"Connect to the websocket and initialize data stores.","docstring_summary":"Connect to the websocket and initialize data stores.","docstring_tokens":["Connect","to","the","websocket","and","initialize","data","stores","."],"function":"def connect(self, endpoint=\"\", symbol=\"XBTN15\", shouldAuth=True):\n '''Connect to the websocket and initialize data stores.'''\n\n self.logger.debug(\"Connecting WebSocket.\")\n self.symbol = symbol\n self.shouldAuth = shouldAuth\n\n # We can subscribe right in the connection querystring, so let's build that.\n # Subscribe to all pertinent endpoints\n subscriptions = [sub + ':' + symbol for sub in [\"quote\", \"trade\", \"orderBook25\"]]\n subscriptions += [\"instrument\"] # We want all of them\n if self.shouldAuth:\n subscriptions += [sub + ':' + symbol for sub in [\"order\", \"execution\"]]\n subscriptions += [\"margin\", \"position\"]\n\n # Get WS URL and connect.\n urlParts = list(urlparse(endpoint))\n urlParts[0] = urlParts[0].replace('http', 'ws')\n urlParts[2] = \"\/realtime?subscribe=\" + \",\".join(subscriptions)\n wsURL = urlunparse(urlParts)\n self.logger.info(\"Connecting to %s\" % wsURL)\n self.__connect(wsURL)\n self.logger.info('Connected to WS. Waiting for data images, this may take a moment...')\n\n # Connected. Wait for partials\n self.__wait_for_symbol(symbol)\n if self.shouldAuth:\n self.__wait_for_account()\n self.logger.info('Got all market data. Starting.')","function_tokens":["def","connect","(","self",",","endpoint","=","\"\"",",","symbol","=","\"XBTN15\"",",","shouldAuth","=","True",")",":","self",".","logger",".","debug","(","\"Connecting WebSocket.\"",")","self",".","symbol","=","symbol","self",".","shouldAuth","=","shouldAuth","# We can subscribe right in the connection querystring, so let's build that.","# Subscribe to all pertinent endpoints","subscriptions","=","[","sub","+","':'","+","symbol","for","sub","in","[","\"quote\"",",","\"trade\"",",","\"orderBook25\"","]","]","subscriptions","+=","[","\"instrument\"","]","# We want all of them","if","self",".","shouldAuth",":","subscriptions","+=","[","sub","+","':'","+","symbol","for","sub","in","[","\"order\"",",","\"execution\"","]","]","subscriptions","+=","[","\"margin\"",",","\"position\"","]","# Get WS URL and connect.","urlParts","=","list","(","urlparse","(","endpoint",")",")","urlParts","[","0","]","=","urlParts","[","0","]",".","replace","(","'http'",",","'ws'",")","urlParts","[","2","]","=","\"\/realtime?subscribe=\"","+","\",\"",".","join","(","subscriptions",")","wsURL","=","urlunparse","(","urlParts",")","self",".","logger",".","info","(","\"Connecting to %s\"","%","wsURL",")","self",".","__connect","(","wsURL",")","self",".","logger",".","info","(","'Connected to WS. Waiting for data images, this may take a moment...'",")","# Connected. Wait for partials","self",".","__wait_for_symbol","(","symbol",")","if","self",".","shouldAuth",":","self",".","__wait_for_account","(",")","self",".","logger",".","info","(","'Got all market data. Starting.'",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L34-L62"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.get_ticker","parameters":"(self, symbol)","argument_list":"","return_statement":"return {k: round(float(v or 0), instrument['tickLog']) for k, v in iteritems(ticker)}","docstring":"Return a ticker object. Generated from instrument.","docstring_summary":"Return a ticker object. Generated from instrument.","docstring_tokens":["Return","a","ticker","object",".","Generated","from","instrument","."],"function":"def get_ticker(self, symbol):\n '''Return a ticker object. Generated from instrument.'''\n\n instrument = self.get_instrument(symbol)\n\n # If this is an index, we have to get the data from the last trade.\n if instrument['symbol'][0] == '.':\n ticker = {}\n ticker['mid'] = ticker['buy'] = ticker['sell'] = ticker['last'] = instrument['markPrice']\n # Normal instrument\n else:\n bid = instrument['bidPrice'] or instrument['lastPrice']\n ask = instrument['askPrice'] or instrument['lastPrice']\n ticker = {\n \"last\": instrument['lastPrice'],\n \"buy\": bid,\n \"sell\": ask,\n \"mid\": (bid + ask) \/ 2\n }\n\n # The instrument has a tickSize. Use it to round values.\n return {k: round(float(v or 0), instrument['tickLog']) for k, v in iteritems(ticker)}","function_tokens":["def","get_ticker","(","self",",","symbol",")",":","instrument","=","self",".","get_instrument","(","symbol",")","# If this is an index, we have to get the data from the last trade.","if","instrument","[","'symbol'","]","[","0","]","==","'.'",":","ticker","=","{","}","ticker","[","'mid'","]","=","ticker","[","'buy'","]","=","ticker","[","'sell'","]","=","ticker","[","'last'","]","=","instrument","[","'markPrice'","]","# Normal instrument","else",":","bid","=","instrument","[","'bidPrice'","]","or","instrument","[","'lastPrice'","]","ask","=","instrument","[","'askPrice'","]","or","instrument","[","'lastPrice'","]","ticker","=","{","\"last\"",":","instrument","[","'lastPrice'","]",",","\"buy\"",":","bid",",","\"sell\"",":","ask",",","\"mid\"",":","(","bid","+","ask",")","\/","2","}","# The instrument has a tickSize. Use it to round values.","return","{","k",":","round","(","float","(","v","or","0",")",",","instrument","[","'tickLog'","]",")","for","k",",","v","in","iteritems","(","ticker",")","}"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L78-L99"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__connect","parameters":"(self, wsURL)","argument_list":"","return_statement":"","docstring":"Connect to the websocket in a thread.","docstring_summary":"Connect to the websocket in a thread.","docstring_tokens":["Connect","to","the","websocket","in","a","thread","."],"function":"def __connect(self, wsURL):\n '''Connect to the websocket in a thread.'''\n self.logger.debug(\"Starting thread\")\n\n self.ws = websocket.WebSocketApp(wsURL,\n on_message=self.__on_message,\n on_close=self.__on_close,\n on_open=self.__on_open,\n on_error=self.__on_error,\n # We can login using email\/pass or API key\n header=self.__get_auth())\n\n self.wst = threading.Thread(target=lambda: self.ws.run_forever())\n self.wst.daemon = True\n self.wst.start()\n self.logger.info(\"Started thread\")\n\n # Wait for connect before continuing\n conn_timeout = 5\n while (not self.ws.sock or not self.ws.sock.connected) and conn_timeout and not self._error:\n sleep(1)\n conn_timeout -= 1\n\n if not conn_timeout or self._error:\n self.logger.error(\"Couldn't connect to WS! Exiting.\")\n self.exit()\n sys.exit(1)","function_tokens":["def","__connect","(","self",",","wsURL",")",":","self",".","logger",".","debug","(","\"Starting thread\"",")","self",".","ws","=","websocket",".","WebSocketApp","(","wsURL",",","on_message","=","self",".","__on_message",",","on_close","=","self",".","__on_close",",","on_open","=","self",".","__on_open",",","on_error","=","self",".","__on_error",",","# We can login using email\/pass or API key","header","=","self",".","__get_auth","(",")",")","self",".","wst","=","threading",".","Thread","(","target","=","lambda",":","self",".","ws",".","run_forever","(",")",")","self",".","wst",".","daemon","=","True","self",".","wst",".","start","(",")","self",".","logger",".","info","(","\"Started thread\"",")","# Wait for connect before continuing","conn_timeout","=","5","while","(","not","self",".","ws",".","sock","or","not","self",".","ws",".","sock",".","connected",")","and","conn_timeout","and","not","self",".","_error",":","sleep","(","1",")","conn_timeout","-=","1","if","not","conn_timeout","or","self",".","_error",":","self",".","logger",".","error","(","\"Couldn't connect to WS! Exiting.\"",")","self",".","exit","(",")","sys",".","exit","(","1",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L140-L166"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__get_auth","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Return auth headers. Will use API Keys if present in settings.","docstring_summary":"Return auth headers. Will use API Keys if present in settings.","docstring_tokens":["Return","auth","headers",".","Will","use","API","Keys","if","present","in","settings","."],"function":"def __get_auth(self):\n '''Return auth headers. Will use API Keys if present in settings.'''\n\n if self.shouldAuth is False:\n return []\n\n if not settings.API_KEY:\n self.logger.info(\"Authenticating with email\/password.\")\n return [\n \"email: \" + settings.LOGIN,\n \"password: \" + settings.PASSWORD\n ]\n else:\n self.logger.info(\"Authenticating with API Key.\")\n # To auth to the WS using an API key, we generate a signature of a nonce and\n # the WS API endpoint.\n nonce = generate_nonce()\n return [\n \"api-nonce: \" + str(nonce),\n \"api-signature: \" + generate_signature(settings.API_SECRET, 'GET', '\/realtime', nonce, ''),\n \"api-key:\" + settings.API_KEY\n ]","function_tokens":["def","__get_auth","(","self",")",":","if","self",".","shouldAuth","is","False",":","return","[","]","if","not","settings",".","API_KEY",":","self",".","logger",".","info","(","\"Authenticating with email\/password.\"",")","return","[","\"email: \"","+","settings",".","LOGIN",",","\"password: \"","+","settings",".","PASSWORD","]","else",":","self",".","logger",".","info","(","\"Authenticating with API Key.\"",")","# To auth to the WS using an API key, we generate a signature of a nonce and","# the WS API endpoint.","nonce","=","generate_nonce","(",")","return","[","\"api-nonce: \"","+","str","(","nonce",")",",","\"api-signature: \"","+","generate_signature","(","settings",".","API_SECRET",",","'GET'",",","'\/realtime'",",","nonce",",","''",")",",","\"api-key:\"","+","settings",".","API_KEY","]"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L168-L189"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__wait_for_account","parameters":"(self)","argument_list":"","return_statement":"","docstring":"On subscribe, this data will come down. Wait for it.","docstring_summary":"On subscribe, this data will come down. Wait for it.","docstring_tokens":["On","subscribe","this","data","will","come","down",".","Wait","for","it","."],"function":"def __wait_for_account(self):\n '''On subscribe, this data will come down. Wait for it.'''\n # Wait for the keys to show up from the ws\n while not {'margin', 'position', 'order'} <= set(self.data):\n sleep(0.1)","function_tokens":["def","__wait_for_account","(","self",")",":","# Wait for the keys to show up from the ws","while","not","{","'margin'",",","'position'",",","'order'","}","<=","set","(","self",".","data",")",":","sleep","(","0.1",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L191-L195"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__wait_for_symbol","parameters":"(self, symbol)","argument_list":"","return_statement":"","docstring":"On subscribe, this data will come down. Wait for it.","docstring_summary":"On subscribe, this data will come down. Wait for it.","docstring_tokens":["On","subscribe","this","data","will","come","down",".","Wait","for","it","."],"function":"def __wait_for_symbol(self, symbol):\n '''On subscribe, this data will come down. Wait for it.'''\n while not {'instrument', 'trade', 'quote'} <= set(self.data):\n sleep(0.1)","function_tokens":["def","__wait_for_symbol","(","self",",","symbol",")",":","while","not","{","'instrument'",",","'trade'",",","'quote'","}","<=","set","(","self",".","data",")",":","sleep","(","0.1",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L197-L200"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__send_command","parameters":"(self, command, args=[])","argument_list":"","return_statement":"","docstring":"Send a raw command.","docstring_summary":"Send a raw command.","docstring_tokens":["Send","a","raw","command","."],"function":"def __send_command(self, command, args=[]):\n '''Send a raw command.'''\n self.ws.send(json.dumps({\"op\": command, \"args\": args}))","function_tokens":["def","__send_command","(","self",",","command",",","args","=","[","]",")",":","self",".","ws",".","send","(","json",".","dumps","(","{","\"op\"",":","command",",","\"args\"",":","args","}",")",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L202-L204"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/ws\/ws_thread.py","language":"python","identifier":"BitMEXWebsocket.__on_message","parameters":"(self, ws, message)","argument_list":"","return_statement":"","docstring":"Handler for parsing WS messages.","docstring_summary":"Handler for parsing WS messages.","docstring_tokens":["Handler","for","parsing","WS","messages","."],"function":"def __on_message(self, ws, message):\n '''Handler for parsing WS messages.'''\n message = json.loads(message)\n self.logger.debug(json.dumps(message))\n\n table = message['table'] if 'table' in message else None\n action = message['action'] if 'action' in message else None\n try:\n if 'subscribe' in message:\n if message['success']:\n self.logger.debug(\"Subscribed to %s.\" % message['subscribe'])\n else:\n self.error(\"Unable to subscribe to %s. Error: \\\"%s\\\" Please check and restart.\" %\n (message['request']['args'][0], message['error']))\n elif 'status' in message:\n if message['status'] == 400:\n self.error(message['error'])\n if message['status'] == 401:\n self.error(\"API Key incorrect, please check and restart.\")\n elif action:\n\n if table not in self.data:\n self.data[table] = []\n\n if table not in self.keys:\n self.keys[table] = []\n\n # There are four possible actions from the WS:\n # 'partial' - full table image\n # 'insert' - new row\n # 'update' - update row\n # 'delete' - delete row\n if action == 'partial':\n self.logger.debug(\"%s: partial\" % table)\n self.data[table] += message['data']\n # Keys are communicated on partials to let you know how to uniquely identify\n # an item. We use it for updates.\n self.keys[table] = message['keys']\n elif action == 'insert':\n self.logger.debug('%s: inserting %s' % (table, message['data']))\n self.data[table] += message['data']\n\n # Limit the max length of the table to avoid excessive memory usage.\n # Don't trim orders because we'll lose valuable state if we do.\n if table != 'order' and len(self.data[table]) > BitMEXWebsocket.MAX_TABLE_LEN:\n self.data[table] = self.data[table][(BitMEXWebsocket.MAX_TABLE_LEN \/\/ 2):]\n\n elif action == 'update':\n self.logger.debug('%s: updating %s' % (table, message['data']))\n # Locate the item in the collection and update it.\n for updateData in message['data']:\n item = findItemByKeys(self.keys[table], self.data[table], updateData)\n if not item:\n return # No item found to update. Could happen before push\n\n # Log executions\n is_canceled = 'ordStatus' in updateData and updateData['ordStatus'] == 'Canceled'\n if table == 'order' and 'leavesQty' in updateData and not is_canceled:\n instrument = self.get_instrument(item['symbol'])\n contExecuted = abs(item['leavesQty'] - updateData['leavesQty'])\n self.logger.info(\"Execution: %s %d Contracts of %s at %.*f\" %\n (item['side'], contExecuted, item['symbol'],\n instrument['tickLog'], item['price']))\n\n item.update(updateData)\n # Remove cancelled \/ filled orders\n if table == 'order' and item['leavesQty'] <= 0:\n self.data[table].remove(item)\n elif action == 'delete':\n self.logger.debug('%s: deleting %s' % (table, message['data']))\n # Locate the item in the collection and remove it.\n for deleteData in message['data']:\n item = findItemByKeys(self.keys[table], self.data[table], deleteData)\n self.data[table].remove(item)\n else:\n raise Exception(\"Unknown action: %s\" % action)\n except:\n self.logger.error(traceback.format_exc())","function_tokens":["def","__on_message","(","self",",","ws",",","message",")",":","message","=","json",".","loads","(","message",")","self",".","logger",".","debug","(","json",".","dumps","(","message",")",")","table","=","message","[","'table'","]","if","'table'","in","message","else","None","action","=","message","[","'action'","]","if","'action'","in","message","else","None","try",":","if","'subscribe'","in","message",":","if","message","[","'success'","]",":","self",".","logger",".","debug","(","\"Subscribed to %s.\"","%","message","[","'subscribe'","]",")","else",":","self",".","error","(","\"Unable to subscribe to %s. Error: \\\"%s\\\" Please check and restart.\"","%","(","message","[","'request'","]","[","'args'","]","[","0","]",",","message","[","'error'","]",")",")","elif","'status'","in","message",":","if","message","[","'status'","]","==","400",":","self",".","error","(","message","[","'error'","]",")","if","message","[","'status'","]","==","401",":","self",".","error","(","\"API Key incorrect, please check and restart.\"",")","elif","action",":","if","table","not","in","self",".","data",":","self",".","data","[","table","]","=","[","]","if","table","not","in","self",".","keys",":","self",".","keys","[","table","]","=","[","]","# There are four possible actions from the WS:","# 'partial' - full table image","# 'insert' - new row","# 'update' - update row","# 'delete' - delete row","if","action","==","'partial'",":","self",".","logger",".","debug","(","\"%s: partial\"","%","table",")","self",".","data","[","table","]","+=","message","[","'data'","]","# Keys are communicated on partials to let you know how to uniquely identify","# an item. We use it for updates.","self",".","keys","[","table","]","=","message","[","'keys'","]","elif","action","==","'insert'",":","self",".","logger",".","debug","(","'%s: inserting %s'","%","(","table",",","message","[","'data'","]",")",")","self",".","data","[","table","]","+=","message","[","'data'","]","# Limit the max length of the table to avoid excessive memory usage.","# Don't trim orders because we'll lose valuable state if we do.","if","table","!=","'order'","and","len","(","self",".","data","[","table","]",")",">","BitMEXWebsocket",".","MAX_TABLE_LEN",":","self",".","data","[","table","]","=","self",".","data","[","table","]","[","(","BitMEXWebsocket",".","MAX_TABLE_LEN","\/\/","2",")",":","]","elif","action","==","'update'",":","self",".","logger",".","debug","(","'%s: updating %s'","%","(","table",",","message","[","'data'","]",")",")","# Locate the item in the collection and update it.","for","updateData","in","message","[","'data'","]",":","item","=","findItemByKeys","(","self",".","keys","[","table","]",",","self",".","data","[","table","]",",","updateData",")","if","not","item",":","return","# No item found to update. Could happen before push","# Log executions","is_canceled","=","'ordStatus'","in","updateData","and","updateData","[","'ordStatus'","]","==","'Canceled'","if","table","==","'order'","and","'leavesQty'","in","updateData","and","not","is_canceled",":","instrument","=","self",".","get_instrument","(","item","[","'symbol'","]",")","contExecuted","=","abs","(","item","[","'leavesQty'","]","-","updateData","[","'leavesQty'","]",")","self",".","logger",".","info","(","\"Execution: %s %d Contracts of %s at %.*f\"","%","(","item","[","'side'","]",",","contExecuted",",","item","[","'symbol'","]",",","instrument","[","'tickLog'","]",",","item","[","'price'","]",")",")","item",".","update","(","updateData",")","# Remove cancelled \/ filled orders","if","table","==","'order'","and","item","[","'leavesQty'","]","<=","0",":","self",".","data","[","table","]",".","remove","(","item",")","elif","action","==","'delete'",":","self",".","logger",".","debug","(","'%s: deleting %s'","%","(","table",",","message","[","'data'","]",")",")","# Locate the item in the collection and remove it.","for","deleteData","in","message","[","'data'","]",":","item","=","findItemByKeys","(","self",".","keys","[","table","]",",","self",".","data","[","table","]",",","deleteData",")","self",".","data","[","table","]",".","remove","(","item",")","else",":","raise","Exception","(","\"Unknown action: %s\"","%","action",")","except",":","self",".","logger",".","error","(","traceback",".","format_exc","(",")",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/ws\/ws_thread.py#L206-L283"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuth.py","language":"python","identifier":"generate_signature","parameters":"(secret, verb, url, nonce, data)","argument_list":"","return_statement":"return signature","docstring":"Generate a request signature compatible with BitMEX.","docstring_summary":"Generate a request signature compatible with BitMEX.","docstring_tokens":["Generate","a","request","signature","compatible","with","BitMEX","."],"function":"def generate_signature(secret, verb, url, nonce, data):\n \"\"\"Generate a request signature compatible with BitMEX.\"\"\"\n # Parse the url so we can remove the base and extract just the path.\n parsedURL = urlparse(url)\n path = parsedURL.path\n if parsedURL.query:\n path = path + '?' + parsedURL.query\n\n # print \"Computing HMAC: %s\" % verb + path + str(nonce) + data\n message = verb + path + str(nonce) + data\n\n signature = hmac.new(bytes(secret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()\n return signature","function_tokens":["def","generate_signature","(","secret",",","verb",",","url",",","nonce",",","data",")",":","# Parse the url so we can remove the base and extract just the path.","parsedURL","=","urlparse","(","url",")","path","=","parsedURL",".","path","if","parsedURL",".","query",":","path","=","path","+","'?'","+","parsedURL",".","query","# print \"Computing HMAC: %s\" % verb + path + str(nonce) + data","message","=","verb","+","path","+","str","(","nonce",")","+","data","signature","=","hmac",".","new","(","bytes","(","secret",",","'utf8'",")",",","bytes","(","message",",","'utf8'",")",",","digestmod","=","hashlib",".","sha256",")",".","hexdigest","(",")","return","signature"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuth.py#L47-L59"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuth.py","language":"python","identifier":"APIKeyAuth.__init__","parameters":"(self, apiKey, apiSecret)","argument_list":"","return_statement":"","docstring":"Init with Key & Secret.","docstring_summary":"Init with Key & Secret.","docstring_tokens":["Init","with","Key","&","Secret","."],"function":"def __init__(self, apiKey, apiSecret):\n \"\"\"Init with Key & Secret.\"\"\"\n self.apiKey = apiKey\n self.apiSecret = apiSecret","function_tokens":["def","__init__","(","self",",","apiKey",",","apiSecret",")",":","self",".","apiKey","=","apiKey","self",".","apiSecret","=","apiSecret"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuth.py#L15-L18"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuth.py","language":"python","identifier":"APIKeyAuth.__call__","parameters":"(self, r)","argument_list":"","return_statement":"return r","docstring":"Called when forming a request - generates api key headers.","docstring_summary":"Called when forming a request - generates api key headers.","docstring_tokens":["Called","when","forming","a","request","-","generates","api","key","headers","."],"function":"def __call__(self, r):\n \"\"\"Called when forming a request - generates api key headers.\"\"\"\n # modify and return the request\n nonce = generate_nonce()\n r.headers['api-nonce'] = str(nonce)\n r.headers['api-key'] = self.apiKey\n r.headers['api-signature'] = generate_signature(self.apiSecret, r.method, r.url, nonce, r.body or '')\n\n return r","function_tokens":["def","__call__","(","self",",","r",")",":","# modify and return the request","nonce","=","generate_nonce","(",")","r",".","headers","[","'api-nonce'","]","=","str","(","nonce",")","r",".","headers","[","'api-key'","]","=","self",".","apiKey","r",".","headers","[","'api-signature'","]","=","generate_signature","(","self",".","apiSecret",",","r",".","method",",","r",".","url",",","nonce",",","r",".","body","or","''",")","return","r"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuth.py#L20-L28"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuthWithExpires.py","language":"python","identifier":"APIKeyAuthWithExpires.__init__","parameters":"(self, apiKey, apiSecret)","argument_list":"","return_statement":"","docstring":"Init with Key & Secret.","docstring_summary":"Init with Key & Secret.","docstring_tokens":["Init","with","Key","&","Secret","."],"function":"def __init__(self, apiKey, apiSecret):\n \"\"\"Init with Key & Secret.\"\"\"\n self.apiKey = apiKey\n self.apiSecret = apiSecret","function_tokens":["def","__init__","(","self",",","apiKey",",","apiSecret",")",":","self",".","apiKey","=","apiKey","self",".","apiSecret","=","apiSecret"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuthWithExpires.py#L15-L18"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuthWithExpires.py","language":"python","identifier":"APIKeyAuthWithExpires.__call__","parameters":"(self, r)","argument_list":"","return_statement":"return r","docstring":"Called when forming a request - generates api key headers. This call uses `expires` instead of nonce.\n\n This way it will not collide with other processes using the same API Key if requests arrive out of order.\n For more details, see https:\/\/www.bitmex.com\/app\/apiKeys","docstring_summary":"Called when forming a request - generates api key headers. This call uses `expires` instead of nonce.","docstring_tokens":["Called","when","forming","a","request","-","generates","api","key","headers",".","This","call","uses","expires","instead","of","nonce","."],"function":"def __call__(self, r):\n \"\"\"\n Called when forming a request - generates api key headers. This call uses `expires` instead of nonce.\n\n This way it will not collide with other processes using the same API Key if requests arrive out of order.\n For more details, see https:\/\/www.bitmex.com\/app\/apiKeys\n \"\"\"\n # modify and return the request\n expires = int(round(time.time()) + 5) # 5s grace period in case of clock skew\n r.headers['api-expires'] = str(expires)\n r.headers['api-key'] = self.apiKey\n r.headers['api-signature'] = self.generate_signature(self.apiSecret, r.method, r.url, expires, r.body or '')\n\n return r","function_tokens":["def","__call__","(","self",",","r",")",":","# modify and return the request","expires","=","int","(","round","(","time",".","time","(",")",")","+","5",")","# 5s grace period in case of clock skew","r",".","headers","[","'api-expires'","]","=","str","(","expires",")","r",".","headers","[","'api-key'","]","=","self",".","apiKey","r",".","headers","[","'api-signature'","]","=","self",".","generate_signature","(","self",".","apiSecret",",","r",".","method",",","r",".","url",",","expires",",","r",".","body","or","''",")","return","r"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuthWithExpires.py#L20-L33"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/APIKeyAuthWithExpires.py","language":"python","identifier":"APIKeyAuthWithExpires.generate_signature","parameters":"(self, secret, verb, url, nonce, data)","argument_list":"","return_statement":"return signature","docstring":"Generate a request signature compatible with BitMEX.","docstring_summary":"Generate a request signature compatible with BitMEX.","docstring_tokens":["Generate","a","request","signature","compatible","with","BitMEX","."],"function":"def generate_signature(self, secret, verb, url, nonce, data):\n \"\"\"Generate a request signature compatible with BitMEX.\"\"\"\n # Parse the url so we can remove the base and extract just the path.\n parsedURL = urlparse(url)\n path = parsedURL.path\n if parsedURL.query:\n path = path + '?' + parsedURL.query\n\n # print \"Computing HMAC: %s\" % verb + path + str(nonce) + data\n message = verb + path + str(nonce) + data\n\n signature = hmac.new(bytes(secret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()\n return signature","function_tokens":["def","generate_signature","(","self",",","secret",",","verb",",","url",",","nonce",",","data",")",":","# Parse the url so we can remove the base and extract just the path.","parsedURL","=","urlparse","(","url",")","path","=","parsedURL",".","path","if","parsedURL",".","query",":","path","=","path","+","'?'","+","parsedURL",".","query","# print \"Computing HMAC: %s\" % verb + path + str(nonce) + data","message","=","verb","+","path","+","str","(","nonce",")","+","data","signature","=","hmac",".","new","(","bytes","(","secret",",","'utf8'",")",",","bytes","(","message",",","'utf8'",")",",","digestmod","=","hashlib",".","sha256",")",".","hexdigest","(",")","return","signature"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/APIKeyAuthWithExpires.py#L48-L60"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/AccessTokenAuth.py","language":"python","identifier":"AccessTokenAuth.__init__","parameters":"(self, accessToken)","argument_list":"","return_statement":"","docstring":"Init with Token.","docstring_summary":"Init with Token.","docstring_tokens":["Init","with","Token","."],"function":"def __init__(self, accessToken):\n \"\"\"Init with Token.\"\"\"\n self.token = accessToken","function_tokens":["def","__init__","(","self",",","accessToken",")",":","self",".","token","=","accessToken"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/AccessTokenAuth.py#L8-L10"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"market_maker\/auth\/AccessTokenAuth.py","language":"python","identifier":"AccessTokenAuth.__call__","parameters":"(self, r)","argument_list":"","return_statement":"return r","docstring":"Called when forming a request - generates access token header.","docstring_summary":"Called when forming a request - generates access token header.","docstring_tokens":["Called","when","forming","a","request","-","generates","access","token","header","."],"function":"def __call__(self, r):\n \"\"\"Called when forming a request - generates access token header.\"\"\"\n if (self.token):\n r.headers['access-token'] = self.token\n return r","function_tokens":["def","__call__","(","self",",","r",")",":","if","(","self",".","token",")",":","r",".","headers","[","'access-token'","]","=","self",".","token","return","r"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/market_maker\/auth\/AccessTokenAuth.py#L12-L16"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"util\/generate-api-key.py","language":"python","identifier":"BitMEX.create_key","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Create an API key.","docstring_summary":"Create an API key.","docstring_tokens":["Create","an","API","key","."],"function":"def create_key(self):\n \"\"\"Create an API key.\"\"\"\n print(\"Creating key. Please input the following options:\")\n name = input(\"Key name (optional): \")\n print(\"To make this key more secure, you should restrict the IP addresses that can use it. \")\n print(\"To use with all IPs, leave blank or use 0.0.0.0\/0.\")\n print(\"To use with a single IP, append '\/32', such as 207.39.29.22\/32. \")\n print(\"See this reference on CIDR blocks: http:\/\/software77.net\/cidr-101.html\")\n cidr = input(\"CIDR (optional): \")\n\n # Set up permissions\n permissions = []\n if strtobool(input(\"Should this key be able to submit orders? [y\/N] \") or 'N'):\n permissions.append('order')\n if strtobool(input(\"Should this key be able to submit withdrawals? [y\/N] \") or 'N'):\n permissions.append('withdraw')\n\n otpToken = input(\"OTP Token (If enabled. If not, press <enter>): \")\n\n key = self._curl_bitmex(\"\/apiKey\",\n postdict={\"name\": name, \"cidr\": cidr, \"enabled\": True, \"token\": otpToken,\n \"permissions\": string.join(permissions, ',')})\n\n print(\"Key created. Details:\\n\")\n print(\"API Key: \" + key[\"id\"])\n print(\"Secret: \" + key[\"secret\"])\n print(\"\\nSafeguard your secret key! If somebody gets a hold of your API key and secret,\")\n print(\"your account can be taken over completely.\")\n print(\"\\nKey generation complete.\")","function_tokens":["def","create_key","(","self",")",":","print","(","\"Creating key. Please input the following options:\"",")","name","=","input","(","\"Key name (optional): \"",")","print","(","\"To make this key more secure, you should restrict the IP addresses that can use it. \"",")","print","(","\"To use with all IPs, leave blank or use 0.0.0.0\/0.\"",")","print","(","\"To use with a single IP, append '\/32', such as 207.39.29.22\/32. \"",")","print","(","\"See this reference on CIDR blocks: http:\/\/software77.net\/cidr-101.html\"",")","cidr","=","input","(","\"CIDR (optional): \"",")","# Set up permissions","permissions","=","[","]","if","strtobool","(","input","(","\"Should this key be able to submit orders? [y\/N] \"",")","or","'N'",")",":","permissions",".","append","(","'order'",")","if","strtobool","(","input","(","\"Should this key be able to submit withdrawals? [y\/N] \"",")","or","'N'",")",":","permissions",".","append","(","'withdraw'",")","otpToken","=","input","(","\"OTP Token (If enabled. If not, press <enter>): \"",")","key","=","self",".","_curl_bitmex","(","\"\/apiKey\"",",","postdict","=","{","\"name\"",":","name",",","\"cidr\"",":","cidr",",","\"enabled\"",":","True",",","\"token\"",":","otpToken",",","\"permissions\"",":","string",".","join","(","permissions",",","','",")","}",")","print","(","\"Key created. Details:\\n\"",")","print","(","\"API Key: \"","+","key","[","\"id\"","]",")","print","(","\"Secret: \"","+","key","[","\"secret\"","]",")","print","(","\"\\nSafeguard your secret key! If somebody gets a hold of your API key and secret,\"",")","print","(","\"your account can be taken over completely.\"",")","print","(","\"\\nKey generation complete.\"",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/util\/generate-api-key.py#L79-L107"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"util\/generate-api-key.py","language":"python","identifier":"BitMEX.list_keys","parameters":"(self)","argument_list":"","return_statement":"","docstring":"List your API Keys.","docstring_summary":"List your API Keys.","docstring_tokens":["List","your","API","Keys","."],"function":"def list_keys(self):\n \"\"\"List your API Keys.\"\"\"\n keys = self._curl_bitmex(\"\/apiKey\/\")\n print(json.dumps(keys, sort_keys=True, indent=4))","function_tokens":["def","list_keys","(","self",")",":","keys","=","self",".","_curl_bitmex","(","\"\/apiKey\/\"",")","print","(","json",".","dumps","(","keys",",","sort_keys","=","True",",","indent","=","4",")",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/util\/generate-api-key.py#L109-L112"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"util\/generate-api-key.py","language":"python","identifier":"BitMEX.enable_key","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Enable an existing API Key.","docstring_summary":"Enable an existing API Key.","docstring_tokens":["Enable","an","existing","API","Key","."],"function":"def enable_key(self):\n \"\"\"Enable an existing API Key.\"\"\"\n print(\"This command will enable a disabled key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n key = self._curl_bitmex(\"\/apiKey\/enable\",\n postdict={\"apiKeyID\": apiKeyID})\n print(\"Key with ID %s enabled.\" % key[\"id\"])\n except:\n print(\"Unable to enable key, please try again.\")\n self.enable_key()","function_tokens":["def","enable_key","(","self",")",":","print","(","\"This command will enable a disabled key.\"",")","apiKeyID","=","input","(","\"API Key ID: \"",")","try",":","key","=","self",".","_curl_bitmex","(","\"\/apiKey\/enable\"",",","postdict","=","{","\"apiKeyID\"",":","apiKeyID","}",")","print","(","\"Key with ID %s enabled.\"","%","key","[","\"id\"","]",")","except",":","print","(","\"Unable to enable key, please try again.\"",")","self",".","enable_key","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/util\/generate-api-key.py#L114-L124"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"util\/generate-api-key.py","language":"python","identifier":"BitMEX.disable_key","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Disable an existing API Key.","docstring_summary":"Disable an existing API Key.","docstring_tokens":["Disable","an","existing","API","Key","."],"function":"def disable_key(self):\n \"\"\"Disable an existing API Key.\"\"\"\n print(\"This command will disable a enabled key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n key = self._curl_bitmex(\"\/apiKey\/disable\",\n postdict={\"apiKeyID\": apiKeyID})\n print(\"Key with ID %s disabled.\" % key[\"id\"])\n except:\n print(\"Unable to disable key, please try again.\")\n self.disable_key()","function_tokens":["def","disable_key","(","self",")",":","print","(","\"This command will disable a enabled key.\"",")","apiKeyID","=","input","(","\"API Key ID: \"",")","try",":","key","=","self",".","_curl_bitmex","(","\"\/apiKey\/disable\"",",","postdict","=","{","\"apiKeyID\"",":","apiKeyID","}",")","print","(","\"Key with ID %s disabled.\"","%","key","[","\"id\"","]",")","except",":","print","(","\"Unable to disable key, please try again.\"",")","self",".","disable_key","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/util\/generate-api-key.py#L126-L136"}
{"nwo":"Behappy123\/market-maker","sha":"aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4","path":"util\/generate-api-key.py","language":"python","identifier":"BitMEX.delete_key","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Delete an existing API Key.","docstring_summary":"Delete an existing API Key.","docstring_tokens":["Delete","an","existing","API","Key","."],"function":"def delete_key(self):\n \"\"\"Delete an existing API Key.\"\"\"\n print(\"This command will delete an API key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n self._curl_bitmex(\"\/apiKey\/\",\n postdict={\"apiKeyID\": apiKeyID}, verb='DELETE')\n print(\"Key with ID %s deleted.\" % apiKeyID)\n except:\n print(\"Unable to delete key, please try again.\")\n self.delete_key()","function_tokens":["def","delete_key","(","self",")",":","print","(","\"This command will delete an API key.\"",")","apiKeyID","=","input","(","\"API Key ID: \"",")","try",":","self",".","_curl_bitmex","(","\"\/apiKey\/\"",",","postdict","=","{","\"apiKeyID\"",":","apiKeyID","}",",","verb","=","'DELETE'",")","print","(","\"Key with ID %s deleted.\"","%","apiKeyID",")","except",":","print","(","\"Unable to delete key, please try again.\"",")","self",".","delete_key","(",")"],"url":"https:\/\/github.com\/Behappy123\/market-maker\/blob\/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4\/util\/generate-api-key.py#L138-L148"}