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/place_order.py
5933 views
1
from tinkoff.invest import Client, OrderDirection, OrderType
2
from trading import trade_help
3
from config.personal_data import get_token, get_account, get_account_type
4
from trading.trade_help import quotation_to_float
5
import sqlite3 as sl
6
from datetime import datetime
7
from trading.get_securities import security_name_by_figi
8
from trading.trade_help import in_lot_figi
9
10
"""
11
12
Тут представлены все функции, которые отвечает за размещение ордеров на покупку/продаужу бумаг
13
14
"""
15
16
'''
17
Функция для покупки ценных бумаг по заданной цене за бумагу
18
Если цена не задана (равна нулю), то бумаги покупаются по лучшей рыночной цене
19
'''
20
21
22
def buy_order(figi, price, quantity_lots, user_id, account_id="", account_type="", via="else"):
23
with Client(get_token(user_id)) as client:
24
25
if account_id == "":
26
account_id = get_account(user_id=user_id)
27
28
if account_type == "":
29
account_type = get_account_type(user_id=user_id)
30
31
if account_type == "sandbox":
32
if price > 0.0:
33
order = client.sandbox.post_sandbox_order(
34
order_id=str(datetime.utcnow().timestamp()),
35
figi=figi,
36
price=trade_help.to_quotation(price),
37
quantity=quantity_lots,
38
account_id=account_id,
39
direction=OrderDirection.ORDER_DIRECTION_BUY,
40
order_type=OrderType.ORDER_TYPE_LIMIT,
41
)
42
else:
43
order = client.sandbox.post_sandbox_order(
44
order_id=str(datetime.utcnow().timestamp()),
45
figi=figi,
46
quantity=quantity_lots,
47
account_id=account_id,
48
direction=OrderDirection.ORDER_DIRECTION_BUY,
49
order_type=OrderType.ORDER_TYPE_MARKET,
50
)
51
else:
52
if price > 0.0:
53
order = client.orders.post_order(
54
order_id=str(datetime.utcnow().timestamp()),
55
figi=figi,
56
price=trade_help.to_quotation(price),
57
quantity=quantity_lots,
58
account_id=account_id,
59
direction=OrderDirection.ORDER_DIRECTION_BUY,
60
order_type=OrderType.ORDER_TYPE_LIMIT,
61
)
62
else:
63
order = client.orders.post_order(
64
order_id=str(datetime.utcnow().timestamp()),
65
figi=figi,
66
quantity=quantity_lots,
67
account_id=account_id,
68
direction=OrderDirection.ORDER_DIRECTION_BUY,
69
order_type=OrderType.ORDER_TYPE_MARKET,
70
)
71
write_operation(order=order, user_id=user_id, via=via, account_id=account_id, account_type=account_type)
72
73
return order
74
75
76
'''
77
Функция для продажи ценных бумаг по заданной цене за бумагу
78
Если цена не задана (равна нулю), то бумаги продаются по лучшей рыночной цене
79
'''
80
81
82
def sell_sfb(figi, price, quantity_lots, user_id, account_id="", account_type="", via="else"):
83
with Client(get_token(user_id)) as client:
84
85
if account_id == "":
86
account_id = get_account(user_id=user_id)
87
88
if account_type == "":
89
account_type = get_account_type(user_id=user_id)
90
91
if account_type == "sandbox":
92
if price > 0.0:
93
try:
94
order = client.sandbox.post_sandbox_order(
95
order_id=str(datetime.utcnow().timestamp()),
96
figi=figi,
97
quantity=quantity_lots,
98
price=trade_help.to_quotation(price),
99
account_id=account_id,
100
direction=OrderDirection.ORDER_DIRECTION_SELL,
101
order_type=OrderType.ORDER_TYPE_LIMIT,
102
)
103
except:
104
return False
105
else:
106
try:
107
order = client.sandbox.post_sandbox_order(
108
order_id=str(datetime.utcnow().timestamp()),
109
figi=figi,
110
quantity=quantity_lots,
111
account_id=account_id,
112
direction=OrderDirection.ORDER_DIRECTION_SELL,
113
order_type=OrderType.ORDER_TYPE_MARKET,
114
)
115
except:
116
return False
117
else:
118
if price > 0.0:
119
try:
120
order = client.orders.post_order(
121
order_id=str(datetime.utcnow().timestamp()),
122
figi=figi,
123
quantity=quantity_lots,
124
price=trade_help.to_quotation(price),
125
account_id=account_id,
126
direction=OrderDirection.ORDER_DIRECTION_SELL,
127
order_type=OrderType.ORDER_TYPE_LIMIT,
128
)
129
except:
130
return False
131
else:
132
try:
133
order = client.orders.post_order(
134
order_id=str(datetime.utcnow().timestamp()),
135
figi=figi,
136
quantity=quantity_lots,
137
account_id=account_id,
138
direction=OrderDirection.ORDER_DIRECTION_SELL,
139
order_type=OrderType.ORDER_TYPE_MARKET,
140
)
141
except:
142
return False
143
144
write_operation(order=order, user_id=user_id, via=via, account_id=account_id, account_type=account_type)
145
146
return order
147
148
149
'''
150
Функция для отмены ордера по его id
151
'''
152
153
154
async def cancel_order(order_id, user_id, account_id="", account_type=""):
155
with Client(get_token(user_id)) as client:
156
157
if account_id == "":
158
account_id = get_account(user_id=user_id)
159
160
if account_type == "":
161
account_type = get_account_type(user_id=user_id)
162
163
if account_type == "sandbox":
164
state = client.sandbox.get_sandbox_order_state(
165
order_id=order_id,
166
account_id=account_id,
167
)
168
169
order = client.sandbox.cancel_sandbox_order(
170
order_id=order_id,
171
account_id=account_id,
172
)
173
else:
174
state = client.orders.get_order_state(
175
order_id=order_id,
176
account_id=account_id,
177
)
178
179
order = client.orders.cancel_order(
180
order_id=order_id,
181
account_id=account_id,
182
)
183
184
connection = sl.connect("db/BotDB.db")
185
cursor = connection.cursor()
186
187
direction = cursor.execute('SELECT direction FROM operations WHERE order_id=?', (order_id,)).fetchone()[0]
188
if direction is not None:
189
quantity_lots = state.lots_executed
190
price = quotation_to_float(state.executed_order_price)
191
commission = quotation_to_float(state.executed_commission)
192
direction += "/canceled"
193
quantity_total = quantity_lots * in_lot_figi(state.figi, user_id=user_id)
194
price_total = quantity_total * price
195
196
new_operation = (quantity_lots, quantity_total, price_total, commission, direction, order_id)
197
198
cursor.execute(
199
'UPDATE OPERATIONS SET quantity_lots = ?, quantity_total = ?, price_total = ?, commission = ?, direction '
200
'= ? WHERE order_id '
201
'= ?;',
202
new_operation)
203
connection.commit()
204
205
return order
206
207
208
def write_operation(order, user_id, account_id, account_type, via="else"):
209
connection = sl.connect("db/BotDB.db")
210
cursor = connection.cursor()
211
212
order_id = order.order_id
213
214
date_op = datetime.now().strftime("%d.%m.%Y")
215
time_op = datetime.now().strftime("%H:%M:%S")
216
217
if order.direction == 2:
218
direction = "sell"
219
elif order.direction == 1:
220
direction = "buy"
221
else:
222
direction = "else"
223
224
figi = order.figi
225
ticker = order.figi # Доделать потом
226
name = security_name_by_figi(figi=figi, user_id=user_id)
227
228
quantity_lots = order.lots_requested
229
in_lot = in_lot_figi(figi=figi, user_id=user_id)
230
quantity_total = quantity_lots * in_lot_figi(figi=figi, user_id=user_id)
231
232
price_position = quotation_to_float(order.initial_order_price)
233
commission = quotation_to_float(order.initial_commission)
234
price_total = price_position * quantity_total - commission
235
236
currency = order.initial_order_price.currency
237
238
message = order.message
239
240
operation = (
241
user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, ticker, name, quantity_lots,
242
in_lot,
243
quantity_total, price_position, price_total,
244
commission, currency, message, via)
245
cursor.execute("INSERT INTO OPERATIONS (user_id, account_id, account_type, order_id, date_op, time_op, direction, "
246
"figi, ticker, name, "
247
"quantity_lots, in_lot, quantity_total, price_position, price_total, commission,currency, message, "
248
"via) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?);",
249
operation)
250
connection.commit()
251
252