Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_trading_bot-master/trading/get_account_info.py
5932 views
1
from tinkoff.invest import Client, Quotation
2
from trading.trade_help import quotation_to_float
3
import pandas as pd
4
from config.personal_data import get_token, get_account_type, get_account
5
import sqlite3 as sl
6
import dataframe_image as dfi
7
from trading.trade_help import get_exchange_rate, get_currency_sing
8
from trading.get_securities import security_name_by_figi
9
10
'''
11
12
Тут представлены все функции, которые позволяют получить какую-либо информацию о счёте
13
14
Все данные будут храниться в pandas DataFrame для дальнейшей обработки
15
16
Все значения, где количество или суммы представлены с помощью units (целая часть) и nano (дробная часть),
17
сразу переводятся в дробные числа для удобства с помощью функции total_quantity.
18
19
'''
20
21
'''
22
Функция для получения информации о свободной валюте на счёте
23
'''
24
25
26
def get_all_currency(user_id, account_id="", account_type=""):
27
with Client(get_token(user_id)) as client:
28
29
if account_id == "":
30
account_id = get_account(user_id=user_id)
31
32
if account_type == "":
33
account_type = get_account_type(user_id=user_id)
34
35
if account_type == "sandbox":
36
positions = client.sandbox.get_sandbox_positions(account_id=account_id)
37
else:
38
positions = client.operations.get_positions(account_id=account_id)
39
40
currency_df = pd.DataFrame(
41
{
42
"currency": i.currency,
43
"name": get_currency_name(user_id=user_id, currency=i.currency),
44
"sign": get_currency_sing(currency=i.currency),
45
"exchange_rate": get_exchange_rate(currency=i.currency),
46
"sum": quotation_to_float(Quotation(units=i.units, nano=i.nano)),
47
"sum_in_ruble": quotation_to_float(Quotation(units=i.units, nano=i.nano)) * get_exchange_rate(
48
currency=i.currency),
49
"units": i.units,
50
"nano": i.nano,
51
} for i in positions.money
52
)
53
54
return currency_df
55
56
57
'''
58
Функция для получения названия валюты
59
Необходима для вывода информации по доступной валюте, так Тинькофф предоставляет только
60
'''
61
62
63
def get_currency_name(user_id, currency):
64
with Client(get_token(user_id)) as client:
65
pos = client.instruments.currencies()
66
67
for i in pos.instruments:
68
if i.nominal.currency == currency:
69
return i.name
70
71
return ""
72
73
74
'''
75
Функция для получения информации о всех купленных бумагах
76
'''
77
78
79
def get_all_securities(user_id, account_id="", account_type=""):
80
with Client(get_token(user_id)) as client:
81
82
if account_id == "":
83
account_id = get_account(user_id=user_id)
84
85
if account_type == "":
86
account_type = get_account_type(user_id=user_id)
87
88
if account_type == "sandbox":
89
portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)
90
else:
91
portfolio = client.operations.get_portfolio(account_id=account_id)
92
93
portfolio_df = pd.DataFrame(
94
{
95
"figi": i.figi,
96
"instrument": i.instrument_type,
97
"security_name": security_name_by_figi(figi=i.figi,user_id=user_id),
98
"quantity": quotation_to_float(i.quantity),
99
"average_price": quotation_to_float(i.average_position_price),
100
"exp_yield": quotation_to_float(i.expected_yield),
101
"nkd": quotation_to_float(i.current_nkd),
102
"average_price_pt": quotation_to_float(i.average_position_price_pt),
103
"current_price": quotation_to_float(i.current_price),
104
"average_price_fifo": quotation_to_float(i.average_position_price_fifo),
105
"lots": quotation_to_float(i.quantity_lots),
106
"currency": i.average_position_price.currency,
107
"currency_sign": get_currency_sing(i.average_position_price.currency)
108
} for i in portfolio.positions
109
)
110
111
return portfolio_df
112
113
114
'''
115
Функция для получения статистики по счёту
116
Суммы по всем активам и предполагаемый доход/убыток
117
'''
118
119
120
def get_all_stat(user_id, account_id="", account_type=""):
121
with Client(get_token(user_id)) as client:
122
123
if account_id == "":
124
account_id = get_account(user_id=user_id)
125
126
if account_type == "":
127
account_type = get_account_type(user_id=user_id)
128
129
if account_type == "sandbox":
130
portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)
131
else:
132
portfolio = client.operations.get_portfolio(account_id=account_id)
133
134
stat_df = pd.DataFrame(
135
{
136
"sum_shares": quotation_to_float(portfolio.total_amount_shares),
137
"sum_bonds": quotation_to_float(portfolio.total_amount_bonds),
138
"sum_etf": quotation_to_float(portfolio.total_amount_etf),
139
"sum_curr": quotation_to_float(portfolio.total_amount_currencies),
140
"sum_fut": quotation_to_float(portfolio.total_amount_futures),
141
"sum_total": quotation_to_float(portfolio.total_amount_shares) + quotation_to_float(
142
portfolio.total_amount_bonds) + quotation_to_float(portfolio.total_amount_etf) + quotation_to_float(
143
portfolio.total_amount_currencies) + quotation_to_float(portfolio.total_amount_futures),
144
"exp_yield": quotation_to_float(portfolio.expected_yield),
145
146
}, index=[0]
147
)
148
149
return stat_df
150
151
152
'''
153
Функция для получения информации о количестве доступных лотов по figi
154
155
Данная функция используется для проверки в боте, можно ли продать указанное количество акций
156
'''
157
158
159
def get_lots_portfolio(figi, user_id, account_id="", account_type=""):
160
with Client(get_token(user_id)) as client:
161
162
if account_id == "":
163
account_id = get_account(user_id=user_id)
164
165
if account_type == "":
166
account_type = get_account_type(user_id=user_id)
167
168
if account_type == "sandbox":
169
portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)
170
else:
171
portfolio = client.operations.get_portfolio(account_id=account_id)
172
173
for i in portfolio.positions:
174
if i.figi == figi:
175
lots = int(quotation_to_float(i.quantity_lots))
176
return int(lots)
177
178
return 0
179
180
181
'''
182
Функция для получения информации о цене бумаги в портфеле
183
'''
184
185
186
def get_price_in_portfolio(figi, user_id, account_id="", account_type=""):
187
with Client(get_token(user_id)) as client:
188
189
if account_id == "":
190
account_id = get_account(user_id=user_id)
191
192
if account_type == "":
193
account_type = get_account_type(user_id=user_id)
194
195
if account_type == "sandbox":
196
portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)
197
else:
198
portfolio = client.operations.get_portfolio(account_id=account_id)
199
200
for i in portfolio.positions:
201
if i.figi == figi:
202
price = quotation_to_float(i.current_price)
203
if price == 0.0:
204
price = quotation_to_float(i.average_position_price)
205
return price
206
207
return 0.0
208
209
210
'''
211
Функция для получения списка открытых ордеров
212
'''
213
214
215
def get_my_order(user_id, account_id="", account_type=""):
216
with Client(get_token(user_id)) as client:
217
218
if account_id == "":
219
account_id = get_account(user_id=user_id)
220
221
if account_type == "":
222
account_type = get_account_type(user_id=user_id)
223
224
if account_type == "sandbox":
225
orders = client.sandbox.get_sandbox_orders(account_id=account_id).orders
226
else:
227
orders = client.orders.get_orders(account_id=account_id).orders
228
229
order_df = pd.DataFrame(
230
{
231
"order_id": i.order_id,
232
"lots_req": i.lots_requested,
233
"lots_ex": i.lots_executed,
234
"sum_req": quotation_to_float(i.initial_order_price),
235
"sum_ex": quotation_to_float(i.executed_order_price),
236
"sum_total": quotation_to_float(i.total_order_amount), # сумма после всех комиссий
237
"commission": quotation_to_float(i.initial_commission),
238
"serv_commission": quotation_to_float(i.service_commission),
239
"currency": i.currency,
240
"currency_sign": get_currency_sing(i.currency),
241
"figi": i.figi,
242
"direction": i.direction,
243
"price_one": quotation_to_float(i.initial_security_price),
244
"order_date": i.order_date,
245
} for i in orders
246
)
247
248
return order_df
249
250
251
'''
252
Функция для получения списка всех операций пользователя
253
'''
254
255
256
def get_my_operations(user_id, account_id="", figi=""):
257
connection = sl.connect("db/BotDB.db")
258
cursor = connection.cursor()
259
260
if account_id == "":
261
account_id = get_account(user_id=user_id)
262
263
if figi == "":
264
operations = cursor.execute(
265
'SELECT id, user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, name, ticker, '
266
'quantity_lots, in_lot, quantity_total, price_position, price_total, commission, currency, message, '
267
'via FROM operations WHERE user_id = ? AND account_id = ?',
268
(user_id, account_id)).fetchall()
269
else:
270
operations = cursor.execute(
271
'SELECT id, user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, name, ticker, '
272
'quantity_lots, in_lot, quantity_total, price_position, price_total, commission, currency, message, '
273
'via FROM operations WHERE user_id = ? AND account_id = ? AND figi = ?',
274
(user_id, account_id, figi)).fetchall()
275
276
if not operations:
277
return False
278
279
operations_df = pd.DataFrame(
280
{
281
"id": line[0],
282
"user_id": user_id,
283
"account_id": account_id,
284
"account_type": line[3],
285
"order_id": line[4],
286
"date": line[5],
287
"time": line[6],
288
"direction": line[7],
289
"figi": line[8],
290
"name": line[9],
291
"ticker": line[10],
292
"quantity_lots": line[11],
293
"in_lot": line[12],
294
"quantity_total": line[13],
295
"price_position": line[14],
296
"price_total": line[15],
297
"commission": line[16],
298
"currency": line[17],
299
"message": line[18],
300
"via": line[19]
301
} for line in operations
302
)
303
304
style_df = operations_df.drop(['id', 'user_id', 'order_id', 'figi', 'ticker'], axis=1)
305
# style_df = style_df.style.apply(color_macd)
306
307
dfi.export(style_df, f"img/operations/all_operations_{user_id}.png")
308
309
return True
310
311