forked from enarjord/passivbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
passivbot.py
1419 lines (1336 loc) · 56 KB
/
passivbot.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
if "NOJIT" not in os.environ:
os.environ["NOJIT"] = "true"
import traceback
import argparse
import asyncio
import json
import signal
import pprint
import numpy as np
from time import time
from procedures import (
load_live_config,
make_get_filepath,
load_exchange_key_secret_passphrase,
numpyize,
print_async_exception,
)
from pure_funcs import (
filter_orders,
create_xk,
round_dynamic,
denumpyize,
spotify_config,
determine_passivbot_mode,
config_pretty_str,
)
from njit_funcs import (
qty_to_cost,
calc_diff,
round_,
calc_close_grid_long,
calc_close_grid_short,
calc_upnl,
calc_entry_grid_long,
calc_entry_grid_short,
calc_samples,
calc_emas_last,
calc_ema,
)
from njit_funcs_neat_grid import (
calc_neat_grid_long,
calc_neat_grid_short,
)
from njit_funcs_recursive_grid import (
calc_recursive_entries_long,
calc_recursive_entries_short,
)
from typing import Union, Dict, List
import websockets
import logging
TEST_MODE_SUPPORTED_EXCHANGES = ["bybit"]
class Bot:
def __init__(self, config: dict):
self.spot = False
self.config = config
self.config["do_long"] = config["long"]["enabled"]
self.config["do_short"] = config["short"]["enabled"]
self.config["max_leverage"] = 25
self.xk = {}
self.ws_user = None
self.ws_market = None
self.hedge_mode = self.config["hedge_mode"] = True
self.set_config(self.config)
self.ts_locked = {
k: 0.0
for k in [
"cancel_orders",
"update_open_orders",
"cancel_and_create",
"update_position",
"create_orders",
"check_fills",
"update_fills",
"force_update",
]
}
self.ts_released = {k: 1.0 for k in self.ts_locked}
self.error_halt = {
"update_open_orders": False,
"update_fills": False,
"update_position": False,
}
self.heartbeat_ts = 0
self.heartbeat_interval_seconds = 60 * 60
self.listen_key = None
self.position = {}
self.open_orders = []
self.fills = []
self.price = 0.0
self.ob = [0.0, 0.0]
self.emas_long = np.zeros(3)
self.emas_short = np.zeros(3)
self.ema_sec = 0
self.n_orders_per_execution = 2
self.delay_between_executions = 3
self.force_update_interval = 30
self.c_mult = self.config["c_mult"] = 1.0
self.log_filepath = make_get_filepath(f"logs/{self.exchange}/{config['config_name']}.log")
self.api_keys = config["api_keys"] if "api_keys" in config else None
_, self.key, self.secret, self.passphrase = load_exchange_key_secret_passphrase(
self.user, self.api_keys
)
self.log_level = 0
self.user_stream_task = None
self.market_stream_task = None
self.stop_websocket = False
self.process_websocket_ticks = True
def set_config(self, config):
for k, v in [
("long_mode", None),
("short_mode", None),
("test_mode", False),
("assigned_balance", None),
("cross_wallet_pct", 1.0),
("price_distance_threshold", 0.5),
("c_mult", 1.0),
("leverage", 7.0),
]:
if k not in config:
config[k] = v
self.passivbot_mode = config["passivbot_mode"] = determine_passivbot_mode(config)
if config["cross_wallet_pct"] > 1.0 or config["cross_wallet_pct"] <= 0.0:
logging.warning(
f"Invalid cross_wallet_pct given: {config['cross_wallet_pct']}. "
+ "It must be greater than zero and less than or equal to one. Defaulting to 1.0."
)
config["cross_wallet_pct"] = 1.0
self.ema_spans_long = [
config["long"]["ema_span_0"],
(config["long"]["ema_span_0"] * config["long"]["ema_span_1"]) ** 0.5,
config["long"]["ema_span_1"],
]
self.ema_spans_short = [
config["short"]["ema_span_0"],
(config["short"]["ema_span_0"] * config["short"]["ema_span_1"]) ** 0.5,
config["short"]["ema_span_1"],
]
self.config = config
for key in config:
setattr(self, key, config[key])
if key in self.xk:
self.xk[key] = config[key]
def set_config_value(self, key, value):
self.config[key] = value
setattr(self, key, self.config[key])
async def _init(self):
self.xk = create_xk(self.config)
await self.init_fills()
def dump_log(self, data) -> None:
if self.config["logging_level"] > 0:
with open(self.log_filepath, "a") as f:
f.write(
json.dumps({**{"log_timestamp": time(), "symbol": self.symbol}, **data}) + "\n"
)
async def init_emas(self) -> None:
ohlcvs1m = await self.fetch_ohlcvs(interval="1m")
max_span = max(list(self.ema_spans_long) + list(self.ema_spans_short))
for mins, interval in zip([5, 15, 30, 60, 60 * 4], ["5m", "15m", "30m", "1h", "4h"]):
if max_span <= len(ohlcvs1m) * mins:
break
ohlcvs = await self.fetch_ohlcvs(interval=interval)
ohlcvs = {ohlcv["timestamp"]: ohlcv for ohlcv in ohlcvs + ohlcvs1m}
samples1s = calc_samples(
numpyize(
[
[o["timestamp"], o["volume"], o["close"]]
for o in sorted(ohlcvs.values(), key=lambda x: x["timestamp"])
]
)
)
spans1s_long = np.array(self.ema_spans_long) * 60
spans1s_short = np.array(self.ema_spans_short) * 60
self.emas_long = calc_emas_last(samples1s[:, 2], spans1s_long)
self.emas_short = calc_emas_last(samples1s[:, 2], spans1s_short)
self.alpha_long = 2 / (spans1s_long + 1)
self.alpha__long = 1 - self.alpha_long
self.alpha_short = 2 / (spans1s_short + 1)
self.alpha__short = 1 - self.alpha_short
self.ema_sec = int(time())
# return samples1s
def update_emas(self, price: float, prev_price: float) -> None:
now_sec = int(time())
if now_sec <= self.ema_sec:
return
while self.ema_sec < int(round(now_sec - 1)):
self.emas_long = calc_ema(self.alpha_long, self.alpha__long, self.emas_long, prev_price)
self.emas_short = calc_ema(
self.alpha_short, self.alpha__short, self.emas_short, prev_price
)
self.ema_sec += 1
self.emas_long = calc_ema(self.alpha_long, self.alpha__long, self.emas_long, price)
self.emas_short = calc_ema(self.alpha_short, self.alpha__short, self.emas_short, price)
self.ema_sec = now_sec
async def update_open_orders(self) -> None:
if self.ts_locked["update_open_orders"] > self.ts_released["update_open_orders"]:
return
try:
open_orders = await self.fetch_open_orders()
open_orders = [x for x in open_orders if x["symbol"] == self.symbol]
if self.open_orders != open_orders:
self.dump_log({"log_type": "open_orders", "data": open_orders})
self.open_orders = open_orders
self.error_halt["update_open_orders"] = False
return True
except Exception as e:
self.error_halt["update_open_orders"] = True
logging.error(f"error with update open orders {e}")
traceback.print_exc()
return False
finally:
self.ts_released["update_open_orders"] = time()
def adjust_wallet_balance(self, balance: float) -> float:
return (
balance if self.assigned_balance is None else self.assigned_balance
) * self.cross_wallet_pct
def add_wallet_exposures_to_pos(self, position_: dict):
position = position_.copy()
position["long"]["wallet_exposure"] = (
(
qty_to_cost(
position["long"]["size"],
position["long"]["price"],
self.xk["inverse"],
self.xk["c_mult"],
)
/ position["wallet_balance"]
)
if position["wallet_balance"]
else 0.0
)
position["short"]["wallet_exposure"] = (
(
qty_to_cost(
position["short"]["size"],
position["short"]["price"],
self.xk["inverse"],
self.xk["c_mult"],
)
/ position["wallet_balance"]
)
if position["wallet_balance"]
else 0.0
)
return position
async def update_position(self) -> None:
if self.ts_locked["update_position"] > self.ts_released["update_position"]:
return
self.ts_locked["update_position"] = time()
try:
position = await self.fetch_position()
position["wallet_balance"] = self.adjust_wallet_balance(position["wallet_balance"])
# isolated equity, not cross equity
position["equity"] = position["wallet_balance"] + calc_upnl(
position["long"]["size"],
position["long"]["price"],
position["short"]["size"],
position["short"]["price"],
self.price,
self.inverse,
self.c_mult,
)
position = self.add_wallet_exposures_to_pos(position)
if self.position != position:
if (
self.position
and "spot" in self.market_type
and (
self.position["long"]["size"] != position["long"]["size"]
or self.position["short"]["size"] != position["short"]["size"]
)
):
# update fills if position size changed
await self.update_fills()
self.dump_log({"log_type": "position", "data": position})
self.position = position
self.error_halt["update_position"] = False
return True
except Exception as e:
self.error_halt["update_position"] = True
logging.error(f"error with update position {e}")
traceback.print_exc()
return False
finally:
self.ts_released["update_position"] = time()
async def init_fills(self, n_days_limit=60):
self.fills = await self.fetch_fills()
async def update_fills(self) -> [dict]:
"""
fetches recent fills
returns list of new fills
"""
if self.ts_locked["update_fills"] > self.ts_released["update_fills"]:
return
self.ts_locked["update_fills"] = time()
try:
fetched = await self.fetch_fills()
seen = set()
updated_fills = []
for fill in fetched + self.fills:
if fill["order_id"] not in seen:
updated_fills.append(fill)
seen.add(fill["order_id"])
self.fills = sorted(updated_fills, key=lambda x: x["order_id"])[-5000:]
self.error_halt["update_fills"] = False
except Exception as e:
self.error_halt["update_fills"] = True
logging.error(f"error with update fills {e}")
traceback.print_exc()
finally:
self.ts_released["update_fills"] = time()
async def create_orders(self, orders_to_create: [dict]) -> [dict]:
if not orders_to_create:
return []
if self.ts_locked["create_orders"] > self.ts_released["create_orders"]:
return []
self.ts_locked["create_orders"] = time()
try:
orders = await self.execute_orders(orders_to_create)
for order in sorted(orders, key=lambda x: calc_diff(x["price"], self.price)):
if "side" in order:
logging.info(
f' created order {order["symbol"]} {order["side"]: <4} '
+ f'{order["position_side"]: <5} {order["qty"]} {order["price"]}'
)
return orders
finally:
self.ts_released["create_orders"] = time()
async def cancel_orders(self, orders_to_cancel: [dict]) -> [dict]:
if self.ts_locked["cancel_orders"] > self.ts_released["cancel_orders"]:
return
self.ts_locked["cancel_orders"] = time()
try:
if not orders_to_cancel:
return
deletions, orders_to_cancel_dedup, oo_ids = [], [], set()
for o in orders_to_cancel:
if o["order_id"] not in oo_ids:
oo_ids.add(o["order_id"])
orders_to_cancel_dedup.append(o)
cancellations = None
try:
cancellations = await self.execute_cancellations(orders_to_cancel_dedup)
for cancellation in cancellations:
if "order_id" in cancellation:
logging.info(
f'cancelled order {cancellation["symbol"]} {cancellation["side"]: <4} '
+ f'{cancellation["position_side"]: <5} {cancellation["qty"]} {cancellation["price"]}'
)
self.open_orders = [
oo
for oo in self.open_orders
if oo["order_id"] != cancellation["order_id"]
]
return cancellations
except Exception as e:
logging.error(f"error cancelling orders {cancellations} {e}")
print_async_exception(cancellations)
return []
finally:
self.ts_released["cancel_orders"] = time()
def stop(self, signum=None, frame=None) -> None:
logging.info("Stopping passivbot, please wait...")
self.stop_websocket = True
if not self.ohlcv:
try:
self.user_stream_task.cancel()
self.market_stream_task.cancel()
except Exception as e:
logging.error(f"An error occurred during shutdown: {e}")
def pause(self) -> None:
self.process_websocket_ticks = False
def resume(self) -> None:
self.process_websocket_ticks = True
def calc_orders(self):
balance = self.position["wallet_balance"]
psize_long = self.position["long"]["size"]
pprice_long = self.position["long"]["price"]
psize_short = self.position["short"]["size"]
pprice_short = self.position["short"]["price"]
if self.hedge_mode:
do_long = self.do_long or psize_long != 0.0
do_short = self.do_short or psize_short != 0.0
else:
no_pos = psize_long == 0.0 and psize_short == 0.0
do_long = (no_pos and self.do_long) or psize_long != 0.0
do_short = (no_pos and self.do_short) or psize_short != 0.0
self.xk["do_long"] = do_long
self.xk["do_short"] = do_short
orders = []
if self.long_mode == "panic":
if psize_long != 0.0:
orders.append(
{
"side": "sell",
"position_side": "long",
"qty": abs(psize_long),
"price": float(self.ob[1]),
"type": "limit",
"reduce_only": True,
"custom_id": "long_panic_close",
}
)
else:
if do_long:
if self.passivbot_mode == "recursive_grid":
entries_long = calc_recursive_entries_long(
balance,
psize_long,
pprice_long,
self.ob[0],
min(self.emas_long),
self.xk["inverse"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["initial_qty_pct"][0],
self.xk["initial_eprice_ema_dist"][0],
self.xk["ddown_factor"][0],
self.xk["rentry_pprice_dist"][0],
self.xk["rentry_pprice_dist_wallet_exposure_weighting"][0],
self.xk["wallet_exposure_limit"][0],
self.xk["auto_unstuck_ema_dist"][0],
self.xk["auto_unstuck_wallet_exposure_threshold"][0],
)
elif self.passivbot_mode == "static_grid":
entries_long = calc_entry_grid_long(
balance,
psize_long,
pprice_long,
self.ob[0],
min(self.emas_long),
self.xk["inverse"],
self.xk["do_long"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["grid_span"][0],
self.xk["wallet_exposure_limit"][0],
self.xk["max_n_entry_orders"][0],
self.xk["initial_qty_pct"][0],
self.xk["initial_eprice_ema_dist"][0],
self.xk["eprice_pprice_diff"][0],
self.xk["secondary_allocation"][0],
self.xk["secondary_pprice_diff"][0],
self.xk["eprice_exp_base"][0],
self.xk["auto_unstuck_wallet_exposure_threshold"][0],
self.xk["auto_unstuck_ema_dist"][0],
)
elif self.passivbot_mode == "neat_grid":
entries_long = calc_neat_grid_long(
balance,
psize_long,
pprice_long,
self.ob[0],
min(self.emas_long),
self.xk["inverse"],
self.xk["do_long"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["grid_span"][0],
self.xk["wallet_exposure_limit"][0],
self.xk["max_n_entry_orders"][0],
self.xk["initial_qty_pct"][0],
self.xk["initial_eprice_ema_dist"][0],
self.xk["eqty_exp_base"][0],
self.xk["eprice_exp_base"][0],
self.xk["auto_unstuck_wallet_exposure_threshold"][0],
self.xk["auto_unstuck_ema_dist"][0],
)
else:
raise Exception(f"unknown passivbot mode {self.passivbot_mode}")
orders += [
{
"side": "buy",
"position_side": "long",
"qty": abs(float(o[0])),
"price": float(o[1]),
"type": "limit",
"reduce_only": False,
"custom_id": o[2],
}
for o in entries_long
if o[0] > 0.0
]
if do_long or self.long_mode == "tp_only":
closes_long = calc_close_grid_long(
self.xk["backwards_tp"][0],
balance,
psize_long,
pprice_long,
self.ob[1],
max(self.emas_long),
self.xk["inverse"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["wallet_exposure_limit"][0],
self.xk["min_markup"][0],
self.xk["markup_range"][0],
self.xk["n_close_orders"][0],
self.xk["auto_unstuck_wallet_exposure_threshold"][0],
self.xk["auto_unstuck_ema_dist"][0],
)
orders += [
{
"side": "sell",
"position_side": "long",
"qty": abs(float(o[0])),
"price": float(o[1]),
"type": "limit",
"reduce_only": True,
"custom_id": o[2],
}
for o in closes_long
if o[0] < 0.0
]
if self.short_mode == "panic":
if psize_short != 0.0:
orders.append(
{
"side": "buy",
"position_side": "short",
"qty": abs(psize_short),
"price": float(self.ob[0]),
"type": "limit",
"reduce_only": True,
"custom_id": "short_panic_close",
}
)
else:
if do_short:
if self.passivbot_mode == "recursive_grid":
entries_short = calc_recursive_entries_short(
balance,
psize_short,
pprice_short,
self.ob[1],
max(self.emas_short),
self.xk["inverse"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["initial_qty_pct"][1],
self.xk["initial_eprice_ema_dist"][1],
self.xk["ddown_factor"][1],
self.xk["rentry_pprice_dist"][1],
self.xk["rentry_pprice_dist_wallet_exposure_weighting"][1],
self.xk["wallet_exposure_limit"][1],
self.xk["auto_unstuck_ema_dist"][1],
self.xk["auto_unstuck_wallet_exposure_threshold"][1],
)
elif self.passivbot_mode == "neat_grid":
entries_short = calc_neat_grid_short(
balance,
psize_short,
pprice_short,
self.ob[1],
max(self.emas_short),
self.xk["inverse"],
self.xk["do_short"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["grid_span"][1],
self.xk["wallet_exposure_limit"][1],
self.xk["max_n_entry_orders"][1],
self.xk["initial_qty_pct"][1],
self.xk["initial_eprice_ema_dist"][1],
self.xk["eqty_exp_base"][1],
self.xk["eprice_exp_base"][1],
self.xk["auto_unstuck_wallet_exposure_threshold"][1],
self.xk["auto_unstuck_ema_dist"][1],
)
elif self.passivbot_mode == "static_grid":
entries_short = calc_entry_grid_short(
balance,
psize_short,
pprice_short,
self.ob[1],
max(self.emas_short),
self.xk["inverse"],
self.xk["do_short"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["grid_span"][1],
self.xk["wallet_exposure_limit"][1],
self.xk["max_n_entry_orders"][1],
self.xk["initial_qty_pct"][1],
self.xk["initial_eprice_ema_dist"][1],
self.xk["eprice_pprice_diff"][1],
self.xk["secondary_allocation"][1],
self.xk["secondary_pprice_diff"][1],
self.xk["eprice_exp_base"][1],
self.xk["auto_unstuck_wallet_exposure_threshold"][1],
self.xk["auto_unstuck_ema_dist"][1],
)
else:
raise Exception(f"unknown passivbot mode {self.passivbot_mode}")
orders += [
{
"side": "sell",
"position_side": "short",
"qty": abs(float(o[0])),
"price": float(o[1]),
"type": "limit",
"reduce_only": False,
"custom_id": o[2],
}
for o in entries_short
if o[0] < 0.0
]
if do_short or self.short_mode == "tp_only":
closes_short = calc_close_grid_short(
self.xk["backwards_tp"][1],
balance,
psize_short,
pprice_short,
self.ob[0],
min(self.emas_short),
self.xk["inverse"],
self.xk["qty_step"],
self.xk["price_step"],
self.xk["min_qty"],
self.xk["min_cost"],
self.xk["c_mult"],
self.xk["wallet_exposure_limit"][1],
self.xk["min_markup"][1],
self.xk["markup_range"][1],
self.xk["n_close_orders"][1],
self.xk["auto_unstuck_wallet_exposure_threshold"][1],
self.xk["auto_unstuck_ema_dist"][1],
)
orders += [
{
"side": "buy",
"position_side": "short",
"qty": abs(float(o[0])),
"price": float(o[1]),
"type": "limit",
"reduce_only": True,
"custom_id": o[2],
}
for o in closes_short
if o[0] > 0.0
]
return sorted(orders, key=lambda x: calc_diff(x["price"], self.price))
async def cancel_and_create(self):
if self.ts_locked["cancel_and_create"] > self.ts_released["cancel_and_create"]:
return
self.ts_locked["cancel_and_create"] = time()
try:
if any(self.error_halt.values()):
logging.warning(
f"warning: error in rest api fetch {self.error_halt}, "
+ "halting order creations/cancellations"
)
return []
ideal_orders = []
all_orders = self.calc_orders()
for o in all_orders:
if (
not self.ohlcv
and "ientry" in o["custom_id"]
and calc_diff(o["price"], self.price) < 0.002
):
# call update_position() before making initial entry orders
# in case websocket has failed
logging.info(
f"update_position with REST API before creating initial entries. Last price {self.price}"
)
await self.update_position()
all_orders = self.calc_orders()
break
for o in all_orders:
if any(x in o["custom_id"] for x in ["ientry", "unstuck"]) and not self.ohlcv:
if calc_diff(o["price"], self.price) < 0.01:
# EMA based orders must be closer than 1% of current price unless ohlcv mode
ideal_orders.append(o)
else:
if calc_diff(o["price"], self.price) < self.price_distance_threshold:
# all orders must be closer than x% of current price
ideal_orders.append(o)
to_cancel_, to_create_ = filter_orders(
self.open_orders,
ideal_orders,
keys=["side", "position_side", "qty", "price"],
)
to_cancel, to_create = [], []
for elm in to_cancel_:
if elm["position_side"] == "long":
if self.long_mode == "tp_only":
if elm["side"] == "sell":
to_cancel.append(elm)
elif self.long_mode != "manual":
to_cancel.append(elm)
if elm["position_side"] == "short":
if self.short_mode == "tp_only":
if elm["side"] == "buy":
to_cancel.append(elm)
elif self.short_mode != "manual":
to_cancel.append(elm)
else:
to_cancel.append(elm)
for elm in to_create_:
if elm["position_side"] == "long":
if self.long_mode == "tp_only":
if elm["side"] == "sell":
to_create.append(elm)
elif self.long_mode != "manual":
to_create.append(elm)
if elm["position_side"] == "short":
if self.short_mode == "tp_only":
if elm["side"] == "buy":
to_create.append(elm)
elif self.short_mode != "manual":
to_create.append(elm)
to_cancel = sorted(to_cancel, key=lambda x: calc_diff(x["price"], self.price))
to_create = sorted(to_create, key=lambda x: calc_diff(x["price"], self.price))
"""
logging.info(f"to_cancel {to_cancel}")
logging.info(f"to create {to_create}")
return
"""
results = []
if to_cancel:
results.append(
asyncio.create_task(
self.cancel_orders(to_cancel[: self.max_n_cancellations_per_batch])
)
)
await asyncio.sleep(
0.01
) # sleep 10 ms between sending cancellations and sending creations
if to_create:
results.append(await self.create_orders(to_create[: self.max_n_orders_per_batch]))
return results
finally:
await asyncio.sleep(self.delay_between_executions) # sleep before releasing lock
self.ts_released["cancel_and_create"] = time()
async def on_market_stream_event(self, ticks: [dict]):
if ticks:
for tick in ticks:
if tick["is_buyer_maker"]:
self.ob[0] = tick["price"]
else:
self.ob[1] = tick["price"]
self.update_emas(ticks[-1]["price"], self.price)
self.price = ticks[-1]["price"]
now = time()
if now - self.ts_released["force_update"] > self.force_update_interval:
self.ts_released["force_update"] = now
# force update pos and open orders thru rest API every x sec (default 30)
await asyncio.gather(self.update_position(), self.update_open_orders())
if now - self.heartbeat_ts > self.heartbeat_interval_seconds:
# print heartbeat once an hour
self.heartbeat_print()
self.heartbeat_ts = time()
await self.cancel_and_create()
def heartbeat_print(self):
logging.info(f"heartbeat {self.symbol}")
self.log_position_long()
self.log_position_short()
liq_price = self.position["long"]["liquidation_price"]
if calc_diff(self.position["short"]["liquidation_price"], self.price) < calc_diff(
liq_price, self.price
):
liq_price = self.position["short"]["liquidation_price"]
logging.info(
f'balance: {round_dynamic(self.position["wallet_balance"], 6)}'
+ f' equity: {round_dynamic(self.position["equity"], 6)} last price: {self.price}'
+ f" liq: {round_(liq_price, self.price_step)}"
)
def log_position_long(self, prev_pos=None):
closes_long = sorted(
[o for o in self.open_orders if o["side"] == "sell" and o["position_side"] == "long"],
key=lambda x: x["price"],
)
entries_long = sorted(
[o for o in self.open_orders if o["side"] == "buy" and o["position_side"] == "long"],
key=lambda x: x["price"],
)
leqty, leprice = (
(entries_long[-1]["qty"], entries_long[-1]["price"]) if entries_long else (0.0, 0.0)
)
lcqty, lcprice = (
(closes_long[0]["qty"], closes_long[0]["price"]) if closes_long else (0.0, 0.0)
)
prev_pos_line = (
(
f'long: {prev_pos["long"]["size"]} @'
+ f' {round_(prev_pos["long"]["price"], self.price_step)} -> '
)
if prev_pos
else ""
)
logging.info(
prev_pos_line
+ f'long: {self.position["long"]["size"]} @'
+ f' {round_(self.position["long"]["price"], self.price_step)}'
+ f' lWE: {self.position["long"]["wallet_exposure"]:.4f}'
+ f' pprc diff {self.position["long"]["price"] / self.price - 1:.3f}'
+ f" EMAs: {[round_dynamic(e, 5) for e in self.emas_long]}"
+ f" e {leqty} @ {leprice} | c {lcqty} @ {lcprice}"
)
def log_position_short(self, prev_pos=None):
closes_short = sorted(
[o for o in self.open_orders if o["side"] == "buy" and o["position_side"] == "short"],
key=lambda x: x["price"],
)
entries_short = sorted(
[o for o in self.open_orders if o["side"] == "sell" and o["position_side"] == "short"],
key=lambda x: x["price"],
)
leqty, leprice = (
(entries_short[0]["qty"], entries_short[0]["price"]) if entries_short else (0.0, 0.0)
)
lcqty, lcprice = (
(closes_short[-1]["qty"], closes_short[-1]["price"]) if closes_short else (0.0, 0.0)
)
pprice_diff = (
(self.price / self.position["short"]["price"] - 1)
if self.position["short"]["price"] != 0.0
else 1.0
)
prev_pos_line = (
(
f'short: {prev_pos["short"]["size"]} @'
+ f' {round_(prev_pos["short"]["price"], self.price_step)} -> '
)
if prev_pos
else ""
)
logging.info(
prev_pos_line
+ f'short: {self.position["short"]["size"]} @'
+ f' {round_(self.position["short"]["price"], self.price_step)}'
+ f' sWE: {self.position["short"]["wallet_exposure"]:.4f}'
+ f" pprc diff {pprice_diff:.3f}"
+ f" EMAs: {[round_dynamic(e, 5) for e in self.emas_short]}"
+ f" e {leqty} @ {leprice} | c {lcqty} @ {lcprice}"
)
async def on_user_stream_events(self, events: Union[List[Dict], List]) -> None:
if type(events) == list:
for event in events:
await self.on_user_stream_event(event)
else:
await self.on_user_stream_event(events)
async def on_user_stream_event(self, event: dict) -> None:
try:
if "logged_in" in event:
# bitget needs to login before sending subscribe requests
await self.subscribe_to_user_stream(self.ws_user)
pos_change = False
if "wallet_balance" in event:
new_wallet_balance = self.adjust_wallet_balance(event["wallet_balance"])
if new_wallet_balance != self.position["wallet_balance"]:
liq_price = self.position["long"]["liquidation_price"]
if calc_diff(self.position["short"]["liquidation_price"], self.price) < calc_diff(
liq_price, self.price
):
liq_price = self.position["short"]["liquidation_price"]
logging.info(
f"balance: {round_dynamic(new_wallet_balance, 6)}"
+ f' equity: {round_dynamic(self.position["equity"], 6)} last price: {self.price}'
+ f" liq: {round_(liq_price, self.price_step)}"
)
self.position["wallet_balance"] = new_wallet_balance
pos_change = True
if "psize_long" in event:
do_log = False
if event["psize_long"] != self.position["long"]["size"]:
do_log = True
self.position["long"]["size"] = event["psize_long"]
self.position["long"]["price"] = event["pprice_long"]
self.position = self.add_wallet_exposures_to_pos(self.position)
pos_change = True
if do_log:
self.log_position_long()
if "psize_short" in event:
do_log = False
if event["psize_short"] != self.position["short"]["size"]:
do_log = True
self.position["short"]["size"] = event["psize_short"]
self.position["short"]["price"] = event["pprice_short"]
self.position = self.add_wallet_exposures_to_pos(self.position)
pos_change = True
if do_log:
self.log_position_short()
if "new_open_order" in event:
if event["new_open_order"]["order_id"] not in {
x["order_id"] for x in self.open_orders
}:
self.open_orders.append(event["new_open_order"])
if "deleted_order_id" in event:
self.open_orders = [
oo for oo in self.open_orders if oo["order_id"] != event["deleted_order_id"]
]
if "partially_filled" in event:
logging.info(f"partial fill {list(event.values())}")
await self.update_open_orders()
if pos_change:
self.position["equity"] = self.position["wallet_balance"] + calc_upnl(
self.position["long"]["size"],
self.position["long"]["price"],
self.position["short"]["size"],
self.position["short"]["price"],
self.price,
self.inverse,
self.c_mult,
)
await asyncio.sleep(
0.01
) # sleep 10 ms to catch both pos update and open orders update
await self.cancel_and_create()
except Exception as e:
logging.error(f"error handling user stream event, {e}")
traceback.print_exc()
def flush_stuck_locks(self, timeout: float = 5.0) -> None:
timeout = max(timeout, self.delay_between_executions + 1)
now = time()
for key in self.ts_locked:
if self.ts_locked[key] > self.ts_released[key]:
if now - self.ts_locked[key] > timeout:
logging.warning(f"flushing stuck lock {key}")
self.ts_released[key] = now
async def start_websocket(self) -> None:
self.stop_websocket = False
self.process_websocket_ticks = True
await asyncio.gather(self.update_position(), self.update_open_orders())
await self.init_exchange_config()