-
Notifications
You must be signed in to change notification settings - Fork 3
/
trailing.py
538 lines (433 loc) · 19.5 KB
/
trailing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
### Sunflow Cryptobot ###
#
# Traling buy and sell
# Load libraries
from loader import load_config
from pybit.unified_trading import HTTP
import database, defs, distance, orders, pprint, threading
# Load config
config = load_config()
# Connect to exchange
session = HTTP(
testnet = False,
api_key = config.api_key,
api_secret = config.api_secret,
return_response_headers = True
)
# Initialize stuck variable
stuck = {}
stuck['check'] = True
stuck['time'] = defs.now_utc()[4]
stuck['interval'] = 20000
# Check if we can do trailing buy or sell
def check_order(symbol, spot, compounding, active_order, all_buys, all_sells, info):
# Debug and speed
debug = False
speed = False
stime = defs.now_utc()[4]
# Declare stuck variable global
global stuck
# Initialize variables
result = ()
type_check = ""
do_check_order = False
# Has current price crossed trigger price
if active_order['side'] == "Sell":
if active_order['current'] <= active_order['trigger']:
type_check = "a regular"
do_check_order = True
else:
if active_order['current'] >= active_order['trigger']:
type_check = "a regular"
do_check_order = True
# Check every interval, sometimes orders get stuck
current_time = defs.now_utc()[4]
if stuck['check']:
stuck['check'] = False
stuck['time'] = defs.now_utc()[4]
if current_time - stuck['time'] > stuck['interval']:
type_check = "an additional"
do_check_order = True
# Current price crossed trigger price
if do_check_order:
# Report to stdout
defs.announce(f"Performing {type_check} check on {active_order['side'].lower()} order")
# Reset stuck
stuck['check'] = True
# Has trailing endend, check if order does still exist
order = {}
message = defs.announce("session: get_open_orders")
try:
order = session.get_open_orders(
category = "spot",
symbol = symbol,
orderID = str(active_order['orderid'])
)
except Exception as e:
defs.log_error(e)
# Check API rate limit and log data if possible
if order:
order = defs.rate_limit(order)
defs.log_exchange(order, message)
# Check if trailing order is filled, if so reset counters and close trailing process
if order['result']['list'] == [] or order['result']['list'][0]['orderStatus'] == "Filled": # *** CHECK *** Odd behavior from exchange, sometimes the realtime table is not cleared
# Prepare message for stdout and Apprise
defs.announce(f"Trailing {active_order['side'].lower()}: *** Order has been filled! ***")
if active_order['side'] == "Buy":
currency = info['quoteCoin']
currency_format = info['quotePrecision']
else:
currency = info['baseCoin']
currency_format = info['basePrecision']
message_1 = f"{active_order['side']} order closed for {defs.format_number(active_order['qty'], currency_format)} {currency} "
message_1 = message_1 + f"at trigger price {defs.format_number(active_order['trigger'], info['tickSize'])} {info['quoteCoin']}"
# Close trailing process
result = close_trail(active_order, all_buys, all_sells, spot, info)
active_order = result[0]
all_buys = result[1]
all_sells = result[2]
transaction = result[3]
revenue = result[4]
# Fill in average price and report message
if active_order['side'] == "Buy":
message_1 = message_1 + f" and fill price {defs.format_number(transaction['avgPrice'], info['tickSize'])} {info['quoteCoin']}"
else:
message_1 = message_1 + f", fill price {defs.format_number(transaction['avgPrice'], info['tickSize'])} {info['quoteCoin']} "
message_1 = message_1 + f"and profit {defs.format_number(revenue, info['quotePrecision'])} {info['quoteCoin']}"
message_2 = f"sold {defs.format_number(active_order['qty'], currency_format)} {currency}, "
message_2 = message_2 + f"profit is {defs.format_number(revenue, info['quotePrecision'])} {info['quoteCoin']}"
# Send message to group 2
defs.announce(message_2, False, 0, True, 1)
# Send message to group 1
defs.announce(message_1, True, 1)
# Report wallet, quote and base currency to stdout and adjust compounding (task)
def report_wallet_task():
compounding['now'] = orders.report_wallet(spot, all_buys, info)[0]
# Report wallet, quote and base currency to stdout and adjust compounding (threat)
if config.wallet_report:
wallet_thread = threading.Thread(target=report_wallet_task)
wallet_thread.start()
# Report compounding, only possible when wallet reporting is active, see config file
if compounding['enabled']:
info = defs.calc_compounding(info, spot, compounding)
# Report to revenue log file
if config.revenue_log:
defs.log_revenue(active_order, transaction, revenue, info, config.revenue_log_sides, config.revenue_log_extend)
# Check if symbol is spiking
else:
result = check_spike(symbol, spot, active_order, order, all_buys, info)
active_order = result[0]
all_buys = result[1]
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return modified data
return active_order, all_buys, compounding, info
# Checks if the trailing error spiked
def check_spike(symbol, spot, active_order, order, all_buys, info):
# Debug and speed
debug = False
speed = True
stime = defs.now_utc()[4]
# Initialize variables
error_code = 0
# Check if the order spiked
transaction = orders.decode(order)
if active_order['side'] == "Sell":
# Did it spike and was forgotten when selling
if transaction['triggerPrice'] > spot:
defs.announce(f"*** Warning: Sell order spiked, cancelling current order! ***", True, 1)
# Reset trailing sell
active_order['active'] = False
# Remove order from exchange
orders.cancel(symbol, active_order['orderid'])
# Rebalance to be safe
all_buys = orders.rebalance(all_buys, info)
else:
# Did it spike and was forgotten when buying
if transaction['triggerPrice'] < spot:
defs.announce(f"*** Warning: Buy order spiked, cancelling current order! ***", True, 1)
# Reset trailing buy
active_order['active'] = False
# Remove order from all buys
all_buys = database.remove(active_order['orderid'], all_buys, info)
# Remove order from exchange
orders.cancel(symbol, active_order['orderid'])
# Rebalance to be safe
all_buys = orders.rebalance(all_buys, info)
if error_code == 1:
defs.announce(f"Although order {active_order['orderid']} spiked, this order was not found at the exchange", True, 1)
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return data
return active_order, all_buys
# Calculate revenue from sell
def calculate_revenue(transaction, all_sells, spot, info):
# Debug and speed
debug = False
speed = True
stime = defs.now_utc()[4]
# Initialize variables
sells = 0
buys = 0
revenue = 0
fees = {}
fees['buy'] = 0
fees['sell'] = 0
fees['total'] = 0
# Logic
sells = transaction['cumExecValue']
buys = sum(item['cumExecValue'] for item in all_sells)
fees['buy'] = sum(item['cumExecFee'] for item in all_sells) * spot
fees['sell'] = transaction['cumExecFee']
fees['total'] = fees['buy'] + fees['sell']
revenue = sells - buys - fees['total']
# Output to stdout for debug
if debug:
message = f"Total sells {sells} {info['quoteCoin']}, buys {buys} {info['quoteCoin']}, "
message = message + f"buy fees {fees['buy']} {info['quoteCoin']}, sell were {fees['sell']}, total fees {fees['total']}, "
message = message + f"giving a revenue of {defs.format_number(revenue, info['quotePrecision'])} {info['quoteCoin']}"
defs.announce(message)
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return revenue
return revenue
# Trailing order does not exist anymore, close it
def close_trail(active_order, all_buys, all_sells, spot, info):
# Debug and speed
debug = False
speed = True
stime = defs.now_utc()[4]
# Initialize variables
revenue = 0
# Make active_order inactive
active_order['active'] = False
# Close the transaction on either buy or sell trailing order
transaction = orders.transaction_from_id(active_order['orderid'])
transaction['status'] = "Closed"
if debug:
defs.announce(f"{active_order['side']} order")
pprint.pprint(transaction)
print()
# Order was bought, create new all buys database
if transaction['side'] == "Buy":
all_buys = database.register_buy(transaction, all_buys, info)
# Order was sold, create new all buys database, rebalance database and clear all sells
if transaction['side'] == "Sell":
# Output to stdout for debug
if debug:
defs.announce("All buy orders matching sell order")
pprint.pprint(all_sells)
print()
# Calculate revenue
revenue = calculate_revenue(transaction, all_sells, spot, info)
# Create new all buys database
all_buys = database.register_sell(all_buys, all_sells, info)
# Clear all sells
all_sells = []
# Rebalance new database
if config.database_rebalance:
all_buys = orders.rebalance(all_buys, info)
# Output to stdout
defs.announce(f"Closed trailing {active_order['side'].lower()} order")
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return modified data
return active_order, all_buys, all_sells, transaction, revenue
# Trailing buy or sell
def trail(symbol, spot, compounding, active_order, info, all_buys, all_sells, prices):
# Debug and speed
debug = False
speed = False
stime = defs.now_utc()[4]
# Initialize variables
result = ()
do_amend = False
# Output trailing to stdout
if debug:
defs.announce(f"Trailing {active_order['side']}: Checking if we can do trailing")
# Check if the order still exists
result = check_order(symbol, spot, compounding, active_order, all_buys, all_sells, info)
active_order = result[0]
all_buys = result[1]
compounding = result[2]
info = result[3]
# Order still exists, we can do trailing buy or sell
if active_order['active']:
# We have a new price
active_order['previous'] = active_order['current']
# Determine distance of trigger price
active_order = distance.calculate(active_order, prices)
# Calculate new trigger price
if active_order['side'] == "Sell":
active_order['trigger_new'] = defs.round_number(active_order['current'] * (1 - (active_order['fluctuation'] / 100)), info['tickSize'], "down")
else:
active_order['trigger_new'] = defs.round_number(active_order['current'] * (1 + (active_order['fluctuation'] / 100)), info['tickSize'], "up")
# Check if we can amend trigger price
if active_order['side'] == "Sell":
if active_order['trigger_new'] > active_order['trigger']:
do_amend = True
else:
if active_order['trigger_new'] < active_order['trigger']:
do_amend = True
# Amend trigger price
if do_amend:
active_order = atp_helper(symbol, active_order, info)
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return modified data
return active_order, all_buys, compounding, info
# Change trigger price current trailing sell helper
def aqs_helper(symbol, active_order, info, all_sells, all_sells_new):
# Initialize variables
debug = False
result = ()
amend_code = 0
amend_error = ""
# Amend order quantity
result = amend_quantity_sell(symbol, active_order, info)
amend_code = result[0]
amend_error = result[1]
# Determine what to do based on error code of amend result
if amend_code == 0:
# Everything went fine, we can continue trailing
message = f"Adjusted quantity from {defs.format_number(active_order['qty'], info['basePrecision'])} "
message = message + f"to {defs.format_number(active_order['qty_new'], info['basePrecision'])} {info['baseCoin']} in {active_order['side'].lower()} order"
defs.announce(message, True, 0)
all_sells = all_sells_new
active_order['qty'] = active_order['qty_new']
if amend_code == 1:
# Order does not exist, trailing order was sold in between
all_sells_new = all_sells
defs.announce("Adjusting trigger quantity not possible, sell order already hit", True, 0)
if amend_code == 2:
# Quantity could not be changed, do nothing
all_sells_new = all_sells
defs.announce("Sell order quantity could not be changed, doing nothing", True, 0)
if amend_code == 10:
all_sells_new = all_sells
# Order does not support modification, do nothing
defs.announce("Sell order quantity could not be changed, order does not support modification", True, 0)
if amend_code == 100:
# Critical error, let's log it and revert
defs.announce("*** Warning: Critical failure while trailing! ***", True, 1)
defs.log_error(amend_error)
# Return data
return active_order, all_sells, all_sells_new
# Change the quantity of the current trailing sell
def amend_quantity_sell(symbol, active_order, info):
# Debug and speed
debug = False
speed = True
stime = defs.now_utc()[4]
# Initialize variables
order = {}
error_code = 0
exception = ""
# Output to stdout
message = f"Trying to adjust quantity from {defs.format_number(active_order['qty'], info['basePrecision'])} "
message = message + f"to {defs.format_number(active_order['qty_new'], info['basePrecision'])} {info['baseCoin']}"
defs.announce(message)
# Ammend order
order = {}
message = defs.announce("session: amend_order")
try:
order = session.amend_order(
category = "spot",
symbol = symbol,
orderId = str(active_order['orderid']),
qty = str(active_order['qty_new'])
)
except Exception as e:
exception = str(e)
if "(ErrCode: 170213)" in exception:
# Order does not exist
error_code = 1
elif "(ErrCode: 10001)" in exception:
error_code = 2
elif "(ErrCode: 170312)" in exception:
# Could not modify
error_code = 10
else:
# Any other error
error_code = 100
# Check API rate limit and log data if possible
if order:
order = defs.rate_limit(order)
defs.log_exchange(order, message)
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return error code
return error_code, exception
# Change quantity trailing sell helper
def atp_helper(symbol, active_order, info):
# Initialize variables
debug = False
result = ()
amend_code = 0
amend_error = ""
# Amend trigger price
result = amend_trigger_price(symbol, active_order, info)
amend_code = result[0]
amend_error = result[1]
# Determine what to do based on error code of amend result
if amend_code == 0:
# Everything went fine, we can continue trailing
message = f"Adjusted trigger price from {defs.format_number(active_order['trigger'], info['tickSize'])} to "
message = message + f"{defs.format_number(active_order['trigger_new'], info['tickSize'])} {info['quoteCoin']} in {active_order['side'].lower()} order"
defs.announce(message, True, 0)
active_order['trigger'] = active_order['trigger_new']
if amend_code == 1:
# Order does not exist, trailing order sold or bought in between
defs.announce(f"Adjusting trigger price not possible, {active_order['side'].lower()} order already hit", True, 0)
if amend_code == 10:
# Order does not support modification
defs.announce(f"Adjusting trigger price not possible, {active_order['side'].lower()} order does not support modification", True, 0)
if amend_code == 100:
# Critical error, let's log it and revert
defs.announce("*** Warning: Critical failure while trailing", True, 1)
defs.log_error(amend_error)
# Return active_order
return active_order
# Change the trigger price of the current trailing sell
def amend_trigger_price(symbol, active_order, info):
# Debug and speed
debug = False
speed = True
stime = defs.now_utc()[4]
# Initialize variables
order = {}
error_code = 0
exception = ""
# Output to stdout
message = f"Trying to adjusted trigger price from {defs.format_number(active_order['trigger'], info['tickSize'])} to "
message = message + f"{defs.format_number(active_order['trigger_new'], info['tickSize'])} {info['quoteCoin']}"
defs.announce(message)
# Amend order
order = {}
message = defs.announce("session: amend_order")
try:
order = session.amend_order(
category = "spot",
symbol = symbol,
orderId = str(active_order['orderid']),
triggerPrice = str(active_order['trigger_new'])
)
except Exception as e:
exception = str(e)
if "(ErrCode: 170213)" in exception:
# Order does not exist
error_code = 1
elif "(ErrCode: 170312)" in exception:
# Could not modify
error_code = 10
else:
# Any other error
error_code = 100
# Check API rate limit and log data if possible
if order:
order = defs.rate_limit(order)
defs.log_exchange(order, message)
# Report execution time
if speed: defs.announce(defs.report_exec(stime))
# Return error code
return error_code, exception