sysstra 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- src/__init__.py +6 -0
- src/custom_indicators.py +903 -0
- src/data/__init__.py +2 -0
- src/data/historical.py +85 -0
- src/data/live.py +77 -0
- src/orders/__init__.py +0 -0
- src/orders/kite.py +36 -0
- src/orders/orders.py +489 -0
- src/utils.py +1465 -0
- sysstra-0.1.0.dist-info/LICENSE +21 -0
- sysstra-0.1.0.dist-info/METADATA +37 -0
- sysstra-0.1.0.dist-info/RECORD +14 -0
- sysstra-0.1.0.dist-info/WHEEL +5 -0
- sysstra-0.1.0.dist-info/top_level.txt +1 -0
src/orders/orders.py
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
def add_order_to_redis(request_id, order_dict, mode):
|
|
2
|
+
"""Function to add order to redis"""
|
|
3
|
+
try:
|
|
4
|
+
logger.info(msg="Adding Order to Redis DB for : {}".format(request_id))
|
|
5
|
+
rdb_cursor.rpush(str(request_id) + "_orders", json.dumps(order_dict, default=str))
|
|
6
|
+
rdb_cursor.publish(str(request_id) + "_orders", json.dumps(order_dict, default=str))
|
|
7
|
+
rdb_cursor.publish(str(order_dict["user_id"]) + "_{}".format(mode) + "_orders", json.dumps(order_dict, default=str))
|
|
8
|
+
logger.info(msg="order added in redis")
|
|
9
|
+
except Exception as e:
|
|
10
|
+
logger.exception(msg="Exception in adding order in redis : {}".format(e))
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def fetch_orders_list(request_id):
|
|
15
|
+
""" Function to fetch an orders list for request_id """
|
|
16
|
+
try:
|
|
17
|
+
logger.info(msg="Fetching Orders List for : {}".format(request_id))
|
|
18
|
+
orders_list_json = rdb_cursor.lrange(str(request_id)+"_orders", 0, -1)
|
|
19
|
+
orders_list = [json.loads(i) for i in orders_list_json]
|
|
20
|
+
# logger.info(msg="Orders List : {}".format(orders_list))
|
|
21
|
+
return orders_list
|
|
22
|
+
except Exception as e:
|
|
23
|
+
logger.exception(msg="Exception in fetching orders list : {}".format(e))
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fetch_last_order(request_id):
|
|
28
|
+
"""Function to fetch last order from redis database"""
|
|
29
|
+
try:
|
|
30
|
+
logger.info(msg="Fetching Last Order from Redis")
|
|
31
|
+
last_order = json.loads(rdb_cursor.lindex(str(request_id) + "_orders", -1))
|
|
32
|
+
logger.info("last_order in redis : {}".format(last_order))
|
|
33
|
+
return last_order
|
|
34
|
+
except Exception as e:
|
|
35
|
+
logger.exception(msg="Exception in fetching last order : {}".format(e))
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def save_bt_report(report_dict):
|
|
40
|
+
"""Function to Save Backtest Report in Database"""
|
|
41
|
+
try:
|
|
42
|
+
logger.info(msg="saving backtest report in DB")
|
|
43
|
+
app_db_cursor[bt_reports_col].insert_one(report_dict)
|
|
44
|
+
logger.info(msg="updating request status")
|
|
45
|
+
app_db_cursor[bt_request_col].update_one({"_id": report_dict["request_id"]},
|
|
46
|
+
{"$set": {"status": "done"}})
|
|
47
|
+
except Exception as e:
|
|
48
|
+
logger.exception("Exception in saving BT Report : {}".format(e))
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def place_bt_order(order_candle, option_type, strike_price, position_type, quantity, transaction_type, order_type, exit_type=None, quantity_left=0, params=None, market_type="cash", trade_type=None, trigger_price=None, lot_size=25, user_id=None, strategy_id=None, request_id=None, exchange="NSE"):
|
|
53
|
+
""" Function to place Backtesting Order """
|
|
54
|
+
try:
|
|
55
|
+
logger.info(msg="* placing backtesting order")
|
|
56
|
+
order_dict = {"exchange": exchange, "user_id": str(user_id), "strategy_id": str(strategy_id),
|
|
57
|
+
"request_id": str(request_id), "order_type": order_type, "position_type": position_type, "quantity": quantity,
|
|
58
|
+
"transaction_type": transaction_type, "option_type": option_type, "strike_price": strike_price,
|
|
59
|
+
"exit_type": exit_type, "quantity_left": quantity_left, "lot_size": lot_size,
|
|
60
|
+
"trade_type": trade_type}
|
|
61
|
+
if trigger_price:
|
|
62
|
+
order_dict["trigger_price"] = trigger_price
|
|
63
|
+
else:
|
|
64
|
+
order_dict["trigger_price"] = order_candle["close"]
|
|
65
|
+
|
|
66
|
+
order_dict["order_timestamp"] = str(order_candle["timestamp"])
|
|
67
|
+
order_dict["tradingsymbol"] = order_candle["symbol"]
|
|
68
|
+
order_dict["date"] = str(order_candle["date"])
|
|
69
|
+
if market_type == "cash":
|
|
70
|
+
order_dict["expiry"] = ""
|
|
71
|
+
else:
|
|
72
|
+
order_dict["expiry"] = order_candle["expiry"]
|
|
73
|
+
|
|
74
|
+
order_dict["day"] = order_candle["date"].strftime("%A")
|
|
75
|
+
if params:
|
|
76
|
+
order_dict.update(params)
|
|
77
|
+
logger.info(msg="* bt_order : {}".format(order_dict))
|
|
78
|
+
# orders_list.append(order_dict)
|
|
79
|
+
|
|
80
|
+
add_order_to_redis(request_id=str(request_id), order_dict=order_dict, mode="bt")
|
|
81
|
+
orders_list = fetch_orders_list(request_id=str(request_id))
|
|
82
|
+
|
|
83
|
+
return orders_list
|
|
84
|
+
|
|
85
|
+
except Exception as e:
|
|
86
|
+
logger.exception(msg="Exception in placing backtesting order : {}".format(e))
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def place_vt_order(order_candle, option_type, strike_price, position_type, quantity, transaction_type,
|
|
91
|
+
order_type, exit_type=None, quantity_left=0, params=None, market_type="options", trade_type=None,
|
|
92
|
+
trigger_price=None, lot_size=15, user_id=None, strategy_id=None, request_id=None, exchange="NSE"):
|
|
93
|
+
"""Function to Place Virtual Trading Order"""
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
logger.info(msg="* placing virtual trade order")
|
|
97
|
+
order_dict = {"exchange": exchange,
|
|
98
|
+
"user_id": user_id,
|
|
99
|
+
"strategy_id": strategy_id,
|
|
100
|
+
"request_id": request_id,
|
|
101
|
+
"option_type": option_type,
|
|
102
|
+
"strike_price": strike_price,
|
|
103
|
+
"quantity": quantity,
|
|
104
|
+
"position_type": position_type,
|
|
105
|
+
"transaction_type": transaction_type,
|
|
106
|
+
"trade_type": trade_type,
|
|
107
|
+
"trade_action": trade_type,
|
|
108
|
+
"order_type": order_type,
|
|
109
|
+
"exit_type": exit_type,
|
|
110
|
+
"quantity_left": quantity_left,
|
|
111
|
+
"lot_size": lot_size
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if trigger_price:
|
|
115
|
+
order_dict["trigger_price"] = trigger_price
|
|
116
|
+
else:
|
|
117
|
+
order_dict["trigger_price"] = order_candle["close"]
|
|
118
|
+
order_dict["order_timestamp"] = datetime.datetime.now().replace(microsecond=0)
|
|
119
|
+
order_dict["tradingsymbol"] = order_candle["symbol"]
|
|
120
|
+
order_dict["date"] = order_candle["date"]
|
|
121
|
+
if market_type == "cash":
|
|
122
|
+
order_dict["expiry"] = ""
|
|
123
|
+
else:
|
|
124
|
+
order_dict["expiry"] = order_candle["expiry"]
|
|
125
|
+
|
|
126
|
+
order_dict["day"] = order_candle["timestamp"].strftime("%A")
|
|
127
|
+
if params:
|
|
128
|
+
order_dict.update(params)
|
|
129
|
+
|
|
130
|
+
logger.info(msg="* vt_order : {}".format(order_dict))
|
|
131
|
+
|
|
132
|
+
# Saving Order Details to Database
|
|
133
|
+
save_vt_order(order_dict=order_dict.copy())
|
|
134
|
+
|
|
135
|
+
# orders_list.append(order_dict)
|
|
136
|
+
|
|
137
|
+
order_dict["user_id"] = str(order_dict["user_id"])
|
|
138
|
+
order_dict["strategy_id"] = str(order_dict["strategy_id"])
|
|
139
|
+
order_dict["request_id"] = str(order_dict["request_id"])
|
|
140
|
+
order_dict["order_timestamp"] = str(order_dict["order_timestamp"])
|
|
141
|
+
order_dict["date"] = str(order_dict["date"])
|
|
142
|
+
order_dict["expiry"] = str(order_dict["expiry"])
|
|
143
|
+
|
|
144
|
+
add_order_to_redis(str(request_id), order_dict, mode="vt")
|
|
145
|
+
orders_list = fetch_orders_list(str(request_id))
|
|
146
|
+
|
|
147
|
+
# Creating Alert Dict
|
|
148
|
+
alert_dict = {"user_id": str(order_dict["user_id"]),
|
|
149
|
+
"strategy_id": str(order_dict["strategy_id"]),
|
|
150
|
+
"request_id": str(order_dict["request_id"]),
|
|
151
|
+
"mode": "vt",
|
|
152
|
+
"exit_type": exit_type,
|
|
153
|
+
"symbol": order_candle["symbol"],
|
|
154
|
+
"quantity": quantity,
|
|
155
|
+
"price": order_dict["trigger_price"],
|
|
156
|
+
"quantity_left": quantity_left,
|
|
157
|
+
"trade_type": trade_type,
|
|
158
|
+
"template_id": 0
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
# Sending Alert
|
|
162
|
+
send_order_alert(alert_dict)
|
|
163
|
+
|
|
164
|
+
return orders_list
|
|
165
|
+
except Exception as e:
|
|
166
|
+
logger.exception(msg="Exception in placing virtual trade : {}".format(e))
|
|
167
|
+
pass
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def save_vt_order(order_dict):
|
|
171
|
+
"""Function to save order in Database"""
|
|
172
|
+
try:
|
|
173
|
+
logger.info(msg="* saving VT order to DB *****")
|
|
174
|
+
|
|
175
|
+
app_db_cursor[vt_orders_col].insert_one(order_dict)
|
|
176
|
+
except Exception as e:
|
|
177
|
+
logger.exception(msg="Exception in saving VT order in DB : {}".format(e))
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def save_vt_trade(trade_dict):
|
|
182
|
+
"""Function to save order in Database"""
|
|
183
|
+
try:
|
|
184
|
+
logger.info(msg="* saving VT trade to DB *****")
|
|
185
|
+
app_db_cursor[vt_trades_col].insert_one(trade_dict)
|
|
186
|
+
except Exception as e:
|
|
187
|
+
logger.exception(msg="Exception in saving VT trade in DB : {}".format(e))
|
|
188
|
+
pass
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def place_lt_order(tradingsymbol, quantity, transaction_type, order_type, lot_size=15, exchange="NSE",
|
|
192
|
+
credential_id=None, trigger_price=None, order_price=None):
|
|
193
|
+
""" Function to Place Live Trading Order """
|
|
194
|
+
try:
|
|
195
|
+
logger.info(msg="* Placing live trade order")
|
|
196
|
+
|
|
197
|
+
if order_type == "MARKET":
|
|
198
|
+
order_data_params = {"tradingsymbol": tradingsymbol,
|
|
199
|
+
"exchange": exchange,
|
|
200
|
+
"transaction_type": transaction_type,
|
|
201
|
+
"quantity": quantity * lot_size,
|
|
202
|
+
"order_type": order_type,
|
|
203
|
+
"product": "MIS",
|
|
204
|
+
"validity": "DAY"}
|
|
205
|
+
|
|
206
|
+
order_response = place_live_order(credential_id=credential_id, order_details=order_data_params)
|
|
207
|
+
logger.info(msg="order_response : {}".format(order_response))
|
|
208
|
+
|
|
209
|
+
if order_response["status"] == "COMPLETE":
|
|
210
|
+
# return "success", order_response["broker_response"][0]["broker_response"]
|
|
211
|
+
return "success", order_response
|
|
212
|
+
else:
|
|
213
|
+
return "failed", None
|
|
214
|
+
|
|
215
|
+
elif order_type == "SL":
|
|
216
|
+
logger.info(msg="*** Placing SL Limit Order ***")
|
|
217
|
+
order_data_params = {"tradingsymbol": tradingsymbol, "exchange": exchange,
|
|
218
|
+
"transaction_type": transaction_type,
|
|
219
|
+
"quantity": quantity * lot_size, "product": "MIS", "validity": "DAY",
|
|
220
|
+
"order_type": "SL", "trigger_price": trigger_price, "price": order_price}
|
|
221
|
+
logger.info(f"order_data_params : {order_data_params}")
|
|
222
|
+
order_response = place_live_order(credential_id=credential_id, order_details=order_data_params)
|
|
223
|
+
logger.info(msg="sl_order_response : {}".format(order_response))
|
|
224
|
+
|
|
225
|
+
if order_response["status"] == "success":
|
|
226
|
+
# return "success", order_response["data"]["order_id"]
|
|
227
|
+
# return "success", order_response["order_id"][0]
|
|
228
|
+
return "success", order_response["order_id"]
|
|
229
|
+
else:
|
|
230
|
+
return "failed", None
|
|
231
|
+
|
|
232
|
+
elif order_type == "LIMIT":
|
|
233
|
+
logger.info(msg="*** Placing Limit BUY Order ***")
|
|
234
|
+
order_data_params = {"tradingsymbol": tradingsymbol, "exchange": exchange,
|
|
235
|
+
"transaction_type": transaction_type, "quantity": quantity * lot_size,
|
|
236
|
+
"product": "MIS", "validity": "TTL", "validity_ttl": 1,
|
|
237
|
+
"order_type": "LIMIT", "price": order_price}
|
|
238
|
+
|
|
239
|
+
order_response = place_live_order(credential_id=credential_id, order_details=order_data_params)
|
|
240
|
+
logger.info(msg="sl_order_response : {}".format(order_response))
|
|
241
|
+
|
|
242
|
+
if order_response["status"] == "success":
|
|
243
|
+
# return "success", order_response["data"]["order_id"]
|
|
244
|
+
# return "success", order_response["order_id"][0]
|
|
245
|
+
return "success", order_response["order_id"]
|
|
246
|
+
else:
|
|
247
|
+
return "failed", None
|
|
248
|
+
|
|
249
|
+
except Exception as e:
|
|
250
|
+
logger.exception(msg="Exception in placing live trade : {}".format(e))
|
|
251
|
+
return "failed", None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def save_lt_order(tradingsymbol, option_type, strike_price, position_type, quantity, transaction_type, order_type,
|
|
255
|
+
orders_list, exit_type=None, quantity_left=0, params=None, market_type="cash", trade_type=None,
|
|
256
|
+
expiry=None, trigger_price=None, lot_size=25, user_id=None, strategy_id=None, request_id=None,
|
|
257
|
+
exchange="NSE", exchange_timestamp=None, order_id=None, broker_response=None, sl_order_id=None):
|
|
258
|
+
|
|
259
|
+
"""Function to save order in Database"""
|
|
260
|
+
try:
|
|
261
|
+
logger.info(msg="* Saving LT order to DB")
|
|
262
|
+
order_dict = {"exchange": exchange, "user_id": user_id, "strategy_id": strategy_id,
|
|
263
|
+
"request_id": request_id, "tradingsymbol": tradingsymbol, "transaction_type": transaction_type,
|
|
264
|
+
"quantity": quantity, "position_type": position_type, "order_type": order_type,
|
|
265
|
+
"exit_type": exit_type, "quantity_left": quantity_left, "lot_size": lot_size, "trade_type": trade_type,
|
|
266
|
+
"trade_action": trade_type,
|
|
267
|
+
"exchange_timestamp": exchange_timestamp, "status": "COMPLETE", "trigger_price": trigger_price, "order_id": order_id}
|
|
268
|
+
|
|
269
|
+
if sl_order_id:
|
|
270
|
+
order_dict["sl_order_id"] = sl_order_id
|
|
271
|
+
|
|
272
|
+
if market_type == "cash":
|
|
273
|
+
order_dict["expiry"] = ""
|
|
274
|
+
order_dict["option_type"] = ""
|
|
275
|
+
order_dict["strike_price"] = ""
|
|
276
|
+
else:
|
|
277
|
+
order_dict["expiry"] = expiry
|
|
278
|
+
order_dict["option_type"] = option_type
|
|
279
|
+
order_dict["strike_price"] = strike_price
|
|
280
|
+
|
|
281
|
+
order_dict["order_timestamp"] = exchange_timestamp
|
|
282
|
+
order_dict["date"] = datetime.datetime.strptime(str(datetime.datetime.today().date()), '%Y-%m-%d')
|
|
283
|
+
order_dict["day"] = order_dict["date"].strftime("%A")
|
|
284
|
+
|
|
285
|
+
if params:
|
|
286
|
+
order_dict.update(params)
|
|
287
|
+
logger.info(msg="* lt_order : {}".format(order_dict))
|
|
288
|
+
|
|
289
|
+
# Creating New Dict for saving data in to db
|
|
290
|
+
lt_order_dict = {}
|
|
291
|
+
for key in order_dict.keys():
|
|
292
|
+
lt_order_dict[key] = order_dict[key]
|
|
293
|
+
|
|
294
|
+
lt_order_dict["order_id"] = order_id
|
|
295
|
+
lt_order_dict["broker_response"] = broker_response
|
|
296
|
+
lt_order_dict["trade_action"] = lt_order_dict["trade_type"]
|
|
297
|
+
|
|
298
|
+
# Saving Order Details to Database
|
|
299
|
+
app_db_cursor[lt_orders_col].insert_one(lt_order_dict)
|
|
300
|
+
|
|
301
|
+
order_dict["strategy_id"] = str(order_dict["strategy_id"])
|
|
302
|
+
order_dict["request_id"] = str(order_dict["request_id"])
|
|
303
|
+
order_dict["user_id"] = str(order_dict["user_id"])
|
|
304
|
+
order_dict["order_timestamp"] = str(order_dict["order_timestamp"])
|
|
305
|
+
order_dict["exchange_timestamp"] = str(order_dict["exchange_timestamp"])
|
|
306
|
+
order_dict["expiry"] = str(order_dict["expiry"])
|
|
307
|
+
order_dict["date"] = str(order_dict["date"])
|
|
308
|
+
order_dict["order_id"] = order_id
|
|
309
|
+
|
|
310
|
+
add_order_to_redis(str(request_id), order_dict, mode="lt")
|
|
311
|
+
orders_list = fetch_orders_list(str(request_id))
|
|
312
|
+
logger.info(msg="Order List Now : {}".format(orders_list))
|
|
313
|
+
|
|
314
|
+
# Creating Alert Dict
|
|
315
|
+
alert_dict = {"user_id": str(order_dict["user_id"]),
|
|
316
|
+
"strategy_id": str(order_dict["strategy_id"]),
|
|
317
|
+
"request_id": str(order_dict["request_id"]),
|
|
318
|
+
"mode": "lt",
|
|
319
|
+
"exit_type": exit_type,
|
|
320
|
+
"symbol": tradingsymbol,
|
|
321
|
+
"quantity": quantity,
|
|
322
|
+
"price": trigger_price,
|
|
323
|
+
"quantity_left": quantity_left,
|
|
324
|
+
"trade_type": trade_type,
|
|
325
|
+
"template_id": 0
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
# Sending Alert
|
|
329
|
+
send_order_alert(alert_dict)
|
|
330
|
+
return "success", orders_list
|
|
331
|
+
|
|
332
|
+
except Exception as e:
|
|
333
|
+
logger.exception(msg="Exception in Saving Order in DB : {}".format(e))
|
|
334
|
+
return "failed", orders_list
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def save_lt_trade(trade_dict):
|
|
338
|
+
"""Function to save order in Database"""
|
|
339
|
+
try:
|
|
340
|
+
logger.info(msg="* saving LT trade to DB *****")
|
|
341
|
+
app_db_cursor[lt_trades_col].insert_one(trade_dict)
|
|
342
|
+
except Exception as e:
|
|
343
|
+
logger.exception(msg="Exception in saving LT trade in DB : {}".format(e))
|
|
344
|
+
pass
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def check_open_orders(orders_list):
|
|
348
|
+
""" Function to open orders available """
|
|
349
|
+
try:
|
|
350
|
+
if orders_list:
|
|
351
|
+
quantity_dict = {}
|
|
352
|
+
for order in orders_list:
|
|
353
|
+
trade_symbol = order["tradingsymbol"]
|
|
354
|
+
quantity_dict[trade_symbol] = {}
|
|
355
|
+
quantity_dict[trade_symbol]["buy_quantity"] = 0
|
|
356
|
+
quantity_dict[trade_symbol]["sell_quantity"] = 0
|
|
357
|
+
quantity_dict[trade_symbol]["quantity"] = 0
|
|
358
|
+
quantity_dict[trade_symbol]["option_type"] = ""
|
|
359
|
+
quantity_dict[trade_symbol]["strike_price"] = ""
|
|
360
|
+
quantity_dict[trade_symbol]["exit_levels"] = []
|
|
361
|
+
quantity_dict[trade_symbol]["order_timestamp"] = ""
|
|
362
|
+
quantity_dict[trade_symbol]["quantity_left"] = 0
|
|
363
|
+
quantity_dict[trade_symbol]["bnf_price"] = 0
|
|
364
|
+
quantity_dict[trade_symbol]["expiry"] = ""
|
|
365
|
+
quantity_dict[trade_symbol]["sl_order_id"] = ""
|
|
366
|
+
quantity_dict[trade_symbol]["option_order_price"] = 0
|
|
367
|
+
quantity_dict[trade_symbol]["hka_option_order_price"] = 0
|
|
368
|
+
quantity_dict[trade_symbol]["trailing_sl"] = 0
|
|
369
|
+
|
|
370
|
+
for order in orders_list:
|
|
371
|
+
trade_symbol = order["tradingsymbol"]
|
|
372
|
+
if order["trade_type"] == "ENTRY":
|
|
373
|
+
quantity_dict[trade_symbol]["buy_quantity"] = order["quantity"]
|
|
374
|
+
quantity_dict[trade_symbol]["quantity"] = order["quantity"]
|
|
375
|
+
quantity_dict[trade_symbol]["option_type"] = order["option_type"]
|
|
376
|
+
quantity_dict[trade_symbol]["strike_price"] = order["strike_price"]
|
|
377
|
+
quantity_dict[trade_symbol]["trigger_price"] = order["trigger_price"]
|
|
378
|
+
quantity_dict[trade_symbol]["order_timestamp"] = datetime.datetime.strptime(str(order["order_timestamp"]), '%Y-%m-%d %H:%M:%S')
|
|
379
|
+
quantity_dict[trade_symbol]["quantity_left"] = order["quantity_left"]
|
|
380
|
+
quantity_dict[trade_symbol]["bnf_price"] = order["bnf_price"]
|
|
381
|
+
quantity_dict[trade_symbol]["hka_option_order_price"] = order["hka_option_order_price"]
|
|
382
|
+
quantity_dict[trade_symbol]["option_order_price"] = order["option_order_price"]
|
|
383
|
+
|
|
384
|
+
if "expiry" in order:
|
|
385
|
+
quantity_dict[trade_symbol]["expiry"] = order["expiry"]
|
|
386
|
+
|
|
387
|
+
if "sl_order_id" in order:
|
|
388
|
+
quantity_dict[trade_symbol]["sl_order_id"] = order["sl_order_id"]
|
|
389
|
+
|
|
390
|
+
if "trailing_sl" in order:
|
|
391
|
+
quantity_dict[trade_symbol]["trailing_sl"] = order["trailing_sl"]
|
|
392
|
+
|
|
393
|
+
elif order["trade_type"] == "EXIT":
|
|
394
|
+
quantity_dict[trade_symbol]["sell_quantity"] += order["quantity"]
|
|
395
|
+
quantity_dict[trade_symbol]["quantity_left"] = order["quantity_left"]
|
|
396
|
+
quantity_dict[trade_symbol]["exit_levels"].append(order["exit_type"])
|
|
397
|
+
|
|
398
|
+
final_out = {}
|
|
399
|
+
for entries in quantity_dict:
|
|
400
|
+
# if quantity_dict[entries]["buy_quantity"] - quantity_dict[entries]["sell_quantity"] > 0:
|
|
401
|
+
if quantity_dict[entries]["quantity_left"] > 0:
|
|
402
|
+
final_out[entries] = quantity_dict[entries]
|
|
403
|
+
return final_out
|
|
404
|
+
|
|
405
|
+
else:
|
|
406
|
+
return {}
|
|
407
|
+
except Exception as e:
|
|
408
|
+
logger.exception("Exception in checking open orders : {}".format(e))
|
|
409
|
+
return {}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def convert_to_trades(orders_list, market_type, order_exit_levels, mode, broker):
|
|
413
|
+
"""Function to convert Orders to Trades """
|
|
414
|
+
try:
|
|
415
|
+
logger.info(msg="* Converting Orders to Trades")
|
|
416
|
+
trade_dict = {}
|
|
417
|
+
trades_array = []
|
|
418
|
+
for order in orders_list:
|
|
419
|
+
# logger.info(msg="order : {}".format(order))
|
|
420
|
+
if order["trade_type"] == "ENTRY":
|
|
421
|
+
trade_dict["date"] = order["date"]
|
|
422
|
+
trade_dict["stock"] = order["tradingsymbol"]
|
|
423
|
+
trade_dict["lot_size"] = order["lot_size"]
|
|
424
|
+
trade_dict["trade_type"] = order["trade_type"]
|
|
425
|
+
trade_dict["bnf_price"] = order["bnf_price"]
|
|
426
|
+
trade_dict["bar_color"] = order["bar_color"]
|
|
427
|
+
trade_dict["entry_time"] = order["order_timestamp"]
|
|
428
|
+
trade_dict["entry_price"] = order["trigger_price"]
|
|
429
|
+
trade_dict["quantity"] = order["quantity"]
|
|
430
|
+
trade_dict["pnl"] = 0
|
|
431
|
+
trade_dict["points"] = 0
|
|
432
|
+
trade_dict["exit_time"] = None
|
|
433
|
+
trade_dict["exit_price"] = None
|
|
434
|
+
trade_dict["exit_type"] = ""
|
|
435
|
+
trade_dict["day"] = order["day"]
|
|
436
|
+
trade_dict["expiry"] = order["expiry"]
|
|
437
|
+
trade_dict["brokerage"] = 0
|
|
438
|
+
trade_dict["net_pnl"] = 0
|
|
439
|
+
|
|
440
|
+
if mode == "lt" or mode == "vt":
|
|
441
|
+
trade_dict["date"] = datetime.datetime.strptime(str(datetime.datetime.today().date()), '%Y-%m-%d')
|
|
442
|
+
trade_dict["user_id"] = bson.ObjectId(order["user_id"])
|
|
443
|
+
trade_dict["strategy_id"] = bson.ObjectId(order["strategy_id"])
|
|
444
|
+
trade_dict["request_id"] = bson.ObjectId(order["request_id"])
|
|
445
|
+
|
|
446
|
+
else:
|
|
447
|
+
if market_type == "cash":
|
|
448
|
+
if order["trade_type"] == "SHORT":
|
|
449
|
+
points = trade_dict["entry_price"] - order["trigger_price"]
|
|
450
|
+
trade_dict["points"] += round(points)
|
|
451
|
+
trade_dict["pnl"] += round(order["quantity"] * points)
|
|
452
|
+
else:
|
|
453
|
+
points = order["trigger_price"] - trade_dict["entry_price"]
|
|
454
|
+
trade_dict["points"] += round(points)
|
|
455
|
+
trade_dict["pnl"] += round(order["quantity"] * points)
|
|
456
|
+
# trade_dict["pnl"] += round(order["quantity"] * trade_dict["points"])
|
|
457
|
+
else:
|
|
458
|
+
points = order["trigger_price"] - trade_dict["entry_price"]
|
|
459
|
+
trade_dict["points"] += round(points)
|
|
460
|
+
trade_dict["pnl"] += round(order["quantity"] * trade_dict["points"] * trade_dict["lot_size"])
|
|
461
|
+
|
|
462
|
+
if trade_dict["exit_type"]:
|
|
463
|
+
trade_dict["exit_type"] += "|" + order["exit_type"]
|
|
464
|
+
else:
|
|
465
|
+
trade_dict["exit_type"] = order["exit_type"]
|
|
466
|
+
|
|
467
|
+
if order["exit_type"] in order_exit_levels:
|
|
468
|
+
trade_dict["exit_time"] = order["order_timestamp"]
|
|
469
|
+
trade_dict["exit_price"] = order["trigger_price"]
|
|
470
|
+
|
|
471
|
+
brokerage, net_pnl = calculate_brokerage(buy_price=trade_dict["entry_price"], sell_price=trade_dict["exit_price"],
|
|
472
|
+
quantity=order["quantity"] * trade_dict["lot_size"], broker=broker)
|
|
473
|
+
trade_dict["brokerage"] += brokerage
|
|
474
|
+
trade_dict["net_pnl"] += net_pnl
|
|
475
|
+
|
|
476
|
+
trades_array.append(trade_dict)
|
|
477
|
+
|
|
478
|
+
# Emptying Trade Dict for next trade
|
|
479
|
+
trade_dict = {}
|
|
480
|
+
else:
|
|
481
|
+
brokerage, net_pnl = calculate_brokerage(buy_price=trade_dict["entry_price"], sell_price=order["trigger_price"],
|
|
482
|
+
quantity=order["quantity"] * trade_dict["lot_size"], broker=broker)
|
|
483
|
+
trade_dict["brokerage"] += brokerage
|
|
484
|
+
trade_dict["net_pnl"] += net_pnl
|
|
485
|
+
logger.info(msg="* total trades : {}".format(len(trades_array)))
|
|
486
|
+
return trades_array
|
|
487
|
+
except Exception as e:
|
|
488
|
+
logger.exception("Exception in converting orders to trades : {}".format(e))
|
|
489
|
+
pass
|