Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
'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 = pair_exchange_to_std(chan.split('_')[-1])
side = BUY if data['type'] == 0 else SELL
amount = Decimal(data['amount'])
price = Decimal(data['price'])
ts = int(data['microtimestamp'])
order_id = data['id']
await self.callback(TRADES, feed=self.id,
pair=pair,
side=side,
amount=amount,
price=price,
timestamp=timestamp_normalize(self.id, ts),
receipt_timestamp=timestamp,
order_id=order_id)
"b": [ // Bids to be updated
[
"0.0024", // Price level to be updated
"10" // Quantity
]
],
"a": [ // Asks to be updated
[
"0.0026", // Price level to be updated
"100" // Quantity
]
]
}
"""
exchange_pair = pair
pair = pair_exchange_to_std(pair)
if pair not in self.l2_book:
await self._snapshot(exchange_pair)
skip_update, forced = self._check_update_id(pair, msg)
if skip_update:
return
delta = {BID: [], ASK: []}
ts = msg['E']
for s, side in (('b', BID), ('a', ASK)):
for update in msg[s]:
price = Decimal(update[0])
amount = Decimal(update[1])
'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'])
await self.callback(TRADES, feed=self.id,
order_id=msg['sid'],
pair=pair_exchange_to_std(msg['cd']),
side=BUY if msg['ab'] == 'BID' else SELL,
amount=amount,
price=price,
timestamp=timestamp_normalize(self.id, msg['ttms']),
receipt_timestamp=timestamp)
{'ap': 6735000.0, 'as': 1.08739294, 'bp': 6713000.0, 'bs': 0.46785444},
{'ap': 6737000.0, 'as': 3.34450006, 'bp': 6712000.0, 'bs': 0.01300915},
{'ap': 6738000.0, 'as': 0.26, 'bp': 6711000.0, 'bs': 0.24701799},
{'ap': 6739000.0, 'as': 0.086, 'bp': 6710000.0, 'bs': 1.97964014},
{'ap': 6740000.0, 'as': 0.00658782, 'bp': 6708000.0, 'bs': 0.0002},
{'ap': 6741000.0, 'as': 0.8004, 'bp': 6707000.0, 'bs': 0.02022364},
{'ap': 6742000.0, 'as': 0.11040396, 'bp': 6706000.0, 'bs': 0.29082183},
{'ap': 6743000.0, 'as': 1.1, 'bp': 6705000.0, 'bs': 0.94493254}],
'st': 'REALTIME', // Streaming type - 'REALTIME' or 'SNAPSHOT'
'tas': 20.67627941, // Total ask size for given 15 depth (not total ask order size)
'tbs': 622.93769692, // Total bid size for given 15 depth (not total bid order size)
'tms': 1584263923870, // Timestamp
}
"""
pair = pair_exchange_to_std(msg['cd'])
orderbook_timestamp = timestamp_normalize(self.id, msg['tms'])
if pair not in self.l2_book:
await self._snapshot(pair)
# forced = True if the snapshot received, otherwise(realtime) forced set to be false
forced = True if msg['st'] == 'SNAPSHOT' else False
update = {
BID: sd({
Decimal(unit['bp']): Decimal(unit['bs'])
for unit in msg['obu'] if unit['bp'] > 0
}),
ASK: sd({
Decimal(unit['ap']): Decimal(unit['as'])
for unit in msg['obu'] if unit['ap'] > 0
})
'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'])
await self.callback(TRADES, feed=self.id,
order_id=msg['sid'],
pair=pair_exchange_to_std(msg['cd']),
side=BUY if msg['ab'] == 'BID' else SELL,
amount=amount,
price=price,
timestamp=timestamp_normalize(self.id, msg['ttms']),
receipt_timestamp=timestamp)
async def _book(self, msg: dict, timestamp: float):
pair = pair_exchange_to_std(msg['ch'].split('.')[1])
data = msg['tick']
forced = pair not in self.l2_book
update = {
BID: sd({
Decimal(price): Decimal(amount)
for price, amount in data['bids']
}),
ASK: sd({
Decimal(price): Decimal(amount)
for price, amount in data['asks']
})
}
if not forced:
self.previous_book[pair] = self.l2_book[pair]
self.l2_book[pair] = update
await self.book_callback(self.l2_book[pair], L2_BOOK, pair, forced, False, timestamp_normalize(self.id, msg['ts']), timestamp)
async def _l2_book(self, msg: dict, timestamp: float):
data = msg['data']
chan = msg['channel']
ts = int(data['microtimestamp'])
pair = pair_exchange_to_std(chan.split('_')[-1])
forced = False
delta = {BID: [], ASK: []}
if pair in self.last_update_id:
if data['timestamp'] < self.last_update_id[pair]:
return
else:
forced = True
del self.last_update_id[pair]
for side in (BID, ASK):
for update in data[side + 's']:
price = Decimal(update[0])
size = Decimal(update[1])
if size == 0:
if price in self.l2_book[pair][side]:
del self.l2_book[pair][side][price]
delta[side].append((price, size))
else:
self.l2_book[pair][side][price] = size
delta[side].append((price, size))
await self.book_callback(self.l2_book[pair], L2_BOOK, pair, forced, delta, timestamp_normalize(self.id, ts), timestamp)
data = self._post_private('/private/TradesHistory', params)
if len(data['error']) != 0:
return data
ret = []
for trade_id, trade in data['result']['trades'].items():
sym = trade['pair']
sym = sym.replace('XX', 'X')
sym = sym.replace('ZUSD', 'USD')
sym = sym.replace('ZCAD', 'CAD')
sym = sym.replace('ZEUR', 'EUR')
sym = sym.replace('ZGBP', 'GBP')
sym = sym.replace('ZJPY', 'JPY')
if pair_exchange_to_std(sym) != symbol:
continue
ret.append({
'price': Decimal(trade['price']),
'amount': Decimal(trade['vol']),
'timestamp': trade['time'],
'side': SELL if trade['type'] == 'sell' else BUY,
'fee_currency': symbol.split('-')[1],
'fee_amount': Decimal(trade['fee']),
'trade_id': trade_id,
'order_id': trade['ordertxid']
})
return ret
async def _trade(self, msg: dict, timestamp: float):
"""
{
'ch': 'market.btcusd.trade.detail',
'ts': 1549773923965,
'tick': {
'id': 100065340982,
'ts': 1549757127140,
'data': [{'id': '10006534098224147003732', 'amount': Decimal('0.0777'), 'price': Decimal('3669.69'), 'direction': 'buy', 'ts': 1549757127140}]}}
"""
for trade in msg['tick']['data']:
await self.callback(TRADES,
feed=self.id,
pair=pair_exchange_to_std(msg['ch'].split('.')[1]),
order_id=trade['id'],
side=BUY if trade['direction'] == 'buy' else SELL,
amount=Decimal(trade['amount']),
price=Decimal(trade['price']),
timestamp=timestamp_normalize(self.id, trade['ts']),
receipt_timestamp=timestamp)
def main():
f = FeedHandler()
f.add_feed(Bybit(pairs=['BTC-USD', 'ETH-USD', 'XRP-USD', 'EOS-USD'], channels=[TRADES], callbacks={TRADES: TradeCallback(trade)}))
f.add_feed(Bybit(pairs=['BTC-USD', 'ETH-USD', 'XRP-USD', 'EOS-USD'], channels=[L2_BOOK], callbacks={L2_BOOK: BookCallback(book)}))
f.run()