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.")