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/client.py
5932 views
1
from datetime import datetime
2
from typing import Optional, List
3
4
from tinkoff.invest import (
5
AsyncClient,
6
CandleInterval,
7
Quotation,
8
OrderDirection,
9
OrderType,
10
PostOrderResponse,
11
GetLastPricesResponse,
12
OrderState,
13
GetTradingStatusResponse,
14
)
15
from tinkoff.invest.async_services import AsyncServices
16
17
from app.settings import settings
18
19
20
class TinkoffClient:
21
"""
22
Wrapper for tinkoff.invest.AsyncClient.
23
Takes responsibility for choosing correct function to call basing on sandbox mode flag.
24
"""
25
26
def __init__(self, token: str, sandbox: bool = False):
27
self.token = token
28
self.sandbox = sandbox
29
self.client: Optional[AsyncServices] = None
30
31
async def ainit(self):
32
self.client = await AsyncClient(token=self.token, app_name="qwertyo1").__aenter__()
33
34
async def get_orders(self, **kwargs):
35
if self.sandbox:
36
return await self.client.sandbox.get_sandbox_orders(**kwargs)
37
return await self.client.orders.get_orders(**kwargs)
38
39
async def get_portfolio(self, **kwargs):
40
if self.sandbox:
41
return await self.client.sandbox.get_sandbox_portfolio(**kwargs)
42
return await self.client.operations.get_portfolio(**kwargs)
43
44
async def get_accounts(self):
45
if self.sandbox:
46
return await self.client.sandbox.get_sandbox_accounts()
47
return await self.client.users.get_accounts()
48
49
async def get_all_candles(self, **kwargs):
50
async for candle in self.client.get_all_candles(**kwargs):
51
yield candle
52
53
async def get_last_prices(self, **kwargs) -> GetLastPricesResponse:
54
return await self.client.market_data.get_last_prices(**kwargs)
55
56
async def post_order(self, **kwargs) -> PostOrderResponse:
57
if self.sandbox:
58
return await self.client.sandbox.post_sandbox_order(**kwargs)
59
return await self.client.orders.post_order(**kwargs)
60
61
async def get_order_state(self, **kwargs) -> OrderState:
62
if self.sandbox:
63
return await self.client.sandbox.get_sandbox_order_state(**kwargs)
64
return await self.client.orders.get_order_state(**kwargs)
65
66
async def get_trading_status(self, **kwargs) -> GetTradingStatusResponse:
67
return await self.client.market_data.get_trading_status(**kwargs)
68
69
70
client = TinkoffClient(token=settings.token, sandbox=settings.sandbox)
71
72