Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffInvestBot-main/functions.py
5925 views
1
import tinkoff.invest as ti
2
import pandas as pd
3
from datetime import datetime, timedelta
4
from ta.momentum import stoch, stoch_signal
5
6
7
CONTRACT_PREFIX = 'tinkoff.public.invest.api.contract.v1.'
8
INSTRUMENT_TICKER = 'GAZP'
9
WINDOW = 14
10
SMOOTH_WINDOW = 3
11
12
13
# Преобразование цены (https://azzrael.ru/api-v2-tinkoff-invest-get-candles-python)
14
def convert_price(p):
15
return p.units + p.nano / 1e9
16
17
18
# Сохранение свеч в датафрейм (https://azzrael.ru/api-v2-tinkoff-invest-get-candles-python)
19
def create_df(candles: [ti.HistoricCandle]):
20
df = pd.DataFrame([{
21
'time': c.time,
22
'volume': c.volume,
23
'open': convert_price(c.open),
24
'close': convert_price(c.close),
25
'high': convert_price(c.high),
26
'low': convert_price(c.low),
27
} for c in candles])
28
return df
29
30
31
def create_df_from_stream(c):
32
df = pd.DataFrame({
33
'time': [c.time],
34
'volume': [c.volume],
35
'open': [convert_price(c.open)],
36
'close': [convert_price(c.close)],
37
'high': [convert_price(c.high)],
38
'low': [convert_price(c.low)]
39
})
40
return df
41
42
43
# Получение FIGI для акций на Мосбирже
44
def get_shares_figi(cl, sharesticker):
45
result = cl.instruments.share_by(id_type=ti.InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER, class_code='TQBR',
46
id=sharesticker)
47
return result.instrument.figi
48
49
50
def get_shares_lot_size(cl, sharesticker):
51
result = cl.instruments.share_by(id_type=ti.InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER, class_code='TQBR',
52
id=sharesticker)
53
return result.instrument.lot
54
55
56
def recalculate_time_series(df1, df2):
57
del df1['%K']
58
del df1['%D']
59
result = pd.concat([df1, df2])
60
result.sort_values(by='time', inplace=True)
61
result = result.reset_index(drop=True)
62
result['%K'] = stoch(result['high'], result['low'], result['close'], window=WINDOW, smooth_window=SMOOTH_WINDOW,
63
fillna=True)
64
result['%D'] = stoch_signal(result['high'], result['low'], result['close'], window=WINDOW,
65
smooth_window=SMOOTH_WINDOW, fillna=True)
66
# print(result.tail())
67
return result
68
69
70
def get_sandbox_account_id(cl):
71
accounts = cl.sandbox.get_sandbox_accounts()
72
if len(accounts.accounts) > 0:
73
result = accounts.accounts[0].id
74
print(cl.sandbox.get_sandbox_positions(account_id=result))
75
# cl.sandbox.close_sandbox_account(account_id=result)
76
else:
77
acc = cl.sandbox.open_sandbox_account()
78
result = acc.account_id
79
cl.sandbox.sandbox_pay_in(account_id=result, amount=ti.MoneyValue(currency='rub', units=10000, nano=0))
80
print(cl.sandbox.get_sandbox_positions(account_id=result))
81
return result
82
83
84
def get_time_series(cl, figi):
85
starttime = datetime.now() - timedelta(days=1)
86
finishtime = datetime.now()
87
result = pd.DataFrame(data=None, columns=['time', 'volume', 'open', 'close', 'high', 'low'])
88
while result.shape[0] < 1000:
89
historiccandles = cl.market_data.get_candles(figi=figi, from_=starttime, to=finishtime,
90
interval=ti.CandleInterval.CANDLE_INTERVAL_5_MIN)
91
tempdf = create_df(historiccandles.candles)
92
result = pd.concat([result, tempdf])
93
starttime = starttime - timedelta(days=1)
94
finishtime = finishtime - timedelta(days=1)
95
result.sort_values(by='time', inplace=True)
96
result = result.reset_index(drop=True)
97
result['%K'] = stoch(result['high'], result['low'], result['close'], window=WINDOW, smooth_window=SMOOTH_WINDOW,
98
fillna=True)
99
result['%D'] = stoch_signal(result['high'], result['low'], result['close'], window=WINDOW,
100
smooth_window=SMOOTH_WINDOW, fillna=True)
101
return result
102
103
104
def get_account_id(cl):
105
result = 0
106
accounts = cl.users.get_accounts()
107
if len(accounts.accounts) > 0:
108
for account in accounts.accounts:
109
if account.access_level == ti.AccessLevel.ACCOUNT_ACCESS_LEVEL_FULL_ACCESS:
110
response = cl.operations.get_positions(account_id=account.id)
111
if response.money[0].units > 0:
112
result = account.id
113
if result == 0:
114
print('Нет аккаунтов с полным доступом или ненулевым балансом')
115
return result
116
117