def test_ticker():
    t = Ticker(
        'COINBASE',
        'BTC-USD',
        Decimal(10),
        Decimal(100),
        time(),
    )
    d = t.to_dict(numeric_type=str)
    d = json.dumps(d)
    d = json.loads(d)
    t2 = Ticker.from_dict(d)
    assert t == t2
Exemple #2
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {
         'time': 1618876417,
         'channel': 'spot.tickers',
         'event': 'update',
         'result': {
             'currency_pair': 'BTC_USDT',
             'last': '55636.45',
             'lowest_ask': '55634.06',
             'highest_bid': '55634.05',
             'change_percentage': '-0.7634',
             'base_volume': '1138.9062880772',
             'quote_volume': '63844439.342660318028',
             'high_24h': '63736.81',
             'low_24h': '50986.18'
         }
     }
     """
     t = Ticker(self.id,
                self.exchange_symbol_to_std_symbol(
                    msg['result']['currency_pair']),
                Decimal(msg['result']['highest_bid']),
                Decimal(msg['result']['lowest_ask']),
                float(msg['time']),
                raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #3
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {
         "ch":"market.btcusdt.ticker",
         "ts":1630982370526,
         "tick":{
             "open":51732,
             "high":52785.64,
             "low":51000,
             "close":52735.63,
             "amount":13259.24137056181,
             "vol":687640987.4125315,
             "count":448737,
             "bid":52732.88,
             "bidSize":0.036,
             "ask":52732.89,
             "askSize":0.583653,
             "lastPrice":52735.63,
             "lastSize":0.03
         }
     }
     """
     t = Ticker(self.id,
                self.exchange_symbol_to_std_symbol(msg['ch'].split('.')[1]),
                msg['tick']['bid'],
                msg['tick']['ask'],
                self.timestamp_normalize(msg['ts']),
                raw=msg['tick'])
     await self.callback(TICKER, t, timestamp)
Exemple #4
0
 async def _ticker(self, msg: dict, ts: float):
     '''
     {
         'ch': 'ticker/1s',
         'data': {
             'BTCUSDT': {
                 't': 1633804289795,
                 'a': '54813.56',
                 'A': '0.82000',
                 'b': '54810.31',
                 'B': '0.00660',
                 'o': '54517.48',
                 'c': '54829.88',
                 'h': '55493.92',
                 'l': '53685.61',
                 'v': '19025.22558',
                 'q': '1040244549.4048389',
                 'p': '312.40',
                 'P': '0.5730272198935094',
                 'L': 1417964345
             }
         }
     }
     '''
     for sym, ticker in msg['data'].items():
         t = Ticker(self.id,
                    self.exchange_symbol_to_std_symbol(sym),
                    Decimal(ticker['b']),
                    Decimal(ticker['a']),
                    self.timestamp_normalize(ticker['t']),
                    raw=msg)
         await self.callback(TICKER, t, ts)
Exemple #5
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {
         'table': 'spot/ticker',
         'data': [
             {
                 'instrument_id': 'BTC-USD',
                 'last': '3977.74',
                 'best_bid': '3977.08',
                 'best_ask': '3978.73',
                 'open_24h': '3978.21',
                 'high_24h': '3995.43',
                 'low_24h': '3961.02',
                 'base_volume_24h': '248.245',
                 'quote_volume_24h': '988112.225861',
                 'timestamp': '2019-03-22T22:26:34.019Z'
             }
         ]
     }
     """
     for update in msg['data']:
         pair = update['instrument_id']
         update_timestamp = self.timestamp_normalize(update['timestamp'])
         t = Ticker(self.id,
                    pair,
                    Decimal(update['best_bid'])
                    if update['best_bid'] else Decimal(0),
                    Decimal(update['best_ask'])
                    if update['best_ask'] else Decimal(0),
                    update_timestamp,
                    raw=update)
         await self.callback(TICKER, t, timestamp)
Exemple #6
0
 async def _ticker(self, msg: dict, pair: str, timestamp: float):
     """
     [93, {'a': ['105.85000', 0, '0.46100000'], 'b': ['105.77000', 45, '45.00000000'], 'c': ['105.83000', '5.00000000'], 'v': ['92170.25739498', '121658.17399954'], 'p': ['107.58276', '107.95234'], 't': [4966, 6717], 'l': ['105.03000', '105.03000'], 'h': ['110.33000', '110.33000'], 'o': ['109.45000', '106.78000']}]
     channel id, asks: price, wholeLotVol, vol, bids: price, wholeLotVol, close: ...,, vol: ..., VWAP: ..., trades: ..., low: ...., high: ..., open: ...
     """
     t = Ticker(self.id, pair, Decimal(msg[1]['b'][0]), Decimal(msg[1]['a'][0]), None, raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #7
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {
         "jsonrpc": "2.0",
         "method": "channelMessage",
         "params": {
             "channel":  "lightning_ticker_BTC_USD",
             "message": {
                 "product_code": "BTC_USD",
                 "state": "RUNNING",
                 "timestamp":"2020-12-25T21:16:19.3661298Z",
                 "tick_id": 703768,
                 "best_bid": 24228.97,
                 "best_ask": 24252.89,
                 "best_bid_size": 0.4006,
                 "best_ask_size": 0.4006,
                 "total_bid_depth": 64.73938803,
                 "total_ask_depth": 51.99613815,
                 "market_bid_size": 0.0,
                 "market_ask_size": 0.0,
                 "ltp": 24382.25,
                 "volume": 241.953371650000,
                 "volume_by_product": 241.953371650000
             }
         }
     }
     """
     pair = self.exchange_symbol_to_std_symbol(msg['params']['message']['product_code'])
     bid = msg['params']['message']['best_bid']
     ask = msg['params']['message']['best_ask']
     t = Ticker(self.id, pair, bid, ask, self.timestamp_normalize(msg['params']['message']['timestamp']), raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #8
0
    async def _ticker(self, msg: dict, timestamp: float):
        '''
        {
            'type': 'ticker',
            'sequence': 5928281084,
            'product_id': 'BTC-USD',
            'price': '8500.01000000',
            'open_24h': '8217.24000000',
            'volume_24h': '4529.1293778',
            'low_24h': '8172.00000000',
            'high_24h': '8600.00000000',
            'volume_30d': '329178.93594133',
            'best_bid': '8500',
            'best_ask': '8500.01'
        }

        {
            'type': 'ticker',
            'sequence': 5928281348,
            'product_id': 'BTC-USD',
            'price': '8500.00000000',
            'open_24h': '8217.24000000',
            'volume_24h': '4529.13179472',
            'low_24h': '8172.00000000',
            'high_24h': '8600.00000000',
            'volume_30d': '329178.93835825',
            'best_bid': '8500',
            'best_ask': '8500.01',
            'side': 'sell',
            'time': '2018-05-21T00:30:11.587000Z',
            'trade_id': 43736677,
            'last_size': '0.00241692'
        }
        '''
        await self.callback(TICKER, Ticker(self.id, self.exchange_symbol_to_std_symbol(msg['product_id']), Decimal(msg['best_bid']), Decimal(msg['best_ask']), self.timestamp_normalize(msg['time']), raw=msg), timestamp)
Exemple #9
0
    async def _ticker(self, msg: dict, symbol: str, timestamp: float):
        """
        {
            "type":"message",
            "topic":"/market/ticker:BTC-USDT",
            "subject":"trade.ticker",
            "data":{

                "sequence":"1545896668986", // Sequence number
                "price":"0.08",             // Last traded price
                "size":"0.011",             //  Last traded amount
                "bestAsk":"0.08",          // Best ask price
                "bestAskSize":"0.18",      // Best ask size
                "bestBid":"0.049",         // Best bid price
                "bestBidSize":"0.036"     // Best bid size
            }
        }
        """
        t = Ticker(self.id,
                   symbol,
                   Decimal(msg['data']['bestBid']),
                   Decimal(msg['data']['bestAsk']),
                   None,
                   raw=msg)
        await self.callback(TICKER, t, timestamp)
Exemple #10
0
 async def _ticker(self, pair: str, msg: list, timestamp: float):
     if msg[1] == 'hb':
         return  # ignore heartbeats
     # bid, bid_size, ask, ask_size, daily_change, daily_change_percent,
     # last_price, volume, high, low
     bid, _, ask, _, _, _, _, _, _, _ = msg[1]
     t = Ticker(self.id, pair, Decimal(bid), Decimal(ask), None, raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #11
0
 async def _ticker(self, msg: dict, timestamp: float):
     for data in msg['data']:
         t = Ticker(self.id,
                    self.exchange_symbol_to_std_symbol(data['symbol']),
                    Decimal(data['bidPrice']),
                    Decimal(data['askPrice']),
                    self.timestamp_normalize(data['timestamp']),
                    raw=data)
         await self.callback(TICKER, t, timestamp)
Exemple #12
0
 async def ticker(self, symbol: str, retry_count=1, retry_delay=60):
     data = await self._request('GET',
                                f'/products/{symbol}/ticker',
                                retry_count=retry_count,
                                retry_delay=retry_delay)
     return Ticker(self.id,
                   symbol,
                   Decimal(data['bid']),
                   Decimal(data['ask']),
                   data['time'].timestamp(),
                   raw=data)
Exemple #13
0
    async def _ticker(self, msg: dict, timestamp: float):
        """
        example message:

        {"channel": "ticker", "market": "BTC/USD", "type": "update", "data": {"bid": 10717.5, "ask": 10719.0,
        "last": 10719.0, "time": 1564834587.1299787}}
        """
        t = Ticker(self.id,
                   self.exchange_symbol_to_std_symbol(msg['market']),
                   Decimal(msg['data']['bid'] if msg['data']['bid'] else 0.0),
                   Decimal(msg['data']['ask'] if msg['data']['ask'] else 0.0),
                   float(msg['data']['time']),
                   raw=msg)
        await self.callback(TICKER, t, timestamp)
Exemple #14
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {"arg": {"channel": "tickers", "instId": "LTC-USD-200327"}, "data": [{"instType": "SWAP","instId": "LTC-USD-SWAP","last": "9999.99","lastSz": "0.1","askPx": "9999.99","askSz": "11","bidPx": "8888.88","bidSz": "5","open24h": "9000","high24h": "10000","low24h": "8888.88","volCcy24h": "2222","vol24h": "2222","sodUtc0": "2222","sodUtc8": "2222","ts": "1597026383085"}]}
     """
     pair = self.exchange_symbol_to_std_symbol(msg['arg']['instId'])
     for update in msg['data']:
         update_timestamp = self.timestamp_normalize(int(update['ts']))
         t = Ticker(
             self.id,
             pair,
             Decimal(update['bidPx']) if update['bidPx'] else Decimal(0),
             Decimal(update['askPx']) if update['askPx'] else Decimal(0),
             update_timestamp,
             raw=update)
         await self.callback(TICKER, t, timestamp)
Exemple #15
0
 async def ticker(self, msg: dict, timestamp: float):
     """
     {
         'symbol': 'BTC-USDT',
         'lastTradeRate': '38904.35254113',
         'bidRate': '38868.52330647',
         'askRate': '38886.38815323'
     }
     """
     t = Ticker(self.id,
                self.exchange_symbol_to_std_symbol(msg['symbol']),
                Decimal(msg['bidRate']),
                Decimal(msg['askRate']),
                None,
                raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #16
0
    async def _ticker(self, msg: dict, timestamp: float):
        """
        Format:

        currencyPair, last, lowestAsk, highestBid, percentChange, baseVolume,
        quoteVolume, isFrozen, 24hrHigh, 24hrLow, postOnly, maintenance mode

        The postOnly field indicates that new orders posted to the market must be non-matching orders (no taker orders).
        Any orders that would match will be rejected. Maintenance mode indicates that maintenace is being performed
        and orders will be rejected
        """
        pair_id, _, ask, bid, _, _, _, _, _, _, _, _ = msg
        if pair_id not in self._channel_map:
            # Ignore new trading pairs that are added during long running sessions
            return
        pair = self.exchange_symbol_to_std_symbol(self._channel_map[pair_id])
        t = Ticker(self.id, pair, Decimal(bid), Decimal(ask), None, raw=msg)
        await self.callback(TICKER, t, timestamp)
Exemple #17
0
 async def _ticker(self, msg: dict, pair: str, timestamp: float):
     """
     {
         "feed": "ticker_lite",
         "product_id": "PI_XBTUSD",
         "bid": 11726.5,
         "ask": 11732.5,
         "change": 0.0,
         "premium": -0.1,
         "volume": "7.0541503E7",
         "tag": "perpetual",
         "pair": "XBT:USD",
         "dtm": -18117,
         "maturityTime": 0
     }
     """
     t = Ticker(self.id, pair, msg['bid'], msg['ask'], None, raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #18
0
    async def _ticker(self, msg: dict, timestamp: float, symbol: str):
        """
        {
            'action': 'snapshot',
            'arg': {
                'instType': 'sp',
                'channel': 'ticker',
                'instId': 'BTCUSDT'
            },
            'data': [
                {
                    'instId': 'BTCUSDT',
                    'last': '46572.07',
                    'open24h': '46414.54',
                    'high24h': '46767.30',
                    'low24h': '46221.11',
                    'bestBid': '46556.590000',
                    'bestAsk': '46565.670000',
                    'baseVolume': '1927.0855',
                    'quoteVolume': '89120317.8812',
                    'ts': 1649013100029,
                    'labeId': 0
                }
            ]
        }
        """
        key = 'ts'
        if msg['arg']['instType'] == 'mc':
            key = 'systemTime'

        for entry in msg['data']:
            # sometimes snapshots do not have bids/asks in them
            if 'bestBid' not in entry or 'bestAsk' not in entry:
                continue
            t = Ticker(self.id,
                       symbol,
                       Decimal(entry['bestBid']),
                       Decimal(entry['bestAsk']),
                       self.timestamp_normalize(entry[key]),
                       raw=entry)
            await self.callback(TICKER, t, timestamp)
Exemple #19
0
 async def _ticker(self, data: dict, timestamp: float):
     '''
     {
         'channel': 'ticker',
         'timestamp': 1639093870710,
         'data': {
             'time': 1639093870710,
             'instrument_id': 'ETH-PERPETUAL',
             'best_bid': '4155.85000000',
             'best_ask': '4155.90000000',
             'best_bid_qty': '2000.00000000',
             'best_ask_qty': '3000.00000000',
             'ask_sigma': '',
             'bid_sigma': '',
             'last_price': '4157.80000000',
             'last_qty': '1000.00000000',
             'open24h': '4436.75000000',
             'high24h': '4490.00000000',
             'low24h': '4086.60000000',
             'price_change24h': '-0.06287260',
             'volume24h': '1000218.00000000',
             'open_interest': '7564685.00000000',
             'funding_rate': '0.00025108',
             'funding_rate8h': '0.00006396',
             'mark_price': '4155.62874869',
             'min_sell': '4030.50000000',
             'max_buy': '4280.50000000'
         }
     }
     '''
     if data['data']['best_bid'] and data['data']['best_ask']:
         t = Ticker(self.id,
                    self.exchange_symbol_to_std_symbol(
                        data['data'].get('instrument_id')
                        or data['data'].get('pair')),
                    Decimal(data['data']['best_bid']),
                    Decimal(data['data']['best_ask']),
                    self.timestamp_normalize(data['timestamp']),
                    raw=data)
         await self.callback(TICKER, t, timestamp)
Exemple #20
0
 async def _ticker(self, msg: dict, timestamp: float):
     """
     {
         "ask": "0.054464", <- best ask
         "bid": "0.054463", <- best bid
         "last": "0.054463", <- last trade
         "open": "0.057133", <- last trade price 24hrs previous
         "low": "0.053615", <- lowest trade in past 24hrs
         "high": "0.057559", <- highest trade in past 24hrs
         "volume": "33068.346", <- total base currency traded in past 24hrs
         "volumeQuote": "1832.687530809", <- total quote currency traded in past 24hrs
         "timestamp": "2017-10-19T15:45:44.941Z", <- last update or refresh ticker timestamp
         "symbol": "ETHBTC"
     }
     """
     t = Ticker(self.id,
                self.exchange_symbol_to_std_symbol(msg['symbol']),
                Decimal(msg['bid']),
                Decimal(msg['ask']),
                self.timestamp_normalize(msg['timestamp']),
                raw=msg)
     await self.callback(TICKER, t, timestamp)
Exemple #21
0
    async def _ticker(self, msg: dict, timestamp: float):
        """
        {
            'u': 382569232,
            's': 'FETUSDT',
            'b': '0.36031000',
            'B': '1500.00000000',
            'a': '0.36092000',
            'A': '176.40000000'
        }
        """
        pair = self.exchange_symbol_to_std_symbol(msg['s'])
        bid = Decimal(msg['b'])
        ask = Decimal(msg['a'])

        # Binance does not have a timestamp in this update, but the two futures APIs do
        if 'E' in msg:
            ts = self.timestamp_normalize(msg['E'])
        else:
            ts = timestamp

        t = Ticker(self.id, pair, bid, ask, ts, raw=msg)
        await self.callback(TICKER, t, timestamp)
Exemple #22
0
 async def _ticker(self, msg: dict, timestamp: float):
     '''
     {
         'instrument_name': 'BTC_USDT',
         'subscription': 'ticker.BTC_USDT',
         'channel': 'ticker',
         'data': [
             {
                 'i': 'BTC_USDT',
                 'b': Decimal('57689.90'),
                 'k': Decimal('57690.90'),
                 'a': Decimal('57690.90'),
                 't': 1637705099140,
                 'v': Decimal('46427.152283'),
                 'h': Decimal('57985.00'),
                 'l': Decimal('55313.95'),
                 'c': Decimal('1311.15')
             }
         ]
     }
     '''
     for entry in msg['data']:
         await self.callback(TICKER, Ticker(self.id, self.exchange_symbol_to_std_symbol(entry['i']), entry['b'], entry['a'], self.timestamp_normalize(entry['t']), raw=entry), timestamp)
Exemple #23
0
    async def _ticker(self, msg: dict, timestamp: float):
        '''
        {
            "params" : {
                "data" : {
                    "timestamp" : 1550652954406,
                    "stats" : {
                        "volume" : null,
                        "low" : null,
                        "high" : null
                    },
                    "state" : "open",
                    "settlement_price" : 3960.14,
                    "open_interest" : 0.12759952124659626,
                    "min_price" : 3943.21,
                    "max_price" : 3982.84,
                    "mark_price" : 3940.06,
                    "last_price" : 3906,
                    "instrument_name" : "BTC-PERPETUAL",
                    "index_price" : 3918.51,
                    "funding_8h" : 0.01520525,
                    "current_funding" : 0.00499954,
                    "best_bid_price" : 3914.97,
                    "best_bid_amount" : 40,
                    "best_ask_price" : 3996.61,
                    "best_ask_amount" : 50
                    },
                "channel" : "ticker.BTC-PERPETUAL.raw"
            },
            "method" : "subscription",
            "jsonrpc" : "2.0"}
        '''
        pair = self.exchange_symbol_to_std_symbol(
            msg['params']['data']['instrument_name'])
        ts = self.timestamp_normalize(msg['params']['data']['timestamp'])
        t = Ticker(self.id,
                   pair,
                   Decimal(msg["params"]["data"]['best_bid_price']),
                   Decimal(msg["params"]["data"]['best_ask_price']),
                   ts,
                   raw=msg)
        await self.callback(TICKER, t, timestamp)

        if "current_funding" in msg["params"]["data"] and "funding_8h" in msg[
                "params"]["data"]:
            f = Funding(self.id,
                        pair,
                        Decimal(msg['params']['data']['mark_price']),
                        Decimal(msg["params"]["data"]["current_funding"]),
                        None,
                        ts,
                        raw=msg)
            await self.callback(FUNDING, f, timestamp)

        oi = msg['params']['data']['open_interest']
        if pair in self._open_interest_cache and oi == self._open_interest_cache[
                pair]:
            return
        self._open_interest_cache[pair] = oi
        o = OpenInterest(self.id, pair, Decimal(oi), ts, raw=msg)
        await self.callback(OPEN_INTEREST, o, timestamp)
Exemple #24
0
def test_ticker_raises_with_bad_args_if_assertions_enabled():
    with pytest.raises(AssertionError):
        # bid and ask should be Decimal, not str
        Ticker(exchange="", symbol="", bid="1.0", ask="2.0", timestamp=None)
Exemple #25
0
def test_ticker_does_not_raise_with_bad_args_if_assertions_not_enabled():
    # bid and ask should be Decimal, not str, but it should not raise
    Ticker(exchange="", symbol="", bid="1.0", ask="2.0", timestamp=None)