Ejemplo n.º 1
0
 async def _trades(self, msg: dict, timestamp: float):
     '''
     {
         'buyer_role': 'taker',
         'price': '54900.0',
         'product_id': 8320,
         'seller_role': 'maker',
         'size': '0.000695',
         'symbol': 'BTC_USDT',
         'timestamp': 1638132618257226,
         'type': 'all_trades'
     }
     '''
     if msg['type'] == 'all_trades':
         t = Trade(self.id,
                   self.exchange_symbol_to_std_symbol(msg['symbol']),
                   BUY if msg['buyer_role'] == 'taker' else SELL,
                   Decimal(msg['size']),
                   Decimal(msg['price']),
                   self.timestamp_normalize(msg['timestamp']),
                   raw=msg)
         await self.callback(TRADES, t, timestamp)
     else:
         for trade in msg['trades']:
             t = Trade(self.id,
                       self.exchange_symbol_to_std_symbol(msg['symbol']),
                       BUY if trade['buyer_role'] == 'taker' else SELL,
                       Decimal(trade['size']),
                       Decimal(trade['price']),
                       self.timestamp_normalize(trade['timestamp']),
                       raw=trade)
             await self.callback(TRADES, t, timestamp)
Ejemplo n.º 2
0
def test_trade():
    t = Trade('COINBASE',
              'BTC-USD',
              BUY,
              Decimal(10),
              Decimal(100),
              time(),
              id=str(int(time())),
              type='TEST')
    d = t.to_dict(numeric_type=str)
    d = json.dumps(d)
    d = json.loads(d)
    t2 = Trade.from_dict(d)
    assert t == t2
Ejemplo n.º 3
0
 async def _trade(self, msg: dict, timestamp: float):
     """
     {
         'ch': 'market.adausdt.trade.detail',
         'ts': 1597792835344,
         'tick': {
             'id': 101801945127,
             'ts': 1597792835336,
             'data': [
                 {
                     'id': Decimal('10180194512782291967181675'),   <- per docs this is deprecated
                     'ts': 1597792835336,
                     'tradeId': 100341530602,
                     'amount': Decimal('0.1'),
                     'price': Decimal('0.137031'),
                     'direction': 'sell'
                 }
             ]
         }
     }
     """
     for trade in msg['tick']['data']:
         t = Trade(self.id,
                   self.exchange_symbol_to_std_symbol(
                       msg['ch'].split('.')[1]),
                   BUY if trade['direction'] == 'buy' else SELL,
                   Decimal(trade['amount']),
                   Decimal(trade['price']),
                   self.timestamp_normalize(trade['ts']),
                   id=str(trade['tradeId']),
                   raw=trade)
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 4
0
 async def _trade(self, msg: dict, ts: float):
     '''
     {
         'ch': 'trades',
         'update': {
             'BTCUSDT': [{
                 't': 1633803835228,
                 'i': 1633803835228,
                 'p': '54774.60',
                 'q': '0.00004',
                 's': 'buy'
             }]
         }
     }
     '''
     for pair, update in msg['update'].items():
         symbol = self.exchange_symbol_to_std_symbol(pair)
         for trade in update:
             t = Trade(self.id,
                       symbol,
                       BUY if trade['s'] == 'buy' else SELL,
                       Decimal(trade['q']),
                       Decimal(trade['p']),
                       self.timestamp_normalize(trade['t']),
                       id=str(trade['i']),
                       raw=msg)
             await self.callback(TRADES, t, ts)
Ejemplo n.º 5
0
    async def _book_update(self, msg: dict, timestamp: float):
        '''
        {
            'type': 'match', or last_match
            'trade_id': 43736593
            'maker_order_id': '2663b65f-b74e-4513-909d-975e3910cf22',
            'taker_order_id': 'd058d737-87f1-4763-bbb4-c2ccf2a40bde',
            'side': 'buy',
            'size': '0.01235647',
            'price': '8506.26000000',
            'product_id': 'BTC-USD',
            'sequence': 5928276661,
            'time': '2018-05-21T00:26:05.585000Z'
        }
        '''
        pair = self.exchange_symbol_to_std_symbol(msg['product_id'])
        ts = self.timestamp_normalize(msg['time'])

        if self.keep_l3_book and 'full' in self.subscription and pair in self.subscription[
                'full']:
            delta = {BID: [], ASK: []}
            price = Decimal(msg['price'])
            side = ASK if msg['side'] == 'sell' else BID
            size = Decimal(msg['size'])
            maker_order_id = msg['maker_order_id']

            _, new_size = self.order_map[maker_order_id]
            new_size -= size
            if new_size <= 0:
                del self.order_map[maker_order_id]
                self.order_type_map.pop(maker_order_id, None)
                delta[side].append((maker_order_id, price, 0))
                del self._l3_book[pair].book[side][price][maker_order_id]
                if len(self._l3_book[pair].book[side][price]) == 0:
                    del self._l3_book[pair].book[side][price]
            else:
                self.order_map[maker_order_id] = (price, new_size)
                self._l3_book[pair].book[side][price][
                    maker_order_id] = new_size
                delta[side].append((maker_order_id, price, new_size))

            await self.book_callback(L3_BOOK,
                                     self._l3_book[pair],
                                     timestamp,
                                     timestamp=ts,
                                     delta=delta,
                                     raw=msg,
                                     sequence_number=self.seq_no[pair])

        order_type = self.order_type_map.get(msg['taker_order_id'])
        t = Trade(self.id,
                  self.exchange_symbol_to_std_symbol(msg['product_id']),
                  SELL if msg['side'] == 'buy' else BUY,
                  Decimal(msg['size']),
                  Decimal(msg['price']),
                  ts,
                  id=str(msg['trade_id']),
                  type=order_type,
                  raw=msg)
        await self.callback(TRADES, t, timestamp)
Ejemplo n.º 6
0
 async def _trades(self, msg: dict, timestamp: float):
     '''
     {
         'instrument_name': 'BTC_USDT',
         'subscription': 'trade.BTC_USDT',
         'channel': 'trade',
         'data': [
             {
                 'dataTime': 1637630445449,
                 'd': 2006341810221954784,
                 's': 'BUY',
                 'p': Decimal('56504.25'),
                 'q': Decimal('0.003802'),
                 't': 1637630445448,
                 'i': 'BTC_USDT'
             }
         ]
     }
     '''
     for entry in msg['data']:
         t = Trade(
             self.id,
             self.exchange_symbol_to_std_symbol(msg['instrument_name']),
             BUY if entry['s'] == 'BUY' else SELL,
             entry['q'],
             entry['p'],
             self.timestamp_normalize(entry['t']),
             id=str(entry['d']),
             raw=entry
         )
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 7
0
 async def _trade(self, msg: dict, pair: str, timestamp: float):
     """
     {
         "feed": "trade",
         "product_id": "PI_XBTUSD",
         "uid": "b5a1c239-7987-4207-96bf-02355a3263cf",
         "side": "sell",
         "type": "fill",
         "seq": 85423,
         "time": 1565342712903,
         "qty": 1135.0,
         "price": 11735.0
     }
     """
     t = Trade(
         self.id,
         pair,
         BUY if msg['side'] == 'buy' else SELL,
         Decimal(msg['qty']),
         Decimal(msg['price']),
         self.timestamp_normalize(msg['time']),
         id=msg['uid'],
         raw=msg
     )
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 8
0
    async def _trades(self, msg: dict, symbol: str, timestamp: float):
        """
        {
            "type":"message",
            "topic":"/market/match:BTC-USDT",
            "subject":"trade.l3match",
            "data":{

                "sequence":"1545896669145",
                "type":"match",
                "symbol":"BTC-USDT",
                "side":"buy",
                "price":"0.08200000000000000000",
                "size":"0.01022222000000000000",
                "tradeId":"5c24c5da03aa673885cd67aa",
                "takerOrderId":"5c24c5d903aa6772d55b371e",
                "makerOrderId":"5c2187d003aa677bd09d5c93",
                "time":"1545913818099033203"
            }
        }
        """
        t = Trade(self.id,
                  symbol,
                  BUY if msg['data']['side'] == 'buy' else SELL,
                  Decimal(msg['data']['size']),
                  Decimal(msg['data']['price']),
                  float(msg['data']['time']) / 1000000000,
                  id=msg['data']['tradeId'],
                  raw=msg)
        await self.callback(TRADES, t, timestamp)
Ejemplo n.º 9
0
 async def _trades(self, msg: dict, timestamp: float):
     """
     "params": {
         "data": [
         {
             "id": 54469813,
             "price": "0.054670",
             "quantity": "0.183",
             "side": "buy",
             "timestamp": "2017-10-19T16:34:25.041Z"
         }
         ],
         "symbol": "ETHBTC"
     }
     """
     pair = self.exchange_symbol_to_std_symbol(msg['symbol'])
     for update in msg['data']:
         t = Trade(self.id,
                   pair,
                   BUY if update['side'] == 'buy' else SELL,
                   Decimal(update['quantity']),
                   Decimal(update['price']),
                   self.timestamp_normalize(update['timestamp']),
                   id=str(update['id']),
                   raw=update)
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 10
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        Doc : https://docs.upbit.com/v1.0.7/reference#시세-체결-조회

        {
            'ty': 'trade'             // Event type
            'cd': 'KRW-BTC',          // Symbol
            'tp': 6759000.0,          // Trade Price
            'tv': 0.03243003,         // Trade volume(amount)
            'tms': 1584257228806,     // Timestamp
            'ttms': 1584257228000,    // Trade Timestamp
            'ab': 'BID',              // 'BID' or 'ASK'
            'cp': 64000.0,            // Change of price
            'pcp': 6823000.0,         // Previous closing price
            'sid': 1584257228000000,  // Sequential ID
            'st': 'SNAPSHOT',         // 'SNAPSHOT' or 'REALTIME'
            'td': '2020-03-15',       // Trade date utc
            'ttm': '07:27:08',        // Trade time utc
            'c': 'FALL',              // Change - 'FALL' / 'RISE' / 'EVEN'
        }
        """

        price = Decimal(msg['tp'])
        amount = Decimal(msg['tv'])
        t = Trade(
            self.id,
            self.exchange_symbol_to_std_symbol(msg['cd']),
            BUY if msg['ab'] == 'BID' else SELL,
            amount,
            price,
            self.timestamp_normalize(msg['ttms']),
            id=str(msg['sid']),
            raw=msg
        )
        await self.callback(TRADES, t, timestamp)
Ejemplo n.º 11
0
 async def _trades(self, msg: dict, timestamp: float):
     """
     {
         "time": 1606292218,
         "channel": "spot.trades",
         "event": "update",
         "result": {
             "id": 309143071,
             "create_time": 1606292218,
             "create_time_ms": "1606292218213.4578",
             "side": "sell",
             "currency_pair": "GT_USDT",
             "amount": "16.4700000000",
             "price": "0.4705000000"
         }
     }
     """
     t = Trade(self.id,
               self.exchange_symbol_to_std_symbol(
                   msg['result']['currency_pair']),
               SELL if msg['result']['side'] == 'sell' else BUY,
               Decimal(msg['result']['amount']),
               Decimal(msg['result']['price']),
               float(msg['result']['create_time_ms']) / 1000,
               id=str(msg['result']['id']),
               raw=msg)
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 12
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        example message:

        {"channel": "trades", "market": "BTC-PERP", "type": "update", "data": [{"id": null, "price": 10738.75,
        "size": 0.3616, "side": "buy", "liquidation": false, "time": "2019-08-03T12:20:19.170586+00:00"}]}
        """
        for trade in msg['data']:
            t = Trade(self.id,
                      self.exchange_symbol_to_std_symbol(msg['market']),
                      BUY if trade['side'] == 'buy' else SELL,
                      Decimal(trade['size']),
                      Decimal(trade['price']),
                      float(self.timestamp_normalize(trade['time'])),
                      id=str(trade['id']),
                      raw=trade)
            await self.callback(TRADES, t, timestamp)
            if bool(trade['liquidation']):
                liq = Liquidation(
                    self.id,
                    self.exchange_symbol_to_std_symbol(msg['market']),
                    BUY if trade['side'] == 'buy' else SELL,
                    Decimal(trade['size']),
                    Decimal(trade['price']),
                    str(trade['id']),
                    FILLED,
                    float(self.timestamp_normalize(trade['time'])),
                    raw=trade)
                await self.callback(LIQUIDATIONS, liq, timestamp)
Ejemplo n.º 13
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        trade msg example

        {
          "seqnum": 21,
          "event": "updated",
          "channel": "trades",
          "symbol": "BTC-USD",
          "timestamp": "2019-08-13T11:30:06.100140Z",
          "side": "sell",
          "qty": 8.5E-5,
          "price": 11252.4,
          "trade_id": "12884909920"
        }
        """
        t = Trade(
            self.id,
            msg['symbol'],
            BUY if msg['side'] == 'buy' else SELL,
            msg['qty'],
            msg['price'],
            self.timestamp_normalize(msg['timestamp']),
            id=msg['trade_id'],
        )
        await self.callback(TRADES, t, timestamp)
Ejemplo n.º 14
0
 async def _trade(self, msg: dict, timestamp: float):
     """
     {
         "arg": {
             "channel": "trades",
             "instId": "BTC-USD-191227"
         },
         "data": [
             {
                 "instId": "BTC-USD-191227",
                 "tradeId": "9",
                 "px": "0.016",
                 "sz": "50",
                 "side": "buy",
                 "ts": "1597026383085"
             }
         ]
     }
     """
     for trade in msg['data']:
         t = Trade(self.id,
                   self.exchange_symbol_to_std_symbol(trade['instId']),
                   BUY if trade['side'] == 'buy' else SELL,
                   Decimal(trade['sz']),
                   Decimal(trade['px']),
                   self.timestamp_normalize(int(trade['ts'])),
                   id=trade['tradeId'],
                   raw=trade)
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 15
0
    async def _trades(self, msg: dict, timestamp: float):
        """
        {'data':
         {
         'microtimestamp': '1562650233964229',      // Event time (micros)
         'amount': Decimal('0.014140160000000001'), // Quantity
         'buy_order_id': 3709484695,                // Buyer order ID
         'sell_order_id': 3709484799,               // Seller order ID
         'amount_str': '0.01414016',                // Quantity string
         'price_str': '12700.00',                   // Price string
         'timestamp': '1562650233',                 // Event time
         'price': Decimal('12700.0'),               // Price
         'type': 1,
         'id': 93215787
         },
         'event': 'trade',
         'channel': 'live_trades_btcusd'
        }
        """
        data = msg['data']
        chan = msg['channel']
        pair = self.exchange_symbol_to_std_symbol(chan.split('_')[-1])

        t = Trade(
            self.id,
            pair,
            BUY if data['type'] == 0 else SELL,
            Decimal(data['amount']),
            Decimal(data['price']),
            self.timestamp_normalize(int(data['microtimestamp'])),
            id=str(data['id']),
            raw=msg
        )
        await self.callback(TRADES, t, timestamp)
Ejemplo n.º 16
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        trade msg example

        {
            'timestamp': '2018-05-19T12:25:26.632Z',
            'symbol': 'XBTUSD',
            'side': 'Buy',
            'size': 40,
            'price': 8335,
            'tickDirection': 'PlusTick',
            'trdMatchID': '5f4ecd49-f87f-41c0-06e3-4a9405b9cdde',
            'grossValue': 479920,
            'homeNotional': Decimal('0.0047992'),
            'foreignNotional': 40
        }
        """
        for data in msg['data']:
            ts = self.timestamp_normalize(data['timestamp'])
            t = Trade(
                self.id,
                self.exchange_symbol_to_std_symbol(data['symbol']),
                BUY if data['side'] == 'Buy' else SELL,
                Decimal(data['size']),
                Decimal(data['price']),
                ts,
                id=data['trdMatchID'],
                raw=data
            )
            await self.callback(TRADES, t, timestamp)
Ejemplo n.º 17
0
 async def _trade(self, msg: dict, timestamp: float):
     """
     {
         "e": "aggTrade",  // Event type
         "E": 123456789,   // Event time
         "s": "BNBBTC",    // Symbol
         "a": 12345,       // Aggregate trade ID
         "p": "0.001",     // Price
         "q": "100",       // Quantity
         "f": 100,         // First trade ID
         "l": 105,         // Last trade ID
         "T": 123456785,   // Trade time
         "m": true,        // Is the buyer the market maker?
         "M": true         // Ignore
     }
     """
     t = Trade(self.id,
               self.exchange_symbol_to_std_symbol(msg['s']),
               SELL if msg['m'] else BUY,
               Decimal(msg['q']),
               Decimal(msg['p']),
               self.timestamp_normalize(msg['T']),
               id=str(msg['a']),
               raw=msg)
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 18
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        {"topic":"trade.BTCUSD",
        "data":[
            {
                "timestamp":"2019-01-22T15:04:33.461Z",
                "symbol":"BTCUSD",
                "side":"Buy",
                "size":980,
                "price":3563.5,
                "tick_direction":"PlusTick",
                "trade_id":"9d229f26-09a8-42f8-aff3-0ba047b0449d",
                "cross_seq":163261271}]}
        """
        data = msg['data']
        for trade in data:
            if isinstance(trade['trade_time_ms'], str):
                ts = int(trade['trade_time_ms'])
            else:
                ts = trade['trade_time_ms']

            t = Trade(
                self.id,
                self.exchange_symbol_to_std_symbol(trade['symbol']),
                BUY if trade['side'] == 'Buy' else SELL,
                Decimal(trade['size']),
                Decimal(trade['price']),
                self.timestamp_normalize(ts),
                id=trade['trade_id'],
                raw=trade
            )
            await self.callback(TRADES, t, timestamp)
Ejemplo n.º 19
0
 async def _trade(self, data: dict, timestamp: float):
     """
     {
         'channel': 'trade',
         'timestamp': 1639080717242,
         'data': [{
             'trade_id': '7016884324',
             'instrument_id': 'BTC-PERPETUAL',
             'price': '47482.50000000',
             'qty': '6000.00000000',
             'side': 'sell',
             'sigma': '0.00000000',
             'is_block_trade': False,
             'created_at': 1639080717195
         }]
     }
     """
     for t in data['data']:
         trade = Trade(self.id,
                       self.exchange_symbol_to_std_symbol(
                           t.get('instrument_id') or t.get('pair')),
                       SELL if t['side'] == 'sell' else BUY,
                       Decimal(t['qty']),
                       Decimal(t['price']),
                       self.timestamp_normalize(t['created_at']),
                       id=t['trade_id'],
                       raw=t)
         await self.callback(TRADES, trade, timestamp)
Ejemplo n.º 20
0
    async def _trades(self, msg: dict, rtimestamp: float):
        '''
        {
            "type": "transaction",
            "content": {
                "list": [
                    {
                        "symbol": "BTC_KRW", // currency code
                        "buySellGb": "1", // type of contract (1: sale contract, 2: buy contract)
                        "contPrice": "10579000", // execution price
                        "contQty": "0.01", // number of contracts
                        "contAmt": "105790.00", // execution amount
                        "contDtm": "2020-01-29 12:24:18.830039", // Signing time
                        "updn": "dn" // comparison with the previous price: up-up, dn-down
                    }
                ]
            }
        }
        '''
        trades = msg.get('content', {}).get('list', [])

        for trade in trades:
            # API ref list uses '-', but market data returns '_'
            symbol = self.exchange_symbol_to_std_symbol(trade['symbol'])
            timestamp = self.timestamp_normalize(trade['contDtm'])
            price = Decimal(trade['contPrice'])
            quantity = Decimal(trade['contQty'])
            side = BUY if trade['buySellGb'] == '2' else SELL

            t = Trade(self.id, symbol, side, quantity, price, timestamp, raw=trade)
            await self.callback(TRADES, t, rtimestamp)
Ejemplo n.º 21
0
 async def trades(self, msg: dict, timestamp: float):
     """
     {
         'deltas': [
             {
                 'id': '8e7f693b-6504-4cb7-9484-835435b147f9',
                 'executedAt': datetime.datetime(2021, 6, 13, 22, 38, 11, 80000, tzinfo=datetime.timezone.utc),
                 'quantity': '0.00693216',
                 'rate': '38808.83000000',
                 'takerSide': 'BUY'
             }
         ],
         'sequence': 204392,
         'marketSymbol': 'BTC-USD'
     }
     """
     pair = self.exchange_symbol_to_std_symbol(msg['marketSymbol'])
     for trade in msg['deltas']:
         t = Trade(self.id,
                   pair,
                   BUY if trade['takerSide'] == 'BUY' else SELL,
                   Decimal(trade['quantity']),
                   Decimal(trade['rate']),
                   self.timestamp_normalize(trade['executedAt']),
                   id=trade['id'],
                   raw=trade)
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 22
0
 async def _trade(self, msg: dict, timestamp: float):
     """
     {
         "jsonrpc":"2.0",
         "method":"channelMessage",
         "params":{
             "channel":"lightning_executions_BTC_JPY",
             "message":[
                 {
                     "id":2084881071,
                     "side":"BUY",
                     "price":2509125.0,
                     "size":0.005,
                     "exec_date":"2020-12-25T21:36:22.8840579Z",
                     "buy_child_order_acceptance_id":"JRF20201225-213620-004123",
                     "sell_child_order_acceptance_id":"JRF20201225-213620-133314"
                 }
             ]
         }
     }
     """
     pair = self.exchange_symbol_to_std_symbol(msg['params']['channel'][21:])
     for update in msg['params']['message']:
         t = Trade(
             self.id,
             pair,
             BUY if update['side'] == 'BUY' else SELL,
             update['size'],
             update['price'],
             self.timestamp_normalize(update['exec_date']),
             raw=update
         )
         await self.callback(TRADES, t, timestamp)
Ejemplo n.º 23
0
 async def _trade(self, msg: dict, timestamp: float):
     '''
     {
         'Channel': 'ticker-eth-aud',
         'Nonce': 78,
         'Data': {
             'TradeGuid': '6d1c2e90-592a-409c-a8d8-58b2d25e0b0b',
             'Pair': 'eth-aud',
             'TradeDate': datetime.datetime(2022, 1, 31, 8, 28, 26, 552573, tzinfo=datetime.timezone(datetime.timedelta(seconds=39600))),
             'Price': Decimal('3650.81'),
             'Volume': Decimal('0.543'),
             'BidGuid': '0430e003-c35e-410e-85f5-f0bb5c40193b',
             'OfferGuid': '559c1dd2-e681-4efc-b49b-14a07c069de4',
             'Side': 'Sell'
         },
         'Time': 1643578106584,
         'Event': 'Trade'
     }
     '''
     t = Trade(
         self.id,
         self.exchange_symbol_to_std_symbol(msg['Data']['Pair']),
         SELL if msg['Data']['Side'] == 'Sell' else BUY,
         Decimal(msg['Data']['Volume']),
         Decimal(msg['Data']['Price']),
         self.timestamp_normalize(msg['Data']['TradeDate']),
         id=msg['Data']['TradeGuid'],
         raw=msg
     )
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 24
0
    async def _book(self, msg: dict, chan_id: int, timestamp: float):
        delta = {BID: [], ASK: []}
        msg_type = msg[0][0]
        pair = None
        # initial update (i.e. snapshot)
        if msg_type == 'i':
            delta = None
            pair = msg[0][1]['currencyPair']
            pair = self.exchange_symbol_to_std_symbol(pair)
            self._l2_book[pair] = OrderBook(self.id,
                                            pair,
                                            max_depth=self.max_depth)
            # 0 is asks, 1 is bids
            order_book = msg[0][1]['orderBook']
            for index, side in enumerate([ASK, BID]):
                for key in order_book[index]:
                    amount = Decimal(order_book[index][key])
                    price = Decimal(key)
                    self._l2_book[pair].book[side][price] = amount
        else:
            pair = self._channel_map[chan_id]
            pair = self.exchange_symbol_to_std_symbol(pair)
            for update in msg:
                msg_type = update[0]
                # order book update
                if msg_type == 'o':
                    side = ASK if update[1] == 0 else BID
                    price = Decimal(update[2])
                    amount = Decimal(update[3])
                    if amount == 0:
                        delta[side].append((price, 0))
                        del self._l2_book[pair].book[side][price]
                    else:
                        delta[side].append((price, amount))
                        self._l2_book[pair].book[side][price] = amount
                elif msg_type == 't':
                    # index 1 is trade id, 2 is side, 3 is price, 4 is amount, 5 is timestamp, 6 is timestamp ms
                    _, order_id, _, price, amount, server_ts, _ = update
                    price = Decimal(price)
                    amount = Decimal(amount)
                    t = Trade(self.id,
                              pair,
                              BUY if update[2] == 1 else SELL,
                              amount,
                              price,
                              float(server_ts),
                              id=order_id,
                              raw=msg)
                    await self.callback(TRADES, t, timestamp)
                else:
                    LOG.warning("%s: Unexpected message received: %s", self.id,
                                msg)

        await self.book_callback(L2_BOOK,
                                 self._l2_book[pair],
                                 timestamp,
                                 delta=delta,
                                 raw=msg)
Ejemplo n.º 25
0
 def _trade_normalize(self, symbol: str, data: dict) -> dict:
     return Trade(self.id,
                  symbol,
                  SELL if data['side'] == 'buy' else BUY,
                  Decimal(data['size']),
                  Decimal(data['price']),
                  data['time'].timestamp(),
                  id=str(data['trade_id']),
                  raw=data)
Ejemplo n.º 26
0
 async def _funding_update(funding: list, timestamp: float):
     order_id, ts, amount, price, period = funding
     t = Trade(self.id,
               pair,
               SELL if amount < 0 else BUY,
               Decimal(abs(Decimal(amount))),
               Decimal(price),
               self.timestamp_normalize(ts),
               id=order_id,
               raw=funding)
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 27
0
 async def _trade_update(trade: list, timestamp: float):
     order_id, ts, amount, price = trade
     t = Trade(
         self.id,
         pair,
         SELL if amount < 0 else BUY,
         Decimal(abs(Decimal(amount))),
         Decimal(price),
         self.timestamp_normalize(ts),
         id=str(order_id),
     )
     await self.callback(TRADES, t, timestamp)
Ejemplo n.º 28
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        update:
        {
           'type': 'channel_data',
           'connection_id': '7b4abf85-f9eb-4f6e-82c0-5479ad5681e9',
           'message_id': 18,
           'id': 'DOGE-USD',
           'channel': 'v3_trades',
           'contents': {
               'trades': [{
                   'size': '390',
                   'side': 'SELL',
                   'price': '0.2334',
                   'createdAt': datetime.datetime(2021, 6, 23, 22, 36, 34, 520000, tzinfo=datetime.timezone.utc)
                }]
            }
        }

        initial message:
        {
            'type': 'subscribed',
            'connection_id': 'ccd8b74c-97b3-491d-a9fc-4a92a171296e',
            'message_id': 4,
            'channel': 'v3_trades',
            'id': 'UNI-USD',
            'contents': {
                'trades': [{
                    'side': 'BUY',
                    'size': '384.1',
                    'price': '17.23',
                    'createdAt': datetime.datetime(2021, 6, 23, 20, 28, 25, 465000, tzinfo=datetime.timezone.utc)
                },
                {
                    'side': 'SELL',
                    'size': '384.1',
                    'price': '17.138',
                    'createdAt': datetime.datetime(2021, 6, 23, 20, 22, 26, 466000, tzinfo=datetime.timezone.utc)},
               }]
            }
        }
        """
        pair = self.exchange_symbol_to_std_symbol(msg['id'])
        for trade in msg['contents']['trades']:
            t = Trade(self.id,
                      pair,
                      BUY if trade['side'] == 'BUY' else SELL,
                      Decimal(trade['size']),
                      Decimal(trade['price']),
                      self.timestamp_normalize(trade['createdAt']),
                      raw=trade)
            await self.callback(TRADES, t, timestamp)
Ejemplo n.º 29
0
    async def _trade(self, msg: dict, timestamp: float):
        """
        {
            "params":
            {
                "data":
                [
                    {
                        "trade_seq": 933,
                        "trade_id": "9178",
                        "timestamp": 1550736299753,
                        "tick_direction": 3,
                        "price": 3948.69,
                        "instrument_name": "BTC-PERPETUAL",
                        "index_price": 3930.73,
                        "direction": "sell",
                        "amount": 10
                    }
                ],
                "channel": "trades.BTC-PERPETUAL.raw"
            },
            "method": "subscription",
            "jsonrpc": "2.0"
        }
        """
        for trade in msg["params"]["data"]:
            t = Trade(
                self.id,
                self.exchange_symbol_to_std_symbol(trade["instrument_name"]),
                BUY if trade['direction'] == 'buy' else SELL,
                Decimal(trade['amount']),
                Decimal(trade['price']),
                self.timestamp_normalize(trade['timestamp']),
                id=trade['trade_id'],
                raw=trade
            )
            await self.callback(TRADES, t, timestamp)

            if 'liquidation' in trade:
                liq = Liquidation(
                    self.id,
                    self.exchange_symbol_to_std_symbol(trade["instrument_name"]),
                    BUY if trade['direction'] == 'buy' else SELL,
                    Decimal(trade['amount']),
                    Decimal(trade['price']),
                    trade['trade_id'],
                    FILLED,
                    self.timestamp_normalize(trade['timestamp']),
                    raw=trade
                )
                await self.callback(LIQUIDATIONS, liq, timestamp)
Ejemplo n.º 30
0
    async def _trades(self, msg: dict, timestamp: float):
        '''
        {
            "channel":"marketdata",
            "market_id":"ETH-BTC",
            "status":"ok","lag":0,
            "recent_trades":[
                {
                    "id":"ETH-BTC:4429182",
                    "price":"0.028229",
                    "quantity":"3.117",
                    "time":"2020-11-01T03:59:06.277Z",
                    "side":"buy","tick_direction":"down"
                },{
                    "id":"ETH-BTC:4429183",
                    "price":"0.028227",
                    "quantity":"1.793",
                    "time":"2020-11-01T03:59:14.528Z",
                    "side":"buy",
                    "tick_direction":"down"
                }
            ],"reset":true
        }

        {
            "channel":"marketdata",
            "market_id":"ETH-BTC",
            "status":"ok","lag":0,
            "recent_trades":[
                {
                    "id":"ETH-BTC:4429282",
                    "price":"0.028235",
                    "quantity":"2.203",
                    "time":"2020-11-01T04:22:15.117Z",
                    "side":"buy",
                    "tick_direction":"down"
                }
            ]
        }
        '''
        pair = self.exchange_symbol_to_std_symbol(msg['market_id'])
        for update in msg['recent_trades']:
            t = Trade(self.id,
                      pair,
                      BUY if update['side'] == 'buy' else SELL,
                      Decimal(update['quantity']),
                      Decimal(update['price']),
                      self.timestamp_normalize(update['time']),
                      id=update['id'],
                      raw=update)
            await self.callback(TRADES, t, timestamp)