-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtinkoffapi.py
90 lines (73 loc) · 3.13 KB
/
tinkoffapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# coding: utf8
from datetime import datetime
from typing import List
from tinkoff.invest import Client, Operation, RequestError
from exceptions import InvalidTinkoffToken, InvalidPortfolioID
from utils import get_now, get_canonical_price
class TinkoffApi:
"""Обёртка для работы с API Тинькова на основе библиотеки tinvest"""
def __init__(self, tinkoff_token: str, broker_account_id: int):
try:
with Client(tinkoff_token) as client:
ok = False
for account in client.users.get_accounts().accounts:
if int(account.id) == broker_account_id:
self._broker_account_started_at = account.opened_date
ok = True
break
if not ok:
raise InvalidPortfolioID()
self._tinkoff_token = tinkoff_token
self._broker_account_id = broker_account_id
except RequestError:
raise InvalidTinkoffToken()
def get_usd_course(self) \
-> float:
"""Отдаёт текущий курс доллара в брокере"""
return self.get_price("BBG0013HGFT4")
def get_price(self, figi: str) \
-> float:
"""Отдаёт текущую цену фиги в брокере"""
with Client(self._tinkoff_token) as client:
price = client.market_data.get_last_prices(figi=[figi]).last_prices[0].price
return get_canonical_price(price)
def get_name(self, figi: str) \
-> str:
"""Отдаёт наименование актива по figi"""
with Client(self._tinkoff_token) as client:
return client.instruments.find_instrument(query=figi).instruments[0].name
def get_ticker(self, figi: str) \
-> str:
"""Отдаёт ticker актива по figi"""
with Client(self._tinkoff_token) as client:
return client.instruments.find_instrument(query=figi).instruments[0].ticker
def get_tinkoff_token(self) \
-> str:
return self._tinkoff_token
def get_broker_account_id(self) \
-> int:
return self._broker_account_id
def get_broker_account_started_at(self) \
-> datetime:
return self._broker_account_started_at
@staticmethod
def get_broker_account_ids(tinkoff_token: str) \
-> List[int]:
with Client(tinkoff_token) as client:
accounts = client.users.get_accounts().accounts
res = []
for account in accounts:
res.append(account.id)
return res
def get_all_operations(self) \
-> List[Operation]:
"""Возвращает все операции в портфеле с указанной даты"""
with Client(self._tinkoff_token) as client:
return client \
.operations \
.get_operations(
account_id=str(self._broker_account_id),
from_=self._broker_account_started_at,
to=get_now()
) \
.operations