Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_tinkoff-trading-bot-develop/app/stats/handler.py
5935 views
1
import asyncio
2
3
from tinkoff.invest import OrderExecutionReportStatus, AioRequestError
4
5
from app.client import TinkoffClient
6
from app.stats.sqlite_client import StatsSQLiteClient
7
from app.strategies.models import StrategyName
8
from app.utils.quotation import quotation_to_float
9
10
FINAL_ORDER_STATUSES = [
11
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_CANCELLED,
12
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_REJECTED,
13
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL,
14
]
15
16
17
class StatsHandler:
18
def __init__(self, strategy: StrategyName, broker_client: TinkoffClient):
19
self.strategy = strategy
20
self.db = StatsSQLiteClient(db_name="stats.db")
21
self.broker_client = broker_client
22
23
async def handle_new_order(self, account_id: str, order_id: str) -> None:
24
"""
25
This method is called when new order is created.
26
It waits for the order to be filled, canceled, or rejected
27
and logs its information to the database
28
29
To prevent affecting the strategy execution,
30
this method can be called with asyncio.create_task()
31
32
:param account_id: id of the account the order was created for
33
:param order_id: id of the order to track its status
34
:return: None
35
"""
36
try:
37
order_state = await self.broker_client.get_order_state(
38
account_id=account_id, order_id=order_id
39
)
40
except AioRequestError:
41
return
42
self.db.add_order(
43
order_id=order_id,
44
figi=order_state.figi,
45
order_direction=str(order_state.direction),
46
price=quotation_to_float(order_state.total_order_amount),
47
quantity=order_state.lots_requested,
48
status=str(order_state.execution_report_status),
49
)
50
while order_state.execution_report_status not in FINAL_ORDER_STATUSES:
51
await asyncio.sleep(10)
52
order_state = await self.broker_client.get_order_state(
53
account_id=account_id, order_id=order_id
54
)
55
self.db.update_order_status(
56
order_id=order_id, status=str(order_state.execution_report_status)
57
)
58
59