Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffBot-main/lib/func.py
5929 views
1
from datetime import datetime, timedelta
2
3
from tinkoff.invest import CandleInterval, Quotation, AccessLevel, AccountStatus, AccountType
4
5
6
def Qt(obj: Quotation) -> float:
7
return obj.units + obj.nano / 1e9
8
9
10
def TradeSession(client, exchange):
11
'''
12
Проверяем можно ли сейчас торговать или сессия закрыта
13
торговлю начинаем через 5 минут после открытия торгов
14
и заканчиваем за 15 минут до окончания
15
'''
16
tms = client.instruments.trading_schedules(from_=datetime.utcnow(), to=datetime.utcnow())
17
for i in tms.exchanges:
18
if i.exchange == exchange:
19
if i.days[0].is_trading_day:
20
if i.days[0].start_time.timestamp() > datetime.utcnow().timestamp():
21
start_time = i.days[0].start_time + timedelta(minutes=5)
22
end_time = i.days[0].end_time - timedelta(minutes=15)
23
return True, start_time, end_time
24
return False,
25
26
27
def GetHistoryData(client, figi, from_data, to_date, interval):
28
'''
29
получаем историю по выбранному интсрументу
30
'''
31
candles = client.market_data.get_candles(figi=figi, from_=from_data, to=to_date, interval=interval)
32
33
data = []
34
for i in candles.candles:
35
data.append((Qt(i.open), Qt(i.high), Qt(i.low), Qt(i.close), i.volume, str(i.time), i.is_complete))
36
37
return data
38
39
40
def SynchronizationTwoArray(smb_1, smb_2):
41
smb_1_index = 0
42
smb_2_index = 0
43
len_common = min(len(smb_1), len(smb_2))
44
45
out_1 = []
46
out_2 = []
47
48
while True:
49
# ('open', 'high', 'low', 'close', 'volume', 'time', 'bar complete')
50
dt1 = smb_1[smb_1_index][5]
51
dt2 = smb_2[smb_2_index][5]
52
53
if dt1 > dt2:
54
smb_2_index += 1
55
continue
56
57
if dt1 < dt2:
58
smb_1_index += 1
59
continue
60
61
out_1.append(smb_1[smb_1_index])
62
out_2.append(smb_2[smb_2_index])
63
64
smb_1_index += 1
65
smb_2_index += 1
66
67
if smb_1_index >= len_common or smb_2_index >= len_common:
68
break
69
70
return out_1, out_2
71
72
73
def AbsoluteToRelative(smb, start_price):
74
'''
75
оставляем только отношение к цене открытия. Остальные данные отбрасываем
76
цена открытия плавающая, чтобы была возможность её менять при закрытии сделки внутри дня
77
'''
78
data = list(map(lambda i: float(i[3] / start_price - 1) * 100, smb))
79
data.insert(0, 0)
80
return data
81
82
83
def CalcMinDelta():
84
'''
85
Рассчитываем минимально необходимое расхождение между активами необхадимое для входа
86
другими словами складываем все комиссионные издержки и переводимв относительную шкалу
87
'''
88
return abs(0.2)
89
90
91
def FigiToTicker(figi) -> str:
92
'''
93
получаем тикер по фиги
94
'''
95
return ''
96
97
98
def FindTwoInstruments():
99
'''
100
Функция поиска необходимой пары инструментов
101
Можно использовать коинтеграцию.
102
Если инструменты схожи или из одного сектора экономики то можно использовать корреляцию
103
Также можно использовать один инструмент но с разных бирж или секиий одной биржи
104
к акция + её адр
105
или спот+фьюч
106
'''
107
SRM2 = 'FUTSBRF06220'
108
VBM2 = 'FUTVTBR06220'
109
return SRM2, VBM2
110
111
112
def FindOpenDeals(client, account_id):
113
'''
114
Ищем открытые сделки
115
'''
116
acc = client.sandbox.get_sandbox_positions(account_id=account_id)
117
return acc.futures
118
119
120
def OpenDeal(client, account_id, figi, lots, direction, order_type, order_id, sandbox):
121
'''
122
Отправляем ордер.Пока работаем только с маркетами
123
'''
124
if sandbox:
125
r = client.sandbox.post_sandbox_order(figi=figi, quantity=lots, account_id=account_id, direction=direction,
126
order_type=order_type, order_id=order_id)
127
else:
128
r = client.orders.post_order(figi=figi, quantity=lots, account_id=account_id, direction=direction,
129
order_type=order_type, order_id=order_id)
130
return r
131
132
133
def CloseAccountSandbox(client, account_id):
134
try:
135
client.sandbox.close_sandbox_account(account_id=account_id)
136
except:
137
pass
138
139
140
def GetAccountSandbox(client):
141
# в песочнице берём первый акк
142
acc = client.sandbox.get_sandbox_accounts()
143
if acc.accounts == []:
144
acc = client.sandbox.open_sandbox_account()
145
return acc.account_id
146
return acc.accounts[0].id
147
148
149
def GetBalance(client, sandbox, account_id):
150
if sandbox:
151
acc = client.sandbox.get_sandbox_portfolio(account_id=account_id)
152
return acc.total_amount_currencies
153
154