forked from enarjord/passivbot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
passivbot_multi.py
1954 lines (1854 loc) · 87 KB
/
passivbot_multi.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 hjson
import pprint
import numpy as np
from prettytable import PrettyTable
from uuid import uuid4
from copy import deepcopy
from collections import defaultdict
from procedures import (
load_broker_code,
load_user_info,
utc_ms,
make_get_filepath,
load_live_config,
get_file_mod_utc,
get_first_ohlcv_timestamps,
load_hjson_config,
)
from njit_funcs_recursive_grid import calc_recursive_entries_long, calc_recursive_entries_short
from njit_funcs import (
calc_samples,
calc_emas_last,
calc_ema,
calc_close_grid_long,
calc_close_grid_short,
calc_diff,
qty_to_cost,
cost_to_qty,
calc_min_entry_qty,
round_,
round_up,
round_dn,
round_dynamic,
calc_pnl,
calc_pnl_long,
calc_pnl_short,
calc_pprice_diff,
)
from njit_multisymbol import calc_AU_allowance
from pure_funcs import (
numpyize,
denumpyize,
filter_orders,
multi_replace,
shorten_custom_id,
determine_side_from_order_tuple,
str2bool,
symbol2coin,
add_missing_params_to_hjson_live_multi_config,
expand_PB_mode,
)
import logging
logging.basicConfig(
format="%(asctime)s %(levelname)-8s %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%dT%H:%M:%S",
)
class Passivbot:
def __init__(self, config: dict):
self.config = config
self.user = config["user"]
self.user_info = load_user_info(config["user"])
self.exchange = self.user_info["exchange"]
self.broker_code = load_broker_code(self.user_info["exchange"])
self.custom_id_max_length = 36
self.sym_padding = 17
self.stop_websocket = False
self.balance = 1e-12
self.upd_timestamps = {
"pnls": 0.0,
"open_orders": 0.0,
"positions": 0.0,
"tickers": 0.0,
}
self.hedge_mode = True
self.inverse = False
self.active_symbols = []
self.fetched_positions = []
self.fetched_open_orders = []
self.open_orders = {}
self.positions = {}
self.pnls = []
self.tickers = {}
self.symbol_ids = {}
self.min_costs = {}
self.min_qtys = {}
self.qty_steps = {}
self.price_steps = {}
self.c_mults = {}
self.max_leverage = {}
self.live_configs = {}
self.stop_bot = False
self.pnls_cache_filepath = make_get_filepath(f"caches/{self.exchange}/{self.user}_pnls.json")
self.ohlcvs_cache_dirpath = make_get_filepath(f"caches/{self.exchange}/ohlcvs/")
self.previous_execution_ts = 0
self.recent_fill = False
self.execution_delay_millis = max(3000.0, self.config["execution_delay_seconds"] * 1000)
self.force_update_age_millis = 60 * 1000 # force update once a minute
self.quote = "USDT"
self.forager_mode = self.config["n_longs"] > 0 or self.config["n_shorts"] > 0
self.config["minimum_market_age_millis"] = (
self.config["minimum_market_age_days"] * 24 * 60 * 60 * 1000
)
self.ohlcvs = {}
self.ohlcv_upd_timestamps = {}
self.emas = {"long": {}, "short": {}}
self.ema_alphas = {"long": {}, "short": {}}
self.upd_minute_emas = {}
self.ineligible_symbols_with_pos = set()
def set_live_configs(self):
# live configs priority:
# 1) -lc path from hjson multi config
# 2) live config from live configs dir, matching name or coin
# 3) live config from default config path
# 4) universal live config given in hjson multi config
if os.path.isdir(self.config["live_configs_dir"]):
# live config candidates from live configs dir
live_configs_fnames = sorted(
[f for f in os.listdir(self.config["live_configs_dir"]) if f.endswith(".json")]
)
else:
live_configs_fnames = []
configs_loaded = {
"lc_flag": set(),
"live_configs_dir_exact_match": set(),
"default_config_path": set(),
"universal_config": set(),
}
for symbol in self.markets_dict:
# try to load live config: 1) -lc flag live_config_path, 2) live_configs_dir, 3) default_config_path, 4) universal live config
try:
self.live_configs[symbol] = load_live_config(self.flags[symbol].live_config_path)
configs_loaded["lc_flag"].add(symbol)
continue
except:
pass
try:
# look for an exact match first
coin = symbol2coin(symbol)
for x in live_configs_fnames:
if coin == symbol2coin(x.replace(".json", "")):
self.live_configs[symbol] = load_live_config(
os.path.join(self.config["live_configs_dir"], x)
)
configs_loaded["live_configs_dir_exact_match"].add(symbol)
break
else:
raise Exception
continue
except:
pass
try:
self.live_configs[symbol] = load_live_config(self.config["default_config_path"])
configs_loaded["default_config_path"].add(symbol)
continue
except:
pass
try:
self.live_configs[symbol] = deepcopy(self.config["universal_live_config"])
configs_loaded["universal_config"].add(symbol)
continue
except Exception as e:
logging.error(f"failed to apply universal_live_config {e}")
raise Exception(f"no usable live config found for {symbol}")
for symbol in self.live_configs:
if symbol in self.flags and self.flags[symbol].leverage is not None:
self.live_configs[symbol]["leverage"] = max(1.0, float(self.flags[symbol].leverage))
else:
self.live_configs[symbol]["leverage"] = max(1.0, float(self.config["leverage"]))
for pside in ["long", "short"]:
# disable timed AU and set backwards TP
for key, val in [
("auto_unstuck_delay_minutes", 0.0),
("auto_unstuck_qty_pct", 0.0),
("auto_unstuck_wallet_exposure_threshold", 0.0),
("auto_unstuck_ema_dist", 0.0),
("backwards_tp", False), # @TEDY Patch set to False
("wallet_exposure_limit", 0.0),
]:
self.live_configs[symbol][pside][key] = val
for key in configs_loaded:
if isinstance(configs_loaded[key], dict):
for symbol in configs_loaded[key]:
logging.info(
f"loaded {key} for {self.pad_sym(symbol)}: {configs_loaded[key][symbol]}"
)
elif isinstance(configs_loaded[key], set):
coins_ = sorted([symbol2coin(s) for s in configs_loaded[key]])
if len(coins_) > 20:
logging.info(f"loaded from {key} for {len(coins_)} symbols")
elif len(coins_) > 0:
logging.info(f"loaded from {key} for {', '.join(coins_)}")
def pad_sym(self, symbol):
return f"{symbol: <{self.sym_padding}}"
def stop_maintainer_ohlcvs(self):
return self.maintainer_ohlcvs.cancel()
async def start_maintainer_ohlcvs(self):
if self.forager_mode:
self.maintainer_ohlcvs = asyncio.create_task(self.maintain_ohlcvs())
else:
self.maintainer_ohlcvs = None
async def start_maintainer_EMAs(self):
self.maintainer_EMAs = asyncio.create_task(self.maintain_EMAs())
def stop_data_maintainers(self):
res = []
try:
res.append(self.maintainer_ohlcvs.cancel())
except Exception as e:
logging.error(f"error stopping maintainer_ohlcvs {e}")
try:
res.append(self.maintainer_EMAs.cancel())
except Exception as e:
logging.error(f"error stopping maintainer_EMAs {e}")
return res
async def init_bot(self):
logging.info(f"setting hedge mode...")
await self.update_exchange_config()
logging.info(f"initiating markets...")
await self.init_markets_dict()
await self.init_flags()
logging.info(f"initiating tickers...")
await self.update_tickers()
logging.info(f"initiating balance, positions...")
await self.update_positions()
logging.info(f"initiating open orders...")
await self.update_open_orders()
self.set_live_configs()
if self.forager_mode:
await self.update_ohlcvs_multi(list(self.eligible_symbols), verbose=True)
self.update_PB_modes()
logging.info(f"initiating pnl history...")
await self.update_pnls()
await self.update_exchange_configs()
async def get_active_symbols(self):
# get symbols with open orders and/or positions
positions, balance = await self.fetch_positions()
open_orders = await self.fetch_open_orders()
return sorted(set([elm["symbol"] for elm in positions + open_orders]))
def format_symbol(self, symbol: str) -> str:
try:
return self.formatted_symbols_map[symbol]
except (KeyError, AttributeError):
pass
if not hasattr(self, "formatted_symbols_map"):
self.formatted_symbols_map = {}
self.formatted_symbols_map_inv = defaultdict(set)
formatted = f"{symbol2coin(symbol.replace(',', ''))}/{self.quote}:{self.quote}"
self.formatted_symbols_map[symbol] = formatted
self.formatted_symbols_map_inv[formatted].add(symbol)
return formatted
def symbol_is_eligible(self, symbol):
# defined for each child class
return True
async def init_markets_dict(self):
self.init_markets_last_update_ms = utc_ms()
self.markets_dict = {elm["symbol"]: elm for elm in (await self.cca.fetch_markets())}
self.markets_dict_all = deepcopy(self.markets_dict)
# remove ineligible symbols from markets dict
ineligible_symbols = {}
for symbol in list(self.markets_dict):
if not self.markets_dict[symbol]["active"]:
ineligible_symbols[symbol] = "not active"
del self.markets_dict[symbol]
elif not self.markets_dict[symbol]["swap"]:
ineligible_symbols[symbol] = "wrong market type"
del self.markets_dict[symbol]
elif not self.markets_dict[symbol]["linear"]:
ineligible_symbols[symbol] = "not linear"
del self.markets_dict[symbol]
elif not symbol.endswith(f"/{self.quote}:{self.quote}"):
ineligible_symbols[symbol] = "wrong quote"
del self.markets_dict[symbol]
elif not self.symbol_is_eligible(symbol):
ineligible_symbols[symbol] = f"not eligible on {self.exchange}"
del self.markets_dict[symbol]
for line in set(ineligible_symbols.values()):
syms_ = [s for s in ineligible_symbols if ineligible_symbols[s] == line]
if len(syms_) > 12:
logging.info(f"{line}: {len(syms_)} symbols")
elif len(syms_) > 0:
logging.info(f"{line}: {','.join(sorted(set([s for s in syms_])))}")
for symbol in self.ineligible_symbols_with_pos:
if symbol not in self.markets_dict and symbol in self.markets_dict_all:
logging.info(f"There is a position in an ineligible market: {symbol}.")
self.markets_dict[symbol] = self.markets_dict_all[symbol]
self.config["ignored_symbols"].append(symbol)
self.set_market_specific_settings()
for symbol in self.markets_dict:
self.format_symbol(symbol)
# for prettier printing
self.max_len_symbol = max([len(s) for s in self.markets_dict])
self.sym_padding = max(self.sym_padding, self.max_len_symbol + 1)
def set_market_specific_settings(self):
# set min cost, min qty, price step, qty step, c_mult
# defined individually for each exchange
self.symbol_ids = {symbol: self.markets_dict[symbol]["id"] for symbol in self.markets_dict}
self.symbol_ids_inv = {v: k for k, v in self.symbol_ids.items()}
def set_wallet_exposure_limits(self):
for pside in ["long", "short"]:
changed = {}
n_actives = len(self.is_active[pside])
WE_limit_div = round_(
self.config[f"TWE_{pside}"] / n_actives if n_actives > 0 else 0.001, 0.0001
)
for symbol in self.is_active[pside]:
new_WE_limit = (
getattr(self.flags[symbol], f"WE_limit_{pside}")
if symbol in self.flags
and getattr(self.flags[symbol], f"WE_limit_{pside}") is not None
else WE_limit_div
)
if "wallet_exposure_limit" not in self.live_configs[symbol][pside]:
changed[symbol] = (0.0, new_WE_limit)
elif self.live_configs[symbol][pside]["wallet_exposure_limit"] != new_WE_limit:
changed[symbol] = (
self.live_configs[symbol][pside]["wallet_exposure_limit"],
new_WE_limit,
)
self.live_configs[symbol][pside]["wallet_exposure_limit"] = new_WE_limit
if changed:
inv = defaultdict(set)
for symbol in changed:
inv[changed[symbol]].add(symbol)
for k, v in inv.items():
syms = ", ".join(sorted([symbol2coin(s) for s in v]))
logging.info(f"changed {pside} WE limit from {k[0]} to {k[1]} for {syms}")
async def update_exchange_configs(self):
if not hasattr(self, "already_updated_exchange_config_symbols"):
self.already_updated_exchange_config_symbols = set()
symbols_not_done = [
x for x in self.active_symbols if x not in self.already_updated_exchange_config_symbols
]
if symbols_not_done:
await self.update_exchange_config_by_symbols(symbols_not_done)
self.already_updated_exchange_config_symbols.update(symbols_not_done)
async def update_exchange_config_by_symbols(self, symbols):
# defined by each exchange child class
pass
async def update_exchange_config(self):
# defined by each exchange child class
pass
def reformat_symbol(self, symbol: str, verbose=False) -> str:
# tries to reformat symbol to correct variant for exchange
# (e.g. BONK -> 1000BONK/USDT:USDT, PEPE - kPEPE/USDC:USDC)
# if no reformatting is possible, return empty string
fsymbol = self.format_symbol(symbol)
if fsymbol in self.markets_dict:
return fsymbol
else:
if verbose:
logging.info(f"{symbol} missing from {self.exchange}")
if fsymbol in self.formatted_symbols_map_inv:
for x in self.formatted_symbols_map_inv[fsymbol]:
if x in self.markets_dict:
if verbose:
logging.info(f"changing {symbol} -> {x}")
return x
return ""
async def init_flags(self):
self.ignored_symbols = {self.reformat_symbol(x) for x in self.config["ignored_symbols"]}
self.flags = {}
self.eligible_symbols = set() # symbols which may be approved for trading
for symbol in self.config["approved_symbols"]:
reformatted_symbol = self.reformat_symbol(symbol, verbose=True)
if reformatted_symbol:
self.flags[reformatted_symbol] = (
self.config["approved_symbols"][symbol]
if isinstance(self.config["approved_symbols"], dict)
else ""
)
self.eligible_symbols.add(reformatted_symbol)
if not self.config["approved_symbols"]:
self.eligible_symbols = set(self.markets_dict)
# this argparser is used only internally
parser = argparse.ArgumentParser(prog="passivbot", description="run passivbot")
parser.add_argument(
"-sm", type=expand_PB_mode, required=False, dest="short_mode", default=None
)
parser.add_argument(
"-lm", type=expand_PB_mode, required=False, dest="long_mode", default=None
)
parser.add_argument("-lw", type=float, required=False, dest="WE_limit_long", default=None)
parser.add_argument("-sw", type=float, required=False, dest="WE_limit_short", default=None)
parser.add_argument("-lev", type=float, required=False, dest="leverage", default=None)
parser.add_argument("-lc", type=str, required=False, dest="live_config_path", default=None)
self.forced_modes = {"long": {}, "short": {}}
for symbol in self.markets_dict:
self.flags[symbol] = parser.parse_args(
self.flags[symbol].split() if symbol in self.flags else []
)
for pside in ["long", "short"]:
if (mode := getattr(self.flags[symbol], f"{pside}_mode")) is None:
if symbol in self.ignored_symbols:
setattr(
self.flags[symbol],
f"{pside}_mode",
"graceful_stop" if self.config["auto_gs"] else "manual",
)
self.forced_modes[pside][symbol] = getattr(
self.flags[symbol], f"{pside}_mode"
)
elif self.config[f"forced_mode_{pside}"]:
try:
setattr(
self.flags[symbol],
f"{pside}_mode",
expand_PB_mode(self.config[f"forced_mode_{pside}"]),
)
self.forced_modes[pside][symbol] = getattr(
self.flags[symbol], f"{pside}_mode"
)
except Exception as e:
logging.error(
f"failed to set PB mode {self.config[f'forced_mode_{pside}']} {e}"
)
else:
self.forced_modes[pside][symbol] = mode
if not self.markets_dict[symbol]["active"]:
self.forced_modes[pside][symbol] = "tp_only"
if self.forager_mode and self.config["minimum_market_age_days"] > 0:
if not hasattr(self, "first_timestamps"):
self.first_timestamps = await get_first_ohlcv_timestamps(cc=self.cca)
for symbol in sorted(self.first_timestamps):
self.first_timestamps[self.format_symbol(symbol)] = self.first_timestamps[symbol]
else:
self.first_timestamps = None
def is_old_enough(self, symbol):
if self.forager_mode and self.config["minimum_market_age_days"] > 0:
if symbol in self.first_timestamps:
# res = utc_ms() - self.first_timestamps[symbol] > self.config["minimum_market_age_millis"]
# logging.info(f"{symbol} {res}")
return (
utc_ms() - self.first_timestamps[symbol]
> self.config["minimum_market_age_millis"]
)
else:
return False
else:
return True
def update_PB_modes(self):
# update passivbot modes for all symbols
if hasattr(self, "PB_modes"):
previous_PB_modes = deepcopy(self.PB_modes)
else:
previous_PB_modes = None
# set modes for all symbols
self.PB_modes = {
"long": {},
"short": {},
} # options: normal, graceful_stop, manual, tp_only, panic
self.actual_actives = {"long": set(), "short": set()} # symbols with position
self.is_active = {"long": set(), "short": set()} # actual actives plus symbols on "normal""
self.ideal_actives = {"long": {}, "short": {}} # dicts as ordered sets
# actual actives, symbols with pos and/or open orders
for elm in self.fetched_positions + self.fetched_open_orders:
self.actual_actives[elm["position_side"]].add(elm["symbol"])
# find ideal actives
# set forced modes first
for pside in self.forced_modes:
for symbol in self.forced_modes[pside]:
if self.forced_modes[pside][symbol] == "normal":
self.PB_modes[pside][symbol] = self.forced_modes[pside][symbol]
self.ideal_actives[pside][symbol] = ""
if symbol in self.actual_actives[pside]:
self.PB_modes[pside][symbol] = self.forced_modes[pside][symbol]
if self.forager_mode:
if self.config["relative_volume_filter_clip_pct"] > 0.0:
self.calc_volumes()
# filter by relative volume
eligible_symbols = sorted(self.volumes, key=lambda x: self.volumes[x])[
int(round(len(self.volumes) * self.config["relative_volume_filter_clip_pct"])) :
]
else:
eligible_symbols = list(self.eligible_symbols)
self.calc_noisiness() # ideal symbols are high noise symbols
# calc ideal actives for long and short separately
for pside in self.actual_actives:
if self.config[f"n_{pside}s"] > 0:
self.warn_on_high_effective_min_cost(pside)
for symbol in sorted(eligible_symbols, key=lambda x: self.noisiness[x], reverse=True):
if (
symbol not in self.eligible_symbols
or not self.is_old_enough(symbol)
or not self.effective_min_cost_is_low_enough(pside, symbol)
):
continue
slots_full = len(self.ideal_actives[pside]) >= self.config[f"n_{pside}s"]
if slots_full:
break
if symbol not in self.ideal_actives[pside]:
self.ideal_actives[pside][symbol] = ""
# actual actives fill slots first
for symbol in self.actual_actives[pside]:
if symbol in self.forced_modes[pside]:
continue # is a forced mode
if symbol in self.ideal_actives[pside]:
self.PB_modes[pside][symbol] = "normal"
else:
self.PB_modes[pside][symbol] = (
"graceful_stop" if self.config["auto_gs"] else "manual"
)
# fill remaining slots with ideal actives
# a slot is filled if symbol in [normal, graceful_stop]
# symbols on other modes are ignored
for symbol in self.ideal_actives[pside]:
if symbol in self.PB_modes[pside] or symbol in self.forced_modes[pside]:
continue
slots_filled = {
k for k, v in self.PB_modes[pside].items() if v in ["normal", "graceful_stop"]
}
if len(slots_filled) >= self.config[f"n_{pside}s"]:
break
self.PB_modes[pside][symbol] = "normal"
else:
# if not forager mode, all eligible symbols are ideal symbols, unless symbol in forced_modes
for pside in ["long", "short"]:
if self.config[f"{pside}_enabled"]:
self.warn_on_high_effective_min_cost(pside)
for symbol in self.eligible_symbols:
if not self.effective_min_cost_is_low_enough(pside, symbol):
continue
if symbol not in self.forced_modes[pside]:
self.PB_modes[pside][symbol] = "normal"
self.ideal_actives[pside][symbol] = ""
for symbol in self.actual_actives[pside]:
if symbol not in self.PB_modes[pside]:
self.PB_modes[pside][symbol] = (
"graceful_stop" if self.config["auto_gs"] else "manual"
)
self.active_symbols = sorted(
{s for subdict in self.PB_modes.values() for s in subdict.keys()}
)
self.is_active = deepcopy(self.actual_actives)
for pside in self.PB_modes:
for symbol in self.PB_modes[pside]:
if self.PB_modes[pside][symbol] == "normal":
self.is_active[pside].add(symbol)
for symbol in self.active_symbols:
for pside in self.PB_modes:
if symbol in self.PB_modes[pside]:
self.live_configs[symbol][pside]["mode"] = self.PB_modes[pside][symbol]
self.live_configs[symbol][pside]["enabled"] = (
self.PB_modes[pside][symbol] == "normal"
)
else:
if self.config["auto_gs"]:
self.live_configs[symbol][pside]["mode"] = "graceful_stop"
self.PB_modes[pside][symbol] = "graceful_stop"
else:
self.live_configs[symbol][pside]["mode"] = "manual"
self.PB_modes[pside][symbol] = "manual"
self.live_configs[symbol][pside]["enabled"] = False
if symbol not in self.positions:
self.positions[symbol] = {
"long": {"size": 0.0, "price": 0.0},
"short": {"size": 0.0, "price": 0.0},
}
if symbol not in self.open_orders:
self.open_orders[symbol] = []
self.set_wallet_exposure_limits()
# log changes
for pside in self.PB_modes:
if previous_PB_modes is None:
for mode in set(self.PB_modes[pside].values()):
coins = [
symbol2coin(s)
for s in self.PB_modes[pside]
if self.PB_modes[pside][s] == mode
]
logging.info(f" setting {pside: <5} {mode}: {','.join(coins)}")
else:
if previous_PB_modes[pside] != self.PB_modes[pside]:
for symbol in self.active_symbols:
if symbol in self.PB_modes[pside]:
if symbol in previous_PB_modes[pside]:
if self.PB_modes[pside][symbol] != previous_PB_modes[pside][symbol]:
logging.info(
f"changing {pside: <5} {self.pad_sym(symbol)}: {previous_PB_modes[pside][symbol]} -> {self.PB_modes[pside][symbol]}"
)
else:
logging.info(
f" setting {pside: <5} {self.pad_sym(symbol)}: {self.PB_modes[pside][symbol]}"
)
else:
if symbol in previous_PB_modes[pside]:
logging.info(
f"removing {pside: <5} {self.pad_sym(symbol)}: {previous_PB_modes[pside][symbol]}"
)
def warn_on_high_effective_min_cost(self, pside):
if not self.config["filter_by_min_effective_cost"]:
return
eligible_symbols_filtered = [
x for x in self.eligible_symbols if self.effective_min_cost_is_low_enough(pside, x)
]
if len(eligible_symbols_filtered) == 0:
logging.info(
f"Warning: No {pside} symbols are approved due to min effective cost too high. "
+ f"Suggestions: 1) increase account balance, 2) "
+ f"set 'filter_by_min_effective_cost' to false, 3) if in forager mode, reduce n_{pside}s"
)
def effective_min_cost_is_low_enough(self, pside, symbol):
if not self.config["filter_by_min_effective_cost"]:
return True
try:
WE_limit = self.live_configs[symbol][pside]["wallet_exposure_limit"]
assert WE_limit > 0.0
except:
if self.forager_mode:
WE_limit = (
self.config[f"TWE_{pside}"] / self.config[f"n_{pside}s"]
if self.config[f"n_{pside}s"] > 0
else 0.0
)
else:
WE_limit = (
self.config[f"TWE_{pside}"] / len(self.config["approved_symbols"])
if len(self.config["approved_symbols"]) > 0
else 0.0
)
return (
self.balance * WE_limit * self.live_configs[symbol][pside]["initial_qty_pct"]
>= self.tickers[symbol]["effective_min_cost"]
)
def add_new_order(self, order, source="WS"):
try:
if not order or "id" not in order:
return False
if "symbol" not in order or order["symbol"] is None:
logging.info(f"{order}")
return False
if order["symbol"] not in self.open_orders:
self.open_orders[order["symbol"]] = []
if order["id"] not in {x["id"] for x in self.open_orders[order["symbol"]]}:
self.open_orders[order["symbol"]].append(order)
logging.info(
f" created {self.pad_sym(order['symbol'])} {order['side']} {order['qty']} {order['position_side']} @ {order['price']} source: {source}"
)
return True
except Exception as e:
logging.error(f"failed to add order to self.open_orders {order} {e}")
traceback.print_exc()
return False
def remove_cancelled_order(self, order: dict, source="WS"):
try:
if not order or "id" not in order:
return False
if "symbol" not in order or order["symbol"] is None:
logging.info(f"{order}")
return False
if order["symbol"] not in self.open_orders:
self.open_orders[order["symbol"]] = []
if order["id"] in {x["id"] for x in self.open_orders[order["symbol"]]}:
self.open_orders[order["symbol"]] = [
x for x in self.open_orders[order["symbol"]] if x["id"] != order["id"]
]
logging.info(
f"cancelled {self.pad_sym(order['symbol'])} {order['side']} {order['qty']} {order['position_side']} @ {order['price']} source: {source}"
)
return True
except Exception as e:
logging.error(f"failed to remove order from self.open_orders {order} {e}")
traceback.print_exc()
return False
def handle_order_update(self, upd_list):
try:
for upd in upd_list:
if upd["status"] == "closed" or (
"filled" in upd and upd["filled"] is not None and upd["filled"] > 0.0
):
# There was a fill, partial or full. Schedule update of open orders, pnls, position.
logging.info(
f" filled {self.pad_sym(upd['symbol'])} {upd['side']} {upd['qty']} {upd['position_side']} @ {upd['price']} source: WS"
)
self.recent_fill = True
elif upd["status"] in ["canceled", "expired", "rejected"]:
# remove order from open_orders
self.remove_cancelled_order(upd)
elif upd["status"] == "open":
# add order to open_orders
self.add_new_order(upd)
else:
print("debug open orders unknown type", upd)
except Exception as e:
logging.error(f"error updating open orders from websocket {upd_list} {e}")
traceback.print_exc()
def handle_balance_update(self, upd, source="WS"):
try:
upd[self.quote]["total"] = round_dynamic(upd[self.quote]["total"], 10)
equity = upd[self.quote]["total"] + self.calc_upnl_sum()
if self.balance != upd[self.quote]["total"]:
logging.info(
f"balance changed: {self.balance} -> {upd[self.quote]['total']} equity: {equity:.4f} source: {source}"
)
self.balance = max(upd[self.quote]["total"], 1e-12)
except Exception as e:
logging.error(f"error updating balance from websocket {upd} {e}")
traceback.print_exc()
def handle_ticker_update(self, upd):
if isinstance(upd, list):
for x in upd:
self.handle_ticker_update(x)
elif isinstance(upd, dict):
if len(upd) == 1:
# sometimes format is {symbol: {ticker}}
upd = upd[next(iter(upd))]
if "bid" not in upd and "bids" in upd and "ask" not in upd and "asks" in upd:
# order book, not ticker
upd["bid"], upd["ask"] = upd["bids"][0][0], upd["asks"][0][0]
if all([key in upd for key in ["bid", "ask", "symbol"]]):
if "last" not in upd or upd["last"] is None:
upd["last"] = np.mean([upd["bid"], upd["ask"]])
for key in ["bid", "ask", "last"]:
if upd[key] is not None:
if upd[key] != self.tickers[upd["symbol"]][key]:
self.tickers[upd["symbol"]][key] = upd[key]
else:
logging.info(f"ticker {upd['symbol']} {key} is None")
# if upd['bid'] is not None:
# if upd['ask'] is not None:
# if upd['last'] is not None:
# self.tickers[upd['symbol']] = {k: upd[k] for k in ["bid", "ask", "last"]}
# return
# self.tickers[upd['symbol']] = {'bid': upd['bid'], 'ask': upd['ask'], 'last': np.random.choice([upd['bid'], upd['ask']])}
# return
# self.tickers[upd['symbol']] = {'bid': upd['bid'], 'ask': upd['bid'], 'last': upd['bid']}
# return
else:
logging.info(f"unexpected WS ticker formatting: {upd}")
def calc_upnl_sum(self):
try:
upnl_sum = 0.0
for elm in self.fetched_positions:
upnl_sum += calc_pnl(
elm["position_side"],
elm["price"],
self.tickers[elm["symbol"]]["last"],
elm["size"],
self.inverse,
self.c_mults[elm["symbol"]],
)
return upnl_sum
except Exception as e:
logging.error(f"error calculating upnl sum {e}")
traceback.print_exc()
return 0.0
async def update_pnls(self):
# fetch latest pnls
# dump new pnls to cache
age_limit = utc_ms() - 1000 * 60 * 60 * 24 * self.config["pnls_max_lookback_days"]
missing_pnls = []
if len(self.pnls) == 0:
# load pnls from cache
pnls_cache = []
try:
if os.path.exists(self.pnls_cache_filepath):
pnls_cache = json.load(open(self.pnls_cache_filepath))
except Exception as e:
logging.error(f"error loading {self.pnls_cache_filepath} {e}")
# fetch pnls since latest timestamp
if len(pnls_cache) > 0:
if pnls_cache[0]["timestamp"] > age_limit + 1000 * 60 * 60 * 4:
# fetch missing pnls
res = await self.fetch_pnls(
start_time=age_limit - 1000, end_time=pnls_cache[0]["timestamp"]
)
if res in [None, False]:
return False
missing_pnls = res
pnls_cache = sorted(
{
elm["id"]: elm
for elm in pnls_cache + missing_pnls
if elm["timestamp"] >= age_limit
}.values(),
key=lambda x: x["timestamp"],
)
self.pnls = pnls_cache
start_time = self.pnls[-1]["timestamp"] if self.pnls else age_limit
res = await self.fetch_pnls(start_time=start_time)
if res in [None, False]:
return False
new_pnls = [x for x in res if x["id"] not in {elm["id"] for elm in self.pnls}]
self.pnls = sorted(
{elm["id"]: elm for elm in self.pnls + new_pnls if elm["timestamp"] > age_limit}.values(),
key=lambda x: x["timestamp"],
)
if new_pnls:
new_income = sum([x["pnl"] for x in new_pnls])
if new_income != 0.0:
logging.info(
f"{len(new_pnls)} new pnl{'s' if len(new_pnls) > 1 else ''} {new_income} {self.quote}"
)
try:
json.dump(self.pnls, open(self.pnls_cache_filepath, "w"))
except Exception as e:
logging.error(f"error dumping pnls to {self.pnls_cache_filepath} {e}")
self.upd_timestamps["pnls"] = utc_ms()
return True
async def check_for_inactive_markets(self):
self.ineligible_symbols_with_pos = [
elm["symbol"]
for elm in self.fetched_positions + self.fetched_open_orders
if elm["symbol"] not in self.markets_dict
or not self.markets_dict[elm["symbol"]]["active"]
]
update = False
if self.ineligible_symbols_with_pos:
logging.info(
f"Caught symbol with pos for ineligible market: {self.ineligible_symbols_with_pos}"
)
update = True
if utc_ms() - self.init_markets_last_update_ms > (1000 * 60 * 60 * 3):
logging.info(f"Force updating markets every three hours.")
update = True
if update:
await self.init_markets_dict()
await self.init_flags()
self.set_live_configs()
self.update_PB_modes()
async def update_open_orders(self):
if not hasattr(self, "open_orders"):
self.open_orders = {}
res = await self.fetch_open_orders()
if res in [None, False]:
return False
self.fetched_open_orders = res
await self.check_for_inactive_markets()
open_orders = res
oo_ids_old = {elm["id"] for sublist in self.open_orders.values() for elm in sublist}
created_prints, cancelled_prints = [], []
for oo in open_orders:
if oo["id"] not in oo_ids_old:
# there was a new open order not caught by websocket
created_prints.append(
f"new order {self.pad_sym(oo['symbol'])} {oo['side']} {oo['qty']} {oo['position_side']} @ {oo['price']} source: REST"
)
oo_ids_new = {elm["id"] for elm in open_orders}
for oo in [elm for sublist in self.open_orders.values() for elm in sublist]:
if oo["id"] not in oo_ids_new:
# there was an order cancellation not caught by websocket
cancelled_prints.append(
f"cancelled {self.pad_sym(oo['symbol'])} {oo['side']} {oo['qty']} {oo['position_side']} @ {oo['price']} source: REST"
)
self.open_orders = {}
for elm in open_orders:
if elm["symbol"] not in self.open_orders:
self.open_orders[elm["symbol"]] = []
self.open_orders[elm["symbol"]].append(elm)
if len(created_prints) > 12:
logging.info(f"{len(created_prints)} new open orders")
else:
for line in created_prints:
logging.info(line)
if len(cancelled_prints) > 12:
logging.info(f"{len(created_prints)} cancelled open orders")
else:
for line in cancelled_prints:
logging.info(line)
self.upd_timestamps["open_orders"] = utc_ms()
return True
async def update_positions(self):
# also updates balance
if not hasattr(self, "positions"):
self.positions = {}
res = await self.fetch_positions()
if all(x in [None, False] for x in res):
return False
positions_list_new, balance_new = res
self.fetched_positions = positions_list_new
await self.check_for_inactive_markets()
self.handle_balance_update({self.quote: {"total": balance_new}})
positions_new = {
sym: {
"long": {"size": 0.0, "price": 0.0},
"short": {"size": 0.0, "price": 0.0},
}
for sym in set(list(self.positions) + list(self.active_symbols))
}
position_changes = []
for elm in positions_list_new:
symbol, pside, pprice = elm["symbol"], elm["position_side"], elm["price"]
psize = abs(elm["size"]) * (-1.0 if elm["position_side"] == "short" else 1.0)
if symbol not in positions_new:
positions_new[symbol] = {
"long": {"size": 0.0, "price": 0.0},
"short": {"size": 0.0, "price": 0.0},
}
positions_new[symbol][pside] = {"size": psize, "price": pprice}
# check if changed
if symbol not in self.positions or self.positions[symbol][pside]["size"] != psize:
position_changes.append((symbol, pside))
try:
self.log_position_changes(position_changes, positions_new)
except Exception as e:
logging.error(f"error printing position changes {e}")
self.positions = positions_new
self.upd_timestamps["positions"] = utc_ms()
return True
def log_position_changes(self, position_changes, positions_new, rd=6) -> str:
if not position_changes:
return ""
table = PrettyTable()
table.border = False
table.header = False
table.padding_width = 0 # Reduces padding between columns to zero
for symbol, pside in position_changes:
wallet_exposure = (
qty_to_cost(
positions_new[symbol][pside]["size"],
positions_new[symbol][pside]["price"],
self.inverse,
self.c_mults[symbol],
)
/ self.balance
)
try:
WE_ratio = wallet_exposure / self.live_configs[symbol][pside]["wallet_exposure_limit"]
except:
WE_ratio = 0.0
try:
pprice_diff = calc_pprice_diff(
pside, positions_new[symbol][pside]["price"], self.tickers[symbol]["last"]
)
except:
pprice_diff = 0.0
try:
upnl = calc_pnl(
pside,
positions_new[symbol][pside]["price"],
self.tickers[symbol]["last"],
positions_new[symbol][pside]["size"],
self.inverse,
self.c_mults[symbol],
)
except Exception as e:
upnl = 0.0
table.add_row(
[