async def liquidator(trader: Trader) -> None: tlog("liquidator() task starting") try: to_market_close = trader.get_time_market_close() if not to_market_close: return else: to_market_close -= timedelta(minutes=15) tlog(f"liquidator() - waiting for market close: {to_market_close}") await asyncio.sleep(to_market_close.total_seconds()) except asyncio.CancelledError: tlog("liquidator() cancelled during sleep") except KeyboardInterrupt: tlog("liquidator() - Caught KeyboardInterrupt") tlog("liquidator() -> starting to liquidate positions") try: for symbol in trading_data.positions: tlog(f"liquidator() -> checking {symbol}") if (trading_data.positions[symbol] != 0 and trading_data.last_used_strategy[symbol].type == StrategyType.DAY_TRADE): retry = 5 while retry: try: await liquidate( symbol, int(trading_data.positions[symbol]), trader, ) break except ConnectionError: await trader.reconnect() await asyncio.sleep(1) retry -= 1 else: tlog( f"liquidator(): {symbol} {trading_data.positions[symbol]} {trading_data.last_used_strategy[symbol].type} {trading_data.last_used_strategy[symbol].name}" ) except asyncio.CancelledError: tlog("liquidator() cancelled") except KeyboardInterrupt: tlog("liquidator() - Caught KeyboardInterrupt") tlog("liquidator() task completed")
async def teardown_task(trader: Trader, tasks: List[asyncio.Task]) -> None: tlog(f"consumer-teardown_task() - starting ") if not config.market_close: tlog( "we're probably in market schedule by-pass mode, exiting consumer-teardown_task()" ) return to_market_close = trader.get_time_market_close() tlog( f"consumer-teardown_task() - waiting for market close: {to_market_close}" ) try: await asyncio.sleep(to_market_close.total_seconds() + 60 * 5 ) # type: ignore tlog("consumer-teardown_task() starting") await end_time("market close") tlog("consumer-teardown_task(): requesting tasks to cancel") for task in tasks: task.cancel() try: await task except asyncio.CancelledError: tlog("consumer-teardown_task(): task is cancelled now") except asyncio.CancelledError: tlog("consumer-teardown_task() cancelled during sleep") except KeyboardInterrupt: tlog("consumer-teardown_task() - Caught KeyboardInterrupt") except Exception as e: tlog( f"consumer-teardown_task() - exception of type {type(e).__name__} with args {e.args}" ) # asyncio.get_running_loop().stop() finally: tlog("consumer-teardown_task() task done.")
def get_position(trader: Trader, symbol: str) -> int: try: return trader.get_position(symbol) except Exception: return 0
async def load_current_positions( trading_api: Trader, symbols: List[str], strategy: Strategy, ) -> int: loaded = 0 for symbol in symbols: try: position = trading_api.get_position(symbol) except Exception as e: tlog(f"failed to load open position for {symbol} w/ {e}") continue if position: try: ( prev_run_id, price, stop_price, target_price, indicators, timestamp, ) = await NewTrade.load_latest( config.db_conn_pool, symbol=symbol, strategy_name=strategy.name, ) if prev_run_id is None: continue tlog( f"loading current position for {symbol} for strategy {strategy.name}" ) trading_data.positions[symbol] = int(position.qty) trading_data.stop_prices[symbol] = stop_price trading_data.target_prices[symbol] = target_price trading_data.latest_cost_basis[ symbol ] = trading_data.latest_scalp_basis[symbol] = price trading_data.open_order_strategy[symbol] = strategy trading_data.last_used_strategy[symbol] = strategy trading_data.buy_time[symbol] = timestamp.astimezone(tz=nyc) await NewTrade.rename_algo_run_id( strategy.algo_run.run_id, prev_run_id, symbol ) tlog( f"moved {symbol} from {prev_run_id} to {strategy.algo_run.run_id}" ) loaded += 1 except ValueError: pass except Exception as e: traceback.print_exc() tlog( f"load_current_positions() for {symbol} could not load latest trade from db due to exception of type {type(e).__name__} with args {e.args}" ) return loaded