async def _balances(self, msg: str, ts: float): ''' { "jsonrpc": "2.0", "method": "balance", "params": [ { "currency": "BTC", "available": "0.00005821", "reserved": "0" }, { "currency": "DOGE", "available": "11", "reserved": "0" } ] } ''' for entry in msg['params']: b = Balance(self.id, entry['currency'], Decimal(entry['available']), Decimal(entry['reserved']), raw=entry) await self.callback(BALANCES, b, ts)
async def balances(self) -> List[Balance]: data = await self._request('GET', "/accounts", auth=True) # def __init__(self, exchange, currency, balance, reserved, raw=None): return [ Balance(self.id, entry['currency'], Decimal(entry['balance']), Decimal(entry['balance']) - Decimal(entry['available']), raw=entry) for entry in data ]
async def _account(self, msg: dict, symbol: str, timestamp: float): ''' spot { 'action': 'snapshot', 'arg': { 'instType': 'spbl', 'channel': 'account', 'instId': 'BTCUSDT_SPBL' }, 'data': [] } futures { 'action': 'snapshot', 'arg': { 'instType': 'dmcbl', 'channel': 'account', 'instId': 'BTCUSD_DMCBL' }, 'data': [{ 'marginCoin': 'BTC', 'locked': '0.00000000', 'available': '0.00000000', 'maxOpenPosAvailable': '0.00000000', 'maxTransferOut': '0.00000000', 'equity': '0.00000000', 'usdtEquity': '0.000000000000' }, { 'marginCoin': 'ETH', 'locked': '0.00000000', 'available': '0.00000000', 'maxOpenPosAvailable': '0.00000000', 'maxTransferOut': '0.00000000', 'equity': '0.00000000', 'usdtEquity': '0.000000000000' }] } ''' for entry in msg['data']: b = Balance(self.id, symbol, Decimal(entry['available']), Decimal(entry['locked']), raw=entry) await self.callback(BALANCES, b, timestamp)
async def _account_update(self, msg: dict, timestamp: float): """ { "e": "outboundAccountPosition", //Event type "E": 1564034571105, //Event Time "u": 1564034571073, //Time of last account update "B": [ //Balances Array { "a": "ETH", //Asset "f": "10000.000000", //Free "l": "0.000000" //Locked } ] } """ for balance in msg['B']: b = Balance(self.id, balance['a'], Decimal(balance['f']), Decimal(balance['l']), raw=msg) await self.callback(BALANCES, b, timestamp)
async def _account_update(self, msg: dict, timestamp: float): """ { "e": "ACCOUNT_UPDATE", // Event Type "E": 1564745798939, // Event Time "T": 1564745798938 , // Transaction "i": "SfsR", // Account Alias "a": // Update Data { "m":"ORDER", // Event reason type "B":[ // Balances { "a":"BTC", // Asset "wb":"122624.12345678", // Wallet Balance "cw":"100.12345678" // Cross Wallet Balance }, { "a":"ETH", "wb":"1.00000000", "cw":"0.00000000" } ], "P":[ { "s":"BTCUSD_200925", // Symbol "pa":"0", // Position Amount "ep":"0.0", // Entry Price "cr":"200", // (Pre-fee) Accumulated Realized "up":"0", // Unrealized PnL "mt":"isolated", // Margin Type "iw":"0.00000000", // Isolated Wallet (if isolated position) "ps":"BOTH" // Position Side }, { "s":"BTCUSD_200925", "pa":"20", "ep":"6563.6", "cr":"0", "up":"2850.21200000", "mt":"isolated", "iw":"13200.70726908", "ps":"LONG" }, { "s":"BTCUSD_200925", "pa":"-10", "ep":"6563.8", "cr":"-45.04000000", "up":"-1423.15600000", "mt":"isolated", "iw":"6570.42511771", "ps":"SHORT" } ] } } """ for balance in msg['a']['B']: b = Balance(self.id, balance['a'], Decimal(balance['wb']), None, raw=msg) await self.callback(BALANCES, b, timestamp) for position in msg['a']['P']: p = Position(self.id, self.exchange_symbol_to_std_symbol(position['s']), Decimal(position['pa']), Decimal(position['ep']), position['ps'].lower(), Decimal(position['up']), self.timestamp_normalize(msg['E']), raw=msg) await self.callback(POSITIONS, p, timestamp)
async def _balances(self, msg: dict, timestamp: float): ''' Futures/Options { "channel":"account", "timestamp":1589031930115, "data":{ "user_id":"53345", "currency":"BTC", "cash_balance":"9999.94981346", "available_balance":"9999.90496213", "margin_balance":"9999.94981421", "initial_margin":"0.04485208", "maintenance_margin":"0.00000114", "equity":"10000.00074364", "pnl":"0.00746583", "total_delta":"0.06207078", "account_id":"8", "mode":"regular", "session_upl":"0.00081244", "session_rpl":"0.00000021", "option_value":"0.05092943", "option_pnl":"0.00737943", "option_session_rpl":"0.00000000", "option_session_upl":"0.00081190", "option_delta":"0.11279249", "option_gamma":"0.00002905", "option_vega":"4.30272923", "option_theta":"-3.08908220", "future_pnl":"0.00008640", "future_session_rpl":"0.00000021", "future_session_upl":"0.00000054", "future_session_funding":"0.00000021", "future_delta":"0.00955630", "created_at":1588997840512, "projected_info": { "projected_initial_margin": "0.97919888", "projected_maintenance_margin": "0.78335911", "projected_total_delta": "3.89635553" } } } Spot { 'channel': 'account', 'timestamp': 1641516119102, 'data': { 'user_id': '979394', 'balances': [ { 'currency': 'BTC', 'available': '31.02527500', 'frozen': '0.00000000' }, { 'currency': 'ETH', 'available': '110.00000000', 'frozen': '0.00000000' } ] } } ''' if 'balances' in msg['data']: # Spot for balance in msg['data']['balances']: b = Balance(self.id, balance['currency'], Decimal(balance['available']), Decimal(balance['frozen']), raw=msg) await self.callback(BALANCES, b, timestamp) else: b = Balance(self.id, msg['data']['currency'], Decimal(msg['data']['cash_balance']), Decimal(msg['data']['cash_balance']) - Decimal(msg['data']['available_balance']), raw=msg) await self.callback(BALANCES, b, timestamp)
async def _user_channels(self, conn: AsyncConnection, msg: dict, timestamp: float, subchan: str): order_status = { "open": OPEN, "filled": FILLED, "rejected": FAILED, "cancelled": CANCELLED, "untriggered": OPEN } order_types = { "limit": LIMIT, "market": MARKET, "stop_limit": STOP_LIMIT, "stop_market": STOP_MARKET } if 'data' in msg['params']: data = msg['params']['data'] if subchan == 'portfolio': ''' { "params" : { "data" : { "total_pl" : 0.00000425, "session_upl" : 0.00000425, "session_rpl" : -2e-8, "projected_maintenance_margin" : 0.00009141, "projected_initial_margin" : 0.00012542, "projected_delta_total" : 0.0043, "portfolio_margining_enabled" : false, "options_vega" : 0, "options_value" : 0, "options_theta" : 0, "options_session_upl" : 0, "options_session_rpl" : 0, "options_pl" : 0, "options_gamma" : 0, "options_delta" : 0, "margin_balance" : 0.2340038, "maintenance_margin" : 0.00009141, "initial_margin" : 0.00012542, "futures_session_upl" : 0.00000425, "futures_session_rpl" : -2e-8, "futures_pl" : 0.00000425, "estimated_liquidation_ratio" : 0.01822795, "equity" : 0.2340038, "delta_total" : 0.0043, "currency" : "BTC", "balance" : 0.23399957, "available_withdrawal_funds" : 0.23387415, "available_funds" : 0.23387838 }, "channel" : "user.portfolio.btc" }, "method" : "subscription", "jsonrpc" : "2.0" } ''' b = Balance(self.id, data['currency'], Decimal(data['balance']), Decimal(data['balance']) - Decimal(data['available_withdrawal_funds']), raw=data) await self.callback(BALANCES, b, timestamp) elif subchan == 'orders': ''' { "params" : { "data" : { "time_in_force" : "good_til_cancelled", "replaced" : false, "reduce_only" : false, "profit_loss" : 0, "price" : 10502.52, "post_only" : false, "original_order_type" : "market", "order_type" : "limit", "order_state" : "open", "order_id" : "5", "max_show" : 200, "last_update_timestamp" : 1581507423789, "label" : "", "is_liquidation" : false, "instrument_name" : "BTC-PERPETUAL", "filled_amount" : 0, "direction" : "buy", "creation_timestamp" : 1581507423789, "commission" : 0, "average_price" : 0, "api" : false, "amount" : 200 }, "channel" : "user.orders.BTC-PERPETUAL.raw" }, "method" : "subscription", "jsonrpc" : "2.0" } ''' oi = OrderInfo( self.id, self.exchange_symbol_to_std_symbol( data['instrument_name']), data["order_id"], BUY if msg["side"] == 'Buy' else SELL, order_status[data["order_state"]], order_types[data['order_type']], Decimal(data['price']), Decimal(data['filled_amount']), Decimal(data['amount']) - Decimal(data['cumQuantity']), self.timestamp_normalize(data["last_update_timestamp"]), raw=data) await self.callback(ORDER_INFO, oi, timestamp) elif subchan == 'trades': ''' { "params" : { "data" : [ { "trade_seq" : 30289432, "trade_id" : "48079254", "timestamp" : 1590484156350, "tick_direction" : 0, "state" : "filled", "self_trade" : false, "reduce_only" : false, "price" : 8954, "post_only" : false, "order_type" : "market", "order_id" : "4008965646", "matching_id" : null, "mark_price" : 8952.86, "liquidity" : "T", "instrument_name" : "BTC-PERPETUAL", "index_price" : 8956.73, "fee_currency" : "BTC", "fee" : 0.00000168, "direction" : "sell", "amount" : 20 }] } } ''' for entry in data: symbol = self.exchange_symbol_to_std_symbol( entry['instrument_name']) f = Fill(self.id, symbol, SELL if entry['direction'] == 'sell' else BUY, Decimal(entry['amount']), Decimal(entry['price']), Decimal(entry['fee']), entry['trade_id'], entry['order_id'], entry['order_type'], TAKER if entry['liquidity'] == 'T' else MAKER, self.timestamp_normalize(entry['timestamp']), raw=entry) await self.callback(FILLS, f, timestamp) else: LOG.warning("%s: Unknown channel 'user.%s'", conn.uuid, subchan) else: LOG.warning("%s: Unknown message %s'", conn.uuid, msg)
async def _user_data(self, msg: dict, timestamp: float): ''' snapshot: { "accounts":[ { "accountBalanceEv":100000024, "accountID":675340001, "bonusBalanceEv":0, "currency":"BTC", "totalUsedBalanceEv":1222, "userID":67534 } ], "orders":[ { "accountID":675340001, "action":"New", "actionBy":"ByUser", "actionTimeNs":1573711481897337000, "addedSeq":1110523, "bonusChangedAmountEv":0, "clOrdID":"uuid-1573711480091", "closedPnlEv":0, "closedSize":0, "code":0, "cumQty":2, "cumValueEv":23018, "curAccBalanceEv":100000005, "curAssignedPosBalanceEv":0, "curBonusBalanceEv":0, "curLeverageEr":0, "curPosSide":"Buy", "curPosSize":2, "curPosTerm":1, "curPosValueEv":23018, "curRiskLimitEv":10000000000, "currency":"BTC", "cxlRejReason":0, "displayQty":2, "execFeeEv":-5, "execID":"92301512-7a79-5138-b582-ac185223727d", "execPriceEp":86885000, "execQty":2, "execSeq":1131034, "execStatus":"MakerFill", "execValueEv":23018, "feeRateEr":-25000, "lastLiquidityInd":"AddedLiquidity", "leavesQty":0, "leavesValueEv":0, "message":"No error", "ordStatus":"Filled", "ordType":"Limit", "orderID":"e9a45803-0af8-41b7-9c63-9b7c417715d9", "orderQty":2, "pegOffsetValueEp":0, "priceEp":86885000, "relatedPosTerm":1, "relatedReqNum":2, "side":"Buy", "stopLossEp":0, "stopPxEp":0, "symbol":"BTCUSD", "takeProfitEp":0, "timeInForce":"GoodTillCancel", "tradeType":"Trade", "transactTimeNs":1573712555309040417, "userID":67534 }, { "accountID":675340001, "action":"New", "actionBy":"ByUser", "actionTimeNs":1573711490507067000, "addedSeq":1110980, "bonusChangedAmountEv":0, "clOrdID":"uuid-1573711488668", "closedPnlEv":0, "closedSize":0, "code":0, "cumQty":3, "cumValueEv":34530, "curAccBalanceEv":100000013, "curAssignedPosBalanceEv":0, "curBonusBalanceEv":0, "curLeverageEr":0, "curPosSide":"Buy", "curPosSize":5, "curPosTerm":1, "curPosValueEv":57548, "curRiskLimitEv":10000000000, "currency":"BTC", "cxlRejReason":0, "displayQty":3, "execFeeEv":-8, "execID":"80899855-5b95-55aa-b84e-8d1052f19886", "execPriceEp":86880000, "execQty":3, "execSeq":1131408, "execStatus":"MakerFill", "execValueEv":34530, "feeRateEr":-25000, "lastLiquidityInd":"AddedLiquidity", "leavesQty":0, "leavesValueEv":0, "message":"No error", "ordStatus":"Filled", "ordType":"Limit", "orderID":"7e03cd6b-e45e-48d9-8937-8c6628e7a79d", "orderQty":3, "pegOffsetValueEp":0, "priceEp":86880000, "relatedPosTerm":1, "relatedReqNum":3, "side":"Buy", "stopLossEp":0, "stopPxEp":0, "symbol":"BTCUSD", "takeProfitEp":0, "timeInForce":"GoodTillCancel", "tradeType":"Trade", "transactTimeNs":1573712559100655668, "userID":67534 }, { "accountID":675340001, "action":"New", "actionBy":"ByUser", "actionTimeNs":1573711499282604000, "addedSeq":1111025, "bonusChangedAmountEv":0, "clOrdID":"uuid-1573711497265", "closedPnlEv":0, "closedSize":0, "code":0, "cumQty":4, "cumValueEv":46048, "curAccBalanceEv":100000024, "curAssignedPosBalanceEv":0, "curBonusBalanceEv":0, "curLeverageEr":0, "curPosSide":"Buy", "curPosSize":9, "curPosTerm":1, "curPosValueEv":103596, "curRiskLimitEv":10000000000, "currency":"BTC", "cxlRejReason":0, "displayQty":4, "execFeeEv":-11, "execID":"0be06645-90b8-5abe-8eb0-dca8e852f82f", "execPriceEp":86865000, "execQty":4, "execSeq":1132422, "execStatus":"MakerFill", "execValueEv":46048, "feeRateEr":-25000, "lastLiquidityInd":"AddedLiquidity", "leavesQty":0, "leavesValueEv":0, "message":"No error", "ordStatus":"Filled", "ordType":"Limit", "orderID":"66753807-9204-443d-acf9-946d15d5bedb", "orderQty":4, "pegOffsetValueEp":0, "priceEp":86865000, "relatedPosTerm":1, "relatedReqNum":4, "side":"Buy", "stopLossEp":0, "stopPxEp":0, "symbol":"BTCUSD", "takeProfitEp":0, "timeInForce":"GoodTillCancel", "tradeType":"Trade", "transactTimeNs":1573712618104628671, "userID":67534 } ], "positions":[ { "accountID":675340001, "assignedPosBalanceEv":0, "avgEntryPriceEp":86875941, "bankruptCommEv":75022, "bankruptPriceEp":90000, "buyLeavesQty":0, "buyLeavesValueEv":0, "buyValueToCostEr":1150750, "createdAtNs":0, "crossSharedBalanceEv":99998802, "cumClosedPnlEv":0, "cumFundingFeeEv":0, "cumTransactFeeEv":-24, "currency":"BTC", "dataVer":4, "deleveragePercentileEr":0, "displayLeverageEr":1000000, "estimatedOrdLossEv":0, "execSeq":1132422, "freeCostEv":0, "freeQty":-9, "initMarginReqEr":1000000, "lastFundingTime":1573703858883133252, "lastTermEndTime":0, "leverageEr":0, "liquidationPriceEp":90000, "maintMarginReqEr":500000, "makerFeeRateEr":0, "markPriceEp":86786292, "orderCostEv":0, "posCostEv":1115, "positionMarginEv":99925002, "positionStatus":"Normal", "riskLimitEv":10000000000, "sellLeavesQty":0, "sellLeavesValueEv":0, "sellValueToCostEr":1149250, "side":"Buy", "size":9, "symbol":"BTCUSD", "takerFeeRateEr":0, "term":1, "transactTimeNs":1573712618104628671, "unrealisedPnlEv":-107, "updatedAtNs":0, "usedBalanceEv":1222, "userID":67534, "valueEv":103596 } ], "sequence":1310812, "timestamp":1573716998131003833, "type":"snapshot" } incremental update: { "accounts":[ { "accountBalanceEv":99999989, "accountID":675340001, "bonusBalanceEv":0, "currency":"BTC", "totalUsedBalanceEv":1803, "userID":67534 } ], "orders":[ { "accountID":675340001, "action":"New", "actionBy":"ByUser", "actionTimeNs":1573717286765750000, "addedSeq":1192303, "bonusChangedAmountEv":0, "clOrdID":"uuid-1573717284329", "closedPnlEv":0, "closedSize":0, "code":0, "cumQty":0, "cumValueEv":0, "curAccBalanceEv":100000024, "curAssignedPosBalanceEv":0, "curBonusBalanceEv":0, "curLeverageEr":0, "curPosSide":"Buy", "curPosSize":9, "curPosTerm":1, "curPosValueEv":103596, "curRiskLimitEv":10000000000, "currency":"BTC", "cxlRejReason":0, "displayQty":4, "execFeeEv":0, "execID":"00000000-0000-0000-0000-000000000000", "execPriceEp":0, "execQty":0, "execSeq":1192303, "execStatus":"New", "execValueEv":0, "feeRateEr":0, "leavesQty":4, "leavesValueEv":46098, "message":"No error", "ordStatus":"New", "ordType":"Limit", "orderID":"e329ae87-ce80-439d-b0cf-ad65272ed44c", "orderQty":4, "pegOffsetValueEp":0, "priceEp":86770000, "relatedPosTerm":1, "relatedReqNum":5, "side":"Buy", "stopLossEp":0, "stopPxEp":0, "symbol":"BTCUSD", "takeProfitEp":0, "timeInForce":"GoodTillCancel", "transactTimeNs":1573717286765896560, "userID":67534 }, { "accountID":675340001, "action":"New", "actionBy":"ByUser", "actionTimeNs":1573717286765750000, "addedSeq":1192303, "bonusChangedAmountEv":0, "clOrdID":"uuid-1573717284329", "closedPnlEv":0, "closedSize":0, "code":0, "cumQty":4, "cumValueEv":46098, "curAccBalanceEv":99999989, "curAssignedPosBalanceEv":0, "curBonusBalanceEv":0, "curLeverageEr":0, "curPosSide":"Buy", "curPosSize":13, "curPosTerm":1, "curPosValueEv":149694, "curRiskLimitEv":10000000000, "currency":"BTC", "cxlRejReason":0, "displayQty":4, "execFeeEv":35, "execID":"8d1848a2-5faf-52dd-be71-9fecbc8926be", "execPriceEp":86770000, "execQty":4, "execSeq":1192303, "execStatus":"TakerFill", "execValueEv":46098, "feeRateEr":75000, "lastLiquidityInd":"RemovedLiquidity", "leavesQty":0, "leavesValueEv":0, "message":"No error", "ordStatus":"Filled", "ordType":"Limit", "orderID":"e329ae87-ce80-439d-b0cf-ad65272ed44c", "orderQty":4, "pegOffsetValueEp":0, "priceEp":86770000, "relatedPosTerm":1, "relatedReqNum":5, "side":"Buy", "stopLossEp":0, "stopPxEp":0, "symbol":"BTCUSD", "takeProfitEp":0, "timeInForce":"GoodTillCancel", "tradeType":"Trade", "transactTimeNs":1573717286765896560, "userID":67534 } ], "positions":[ { "accountID":675340001, "assignedPosBalanceEv":0, "avgEntryPriceEp":86843828, "bankruptCommEv":75056, "bankruptPriceEp":130000, "buyLeavesQty":0, "buyLeavesValueEv":0, "buyValueToCostEr":1150750, "createdAtNs":0, "crossSharedBalanceEv":99998186, "cumClosedPnlEv":0, "cumFundingFeeEv":0, "cumTransactFeeEv":11, "currency":"BTC", "dataVer":5, "deleveragePercentileEr":0, "displayLeverageEr":1000000, "estimatedOrdLossEv":0, "execSeq":1192303, "freeCostEv":0, "freeQty":-13, "initMarginReqEr":1000000, "lastFundingTime":1573703858883133252, "lastTermEndTime":0, "leverageEr":0, "liquidationPriceEp":130000, "maintMarginReqEr":500000, "makerFeeRateEr":0, "markPriceEp":86732335, "orderCostEv":0, "posCostEv":1611, "positionMarginEv":99924933, "positionStatus":"Normal", "riskLimitEv":10000000000, "sellLeavesQty":0, "sellLeavesValueEv":0, "sellValueToCostEr":1149250, "side":"Buy", "size":13, "symbol":"BTCUSD", "takerFeeRateEr":0, "term":1, "transactTimeNs":1573717286765896560, "unrealisedPnlEv":-192, "updatedAtNs":0, "usedBalanceEv":1803, "userID":67534, "valueEv":149694 } ], "sequence":1315725, "timestamp":1573717286767188294, "type":"incremental" } ''' for entry in msg['accounts']: b = Balance( self.id, entry['currency'], Decimal(entry['accountBalanceEv']), Decimal(entry['totalUsedBalanceEv']), self.timestamp_normalize(msg['timestamp']), raw=entry ) await self.callback(BALANCES, b, timestamp)