async def fetch_ticks(self, from_id: int = None, start_time: int = None, end_time: int = None, do_print: bool = True): params = {'symbol': self.symbol, 'limit': 1000} if from_id is not None: params['fromId'] = max(0, from_id) if start_time is not None: params['startTime'] = start_time if end_time is not None: params['endTime'] = end_time try: fetched = await self.private_get(self.endpoints['ticks'], params) except Exception as e: print('error fetching ticks a', e) return [] try: ticks = [{'trade_id': int(t['a']), 'price': float(t['p']), 'qty': float(t['q']), 'timestamp': int(t['T']), 'is_buyer_maker': t['m']} for t in fetched] if do_print: print_(['fetched ticks', self.symbol, ticks[0]['trade_id'], ts_to_date(float(ticks[0]['timestamp']) / 1000)]) except Exception as e: print('error fetching ticks b', e, fetched) ticks = [] if do_print: print_(['fetched no new ticks', self.symbol]) return ticks
async def start_websocket(self) -> None: self.stop_websocket = False uri = f"wss://fstream.binance.com/ws/{self.symbol.lower()}@aggTrade" print_([uri]) try: print(await self.cc.fapiPrivate_post_margintype(params={'symbol': self.symbol, 'marginType': 'CROSSED'})) except Exception as e: print(e) try: print(await self.cc.fapiPrivate_post_leverage(params={'symbol': self.symbol, 'leverage': int(self.leverage)})) except Exception as e: print(e) await self.update_position() async with websockets.connect(uri) as ws: async for msg in ws: if msg is None: continue data = json.loads(msg) price = float(data['p']) trade_id = data['a'] if data['m']: self.ob[0] = price else: self.ob[1] = price self.trade_id = trade_id self.price = price if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) elif self.trade_id % 10 == 0: self.flush_stuck_locks() if self.stop_websocket: break
async def init_exchange_config(self): try: print(await self.private_post(self.endpoints['margin_type'], {'symbol': self.symbol, 'marginType': 'CROSSED'})) except Exception as e: print(e) try: lev = await self.execute_leverage_change() print_([lev]) if self.market_type == 'linear_perpetual': self.max_pos_size_ito_usdt = float(lev['maxNotionalValue']) print('max pos size in terms of usdt', self.max_pos_size_ito_usdt) elif self.market_type == 'inverse_coin_margined': self.max_pos_size_ito_coin = float(lev['maxQty']) print('max pos size in terms of coin', self.max_pos_size_ito_coin) except Exception as e: print(e) try: res = await self.private_post(self.endpoints['position_side'], {'dualSidePosition': 'true'}) print(res) except Exception as e: if '"code":-4059' not in e.args[0]: print(e) print('unable to set hedge mode, aborting') raise Exception('failed to set hedge mode') await self.check_if_other_positions()
async def start_websocket(self) -> None: self.stop_websocket = False uri = f"{self.endpoints['websocket']}/ws/{self.symbol.lower()}@aggTrade" print_([uri]) await self.update_position() await self.init_exchange_settings() k = 1 async with websockets.connect(uri) as ws: async for msg in ws: if msg is None: continue data = json.loads(msg) price = float(data['p']) trade_id = data['a'] if data['m']: self.ob[0] = price else: self.ob[1] = price if price != self.price: self.ema = calc_ema(self.ema_alpha, self.ema_alpha_, self.ema, price) self.price = price if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) if k % 10 == 0: self.flush_stuck_locks() k = 1 if self.stop_websocket: break k += 1
async def start_websocket(self) -> None: self.stop_websocket = False uri = f"wss://stream.bybit.com/realtime" print_([uri]) await self.init_indicators() await self.update_position() try: leverage_ = 0 if self.settings['cross_mode'] else self.leverage print(await self.cc.v2_private_post_position_leverage_save( params={ 'symbol': self.symbol, 'leverage': leverage_ })) except Exception as e: print('error starting websocket', e) param = {'op': 'subscribe', 'args': ['trade.' + self.symbol]} k = 1 async with websockets.connect(uri) as ws: await ws.send(json.dumps(param)) async for msg in ws: if msg is None: continue data = json.loads(msg) price_changed = False try: for e in data['data']: if e['price'] != self.price: if e['side'] == 'Buy': self.ob[1] = e['price'] elif e['side'] == 'Sell': self.ob[0] = e['price'] self.price = e['price'] price_changed = True self.update_indicators({ 'timestamp': e['trade_time_ms'], 'price': e['price'], 'side': e['side'].lower(), 'qty': e['size'] }) except Exception as e: if 'success' not in data: print('error in websocket streamed data', e) if price_changed: if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) if k % 10 == 0: self.flush_stuck_locks() k = 1 k += 1
async def start_websocket(self) -> None: self.stop_websocket = False uri = f"wss://fstream.binance.com/ws/{self.symbol.lower()}@aggTrade" print_([uri]) try: mode = 'CROSSED' if self.settings['cross_mode'] else 'ISOLATED' print(await self.cc.fapiPrivate_post_margintype(params={ 'symbol': self.symbol, 'marginType': mode })) except Exception as e: print(e) try: lev = await self.cc.fapiPrivate_post_leverage( params={ 'symbol': self.symbol, 'leverage': int(self.leverage) }) self.max_pos_size_ito_usdt = float(lev['maxNotionalValue']) print('max pos size in terms of usdt', self.max_pos_size_ito_usdt) except Exception as e: print(e) await self.init_indicators() await self.update_position() k = 1 async with websockets.connect(uri) as ws: async for msg in ws: if msg is None: continue data = json.loads(msg) price = float(data['p']) trade_id = data['a'] if data['m']: self.ob[0] = price else: self.ob[1] = price if price != self.price: self.update_indicators({ 'timestamp': data['T'], 'price': price, 'side': 'sell' if data['m'] else 'buy', 'qty': float(data['q']) }) self.price = price if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) elif k % 10 == 0: self.flush_stuck_locks() k = 1 if self.stop_websocket: break k += 1
async def fetch_trades(cc, symbol: str, from_id: int = None) -> [dict]: params = {'symbol': symbol, 'limit': 1000} if from_id: params['fromId'] = from_id fetched_trades = await cc.fapiPublic_get_aggtrades(params=params) trades = [{'trade_id': int(t['a']), 'price': float(t['p']), 'qty': float(t['q']), 'timestamp': t['T'], 'is_buyer_maker': t['m']} for t in fetched_trades] print_(['fetched trades', symbol, trades[0]['trade_id'], ts_to_date(trades[0]['timestamp'] / 1000)]) return trades
async def fetch_ticks(cc, symbol: str, from_id: int = None, do_print=True) -> [dict]: params = {'symbol': symbol, 'limit': 1000} if from_id: params['from'] = max(0, from_id) try: fetched_trades = await cc.v2_public_get_trading_records(params=params) except Exception as e: print(e) return [] trades = [format_tick(t) for t in fetched_trades['result']] if do_print: print_(['fetched trades', symbol, trades[0]['trade_id'], ts_to_date(trades[0]['timestamp'] / 1000)]) return trades
async def fetch_trades(cc, symbol: str, from_id: int = None) -> [dict]: params = {'symbol': symbol, 'limit': 1000} if from_id: params['from'] = from_id fetched_trades = await cc.public_get_trading_records(params=params) trades = [{ 'trade_id': int(t['id']), 'side': t['side'], 'price': t['price'], 'qty': t['qty'], 'timestamp': date_to_ts(t['time'][:-1]) } for t in fetched_trades['result']] print_([ 'fetched trades', symbol, trades[0]['trade_id'], ts_to_date(trades[0]['timestamp'] / 1000) ]) return trades
async def start_websocket(self) -> None: self.stop_websocket = False uri = f"wss://stream.bybit.com/realtime" print_([uri]) await self.update_position() if self.position['leverage'] != self.leverage: try: print(await self.cc.user_post_leverage_save(params={ 'symbol': self.symbol, 'leverage': 0 })) except Exception as e: print('error starting websocket', e) await self.init_emas() param = {'op': 'subscribe', 'args': ['trade.' + self.symbol]} k = 1 async with websockets.connect(uri) as ws: await ws.send(json.dumps(param)) async for msg in ws: if msg is None: continue data = json.loads(msg) try: for e in data['data']: for span in self.ema_spans: self.emas[span] = calc_new_ema( self.price, e['price'], self.emas[span], alpha=self.ema_alphas[span]) self.price = e['price'] if e['side'] == 'Buy': self.ob[1] = e['price'] elif e['side'] == 'Sell': self.ob[0] = e['price'] except Exception as e: if 'success' not in data: print('error in websocket streamed data', e) if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) elif k % 10 == 0: self.flush_stuck_locks() k = 1 k += 1
async def fetch_ticks(self, from_id: int = None, do_print: bool = True): params = {'symbol': self.symbol, 'limit': 1000} if from_id is not None: params['from'] = max(0, from_id) try: ticks = await self.public_get(self.endpoints['ticks'], params) except Exception as e: print('error fetching ticks', e) return [] try: trades = list(map(format_tick, ticks['result'])) if do_print: print_(['fetched trades', self.symbol, trades[0]['trade_id'], ts_to_date(float(trades[0]['timestamp']) / 1000)]) except: trades = [] if do_print: print_(['fetched no new trades', self.symbol]) return trades
async def start_websocket(self) -> None: self.stop_websocket = False uri = self.endpoints['websocket_url'] print_([uri]) await self.init_exchange_settings() param = {'op': 'subscribe', 'args': ['trade.' + self.symbol]} k = 1 async with websockets.connect(uri) as ws: await ws.send(json.dumps(param)) async for msg in ws: if msg is None: continue data = json.loads(msg) price_changed = False try: for e in data['data']: price = float(e['price']) if price != self.price: if e['side'] == 'Buy': self.ob[1] = price elif e['side'] == 'Sell': self.ob[0] = price self.price = price price_changed = True self.ema = calc_ema(self.ema_alpha, self.ema_alpha_, self.ema, price) except Exception as e: if 'success' not in data: print('error in websocket streamed data', e) if price_changed: if self.ts_locked['decide'] < self.ts_released['decide']: asyncio.create_task(self.decide()) if k % 10 == 0: self.flush_stuck_locks() k = 1 k += 1