Path: blob/master/ invest-robot-contest_tinkoff-trading-bot-develop/app/stats/handler.py
5935 views
import asyncio12from tinkoff.invest import OrderExecutionReportStatus, AioRequestError34from app.client import TinkoffClient5from app.stats.sqlite_client import StatsSQLiteClient6from app.strategies.models import StrategyName7from app.utils.quotation import quotation_to_float89FINAL_ORDER_STATUSES = [10OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_CANCELLED,11OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_REJECTED,12OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL,13]141516class StatsHandler:17def __init__(self, strategy: StrategyName, broker_client: TinkoffClient):18self.strategy = strategy19self.db = StatsSQLiteClient(db_name="stats.db")20self.broker_client = broker_client2122async def handle_new_order(self, account_id: str, order_id: str) -> None:23"""24This method is called when new order is created.25It waits for the order to be filled, canceled, or rejected26and logs its information to the database2728To prevent affecting the strategy execution,29this method can be called with asyncio.create_task()3031:param account_id: id of the account the order was created for32:param order_id: id of the order to track its status33:return: None34"""35try:36order_state = await self.broker_client.get_order_state(37account_id=account_id, order_id=order_id38)39except AioRequestError:40return41self.db.add_order(42order_id=order_id,43figi=order_state.figi,44order_direction=str(order_state.direction),45price=quotation_to_float(order_state.total_order_amount),46quantity=order_state.lots_requested,47status=str(order_state.execution_report_status),48)49while order_state.execution_report_status not in FINAL_ORDER_STATUSES:50await asyncio.sleep(10)51order_state = await self.broker_client.get_order_state(52account_id=account_id, order_id=order_id53)54self.db.update_order_status(55order_id=order_id, status=str(order_state.execution_report_status)56)575859