forked from donewiththedollar/directionalscalper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_bot_aio.py
1436 lines (1158 loc) · 72.5 KB
/
multi_bot_aio.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 sys
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import Future
import threading
from threading import Thread
import random
import colorama
# from colorama import Fore, Style
from colorama import Fore, Back, Style, init
from pathlib import Path
project_dir = str(Path(__file__).resolve().parent)
print("Project directory:", project_dir)
sys.path.insert(0, project_dir)
import traceback
import inquirer
from rich.live import Live
import argparse
from pathlib import Path
from config import load_config, Config, VERSION
from api.manager import Manager
from directionalscalper.core.exchanges import *
import directionalscalper.core.strategies.bybit.gridbased as gridbased
import directionalscalper.core.strategies.bybit.hedging as bybit_hedging
from directionalscalper.core.strategies.binance import *
from directionalscalper.core.strategies.huobi import *
from live_table_manager import LiveTableManager, shared_symbols_data
from directionalscalper.core.strategies.logger import Logger
from rate_limit import RateLimit
from collections import deque
general_rate_limiter = RateLimit(50, 1)
order_rate_limiter = RateLimit(5, 1)
thread_management_lock = threading.Lock()
thread_to_symbol = {}
thread_to_symbol_lock = threading.Lock()
active_symbols = set()
active_threads = []
long_threads = {}
short_threads = {}
active_long_symbols = set()
active_short_symbols = set()
unique_active_symbols = set()
threads = {} # Threads for each symbol
thread_start_time = {} # Dictionary to track the start time for each symbol's thread
symbol_last_started_time = {}
extra_symbols = set() # To track symbols opened past the limit
under_review_symbols = set()
latest_rotator_symbols = set()
last_rotator_update_time = time.time()
tried_symbols = set()
rotator_symbols_cache = {
'timestamp': 0,
'symbols': set()
}
CACHE_DURATION = 50 # Cache duration in seconds
logging = Logger(logger_name="MultiBot", filename="MultiBot.log", stream=True)
colorama.init()
def print_cool_trading_info(symbol, exchange_name, strategy_name, account_name):
ascii_art = r"""
____ _ _ _ _ ____ _
| _ \(_)_ __ ___ ___| |_(_) ___ _ __ __ _| |/ ___| ___ __ _| |_ __ ___ _ __
| | | | | '__/ _ \/ __| __| |/ _ \| '_ \ / _` | |\___ \ / __/ _` | | '_ \ / _ \ '__|
| |_| | | | | __/ (__| |_| | (_) | | | | (_| | | ___) | (_| (_| | | |_) | __/ |
|____/|_|_| \___|\___|___|_|\___/|_| |_|\__,_|_||____/ \___\__,_|_| .__/ \___|_|
|_|
╔═══════════════════════════════════════════════════════════════════════════╗
║ Created by Tyler Simpson and contributors at QVL ║
╚═══════════════════════════════════════════════════════════════════════════╝
"""
print(Fore.CYAN + ascii_art)
print(Style.BRIGHT + Fore.YELLOW + "DirectionalScalper is trading..")
print(Fore.GREEN + f"Trading symbol: {symbol}")
print(Fore.MAGENTA + f"Exchange name: {exchange_name}")
print(Fore.BLUE + f"Strategy name: {strategy_name}")
print(Fore.RED + f"Account name: {account_name}")
print(Style.RESET_ALL)
def standardize_symbol(symbol):
return symbol.replace('/', '').split(':')[0]
def get_available_strategies():
return [
'qsgridob'
# 'qsgridob',
# 'qsgridoblsignal',
# 'qstrendobdynamictp',
# 'qsgridinstantsignal',
# 'qsgridobtight',
# 'qsgriddynamicstatic',
# 'qsgridobdca',
# 'qsgriddynmaicgridspaninstant',
# 'qsdynamicgridspan',
# 'qsgriddynamictplinspaced',
# 'dynamicgridob',
# 'dynamicgridobsratrp',
# 'qsgriddynamictp',
# 'qsgriddynamic',
# 'qsgridbasic',
# 'basicgridpersist',
# 'qstrend',
# 'qstrendob',
# 'qstrenderi',
# 'qstrendemas',
# 'qstrend',
# 'qsematrend',
# 'qstrendemas',
# 'mfieritrend',
# 'qstrendlongonly',
# 'qstrendshortonly',
# 'qstrend_unified',
# 'qstrendspot',
]
def choose_strategy():
questions = [
inquirer.List('strategy',
message='Which strategy would you like to run?',
choices=get_available_strategies())
]
answers = inquirer.prompt(questions)
return answers['strategy']
def get_available_exchanges():
return ['bybit', 'hyperliquid']
def ask_for_missing_arguments(args):
questions = []
if not args.exchange:
questions.append(inquirer.List('exchange', message="Which exchange do you want to use?", choices=get_available_exchanges()))
if not args.strategy:
questions.append(inquirer.List('strategy', message="Which strategy do you want to use?", choices=get_available_strategies()))
if not args.account_name:
questions.append(inquirer.Text('account_name', message="Please enter the name of the account:"))
if questions:
answers = inquirer.prompt(questions)
args.exchange = args.exchange or answers.get('exchange')
args.strategy = args.strategy or answers.get('strategy')
args.account_name = args.account_name or answers.get('account_name')
return args
class DirectionalMarketMaker:
def __init__(self, config: Config, exchange_name: str, account_name: str):
self.config = config
self.exchange_name = exchange_name
self.account_name = account_name
self.entry_signal_type = config.bot.linear_grid.get('entry_signal_type', 'lorentzian') # Default to mfirsi_signal
exchange_config = next((exch for exch in config.exchanges if exch.name == exchange_name and exch.account_name == account_name), None)
if not exchange_config:
raise ValueError(f"Exchange {exchange_name} with account {account_name} not found in the configuration file.")
api_key = exchange_config.api_key
secret_key = exchange_config.api_secret
passphrase = getattr(exchange_config, 'passphrase', None) # Use getattr to get passphrase if it exists
exchange_classes = {
'bybit': BybitExchange,
'bybit_spot': BybitExchange,
'hyperliquid': HyperLiquidExchange,
'huobi': HuobiExchange,
'bitget': BitgetExchange,
'binance': BinanceExchange,
'mexc': MexcExchange,
'lbank': LBankExchange,
'blofin': BlofinExchange
}
exchange_class = exchange_classes.get(exchange_name.lower(), Exchange)
# Initialize the exchange based on whether a passphrase is required
if exchange_name.lower() in ['bybit', 'binance']: # Add other exchanges here that do not require a passphrase
self.exchange = exchange_class(api_key, secret_key, collateral_currency=exchange_config.collateral_currency)
elif exchange_name.lower() == 'bybit_spot':
self.exchange = exchange_class(api_key, secret_key, 'spot')
else:
self.exchange = exchange_class(api_key, secret_key, passphrase)
def run_strategy(self, symbol, strategy_name, config, account_name, symbols_to_trade=None, rotator_symbols_standardized=None, mfirsi_signal=None, action=None):
logging.info(f"Received rotator symbols in run_strategy for {symbol}: {rotator_symbols_standardized}")
symbols_allowed = next((exch.symbols_allowed for exch in config.exchanges if exch.name == self.exchange_name and exch.account_name == account_name), None)
logging.info(f"Matched exchange: {self.exchange_name}, account: {account_name}. Symbols allowed: {symbols_allowed}")
if symbols_to_trade:
logging.info(f"Calling run method with symbols: {symbols_to_trade}")
try:
print_cool_trading_info(symbol, self.exchange_name, strategy_name, account_name)
logging.info(f"Printed trading info for {symbol}")
except Exception as e:
logging.error(f"Error in printing info: {e}")
strategy_classes = {
'qstrendobdynamictp': gridbased.BybitQuickScalpTrendDynamicTP,
'qsgridob': gridbased.LinearGridBaseFutures
}
strategy_class = strategy_classes.get(strategy_name.lower())
if strategy_class:
strategy = strategy_class(self.exchange, self.manager, config.bot, symbols_allowed)
try:
logging.info(f"Running strategy for symbol {symbol} with action {action}")
if action == "long":
future_long = Future()
Thread(target=self.run_with_future, args=(strategy, symbol, rotator_symbols_standardized, mfirsi_signal, "long", future_long)).start()
return future_long
elif action == "short":
future_short = Future()
Thread(target=self.run_with_future, args=(strategy, symbol, rotator_symbols_standardized, mfirsi_signal, "short", future_short)).start()
return future_short
else:
future = Future()
future.set_result(True)
return future
except Exception as e:
future = Future()
future.set_exception(e)
return future
else:
logging.error(f"Strategy {strategy_name} not found.")
future = Future()
future.set_exception(ValueError(f"Strategy {strategy_name} not found."))
return future
def run_with_future(self, strategy, symbol, rotator_symbols_standardized, mfirsi_signal, action, future):
try:
strategy.run(symbol, rotator_symbols_standardized=rotator_symbols_standardized, mfirsi_signal=mfirsi_signal, action=action)
future.set_result(True)
except Exception as e:
future.set_exception(e)
def get_balance(self, quote, market_type=None, sub_type=None):
if self.exchange_name == 'bitget':
return self.exchange.get_balance_bitget(quote)
elif self.exchange_name == 'bybit':
#self.exchange.retry_api_call(self.exchange.get_balance_bybit, quote)
# return self.exchange.retry_api_call(self.exchange.get_balance_bybit(quote))
return self.exchange.get_balance_bybit(quote)
elif self.exchange_name == 'bybit_unified':
return self.exchange.retry_api_call(self.exchange.get_balance_bybit(quote))
elif self.exchange_name == 'mexc':
return self.exchange.get_balance_mexc(quote, market_type='swap')
elif self.exchange_name == 'huobi':
print("Huobi starting..")
elif self.exchange_name == 'okx':
print(f"Unsupported for now")
elif self.exchange_name == 'binance':
return self.exchange.get_balance_binance(quote)
elif self.exchange_name == 'phemex':
print(f"Unsupported for now")
def create_order(self, symbol, order_type, side, amount, price=None):
return self.exchange.create_order(symbol, order_type, side, amount, price)
def get_symbols(self):
with general_rate_limiter:
return self.exchange._get_symbols()
def format_symbol_bybit(self, symbol):
return f"{symbol[:3]}/{symbol[3:]}:USDT"
def is_valid_symbol_bybit(self, symbol):
valid_symbols = self.get_symbols()
# Check for SYMBOL/USDT:USDT format
if f"{symbol[:3]}/{symbol[3:]}:USDT" in valid_symbols:
return True
# Check for SYMBOL/USD:SYMBOL format
if f"{symbol[:3]}/USD:{symbol[:3]}" in valid_symbols:
return True
# Check for SYMBOL/USDC:USDC format
if f"{symbol}/USDC:USDC" in valid_symbols:
return True
# Check for SYMBOL/USDC:USDC-YYMMDD format
for valid_symbol in valid_symbols:
if valid_symbol.startswith(f"{symbol}/USDC:USDC-"):
return True
# Check for SYMBOL/USDC:USDC-YYMMDD-STRIKE-C/P format
for valid_symbol in valid_symbols:
if valid_symbol.startswith(f"{symbol}/USDC:USDC-") and valid_symbol.endswith(("-C", "-P")):
return True
logging.info(f"Invalid symbol type for some reason according to bybit but is probably valid symbol: {symbol}")
return True
def fetch_open_orders(self, symbol):
with general_rate_limiter:
return self.exchange.retry_api_call(self.exchange.get_open_orders, symbol)
def get_signal(self, symbol):
if self.entry_signal_type == 'mfirsi_signal':
logging.info(f"Using mfirsi signals for symbol {symbol}")
signal = self.get_mfirsi_signal(symbol)
elif self.entry_signal_type == 'lorentzian':
logging.info(f"Using lorentzian signals for symbol {symbol}")
signal = self.generate_l_signals(symbol)
else:
raise ValueError(f"Unknown entry signal type: {self.entry_signal_type}")
logging.info(f"Generated signal for {symbol}: {signal}")
if signal == "neutral":
logging.info(f"Skipping processing for {symbol} due to neutral signal.")
return "neutral" # Return a specific flag for neutral signals
return signal
def generate_l_signals(self, symbol):
with general_rate_limiter:
return self.exchange.generate_l_signals(symbol)
def get_mfirsi_signal(self, symbol):
# Retrieve the MFI/RSI signal
with general_rate_limiter:
return self.exchange.get_mfirsi_ema_secondary_ema(symbol, limit=100, lookback=1, ema_period=5, secondary_ema_period=3)
BALANCE_REFRESH_INTERVAL = 600 # in seconds
orders_canceled = False
def run_bot(symbol, args, market_maker, manager, account_name, symbols_allowed, rotator_symbols_standardized, thread_completed, mfirsi_signal, action):
global orders_canceled, unique_active_symbols, active_long_symbols, active_short_symbols
current_thread = threading.current_thread()
try:
if not args.config.startswith('configs/'):
config_file_path = Path('configs/' + args.config)
else:
config_file_path = Path(args.config)
logging.info(f"Loading config from: {config_file_path}")
account_file_path = Path('configs/account.json') # Define the account file path
config = load_config(config_file_path, account_file_path) # Pass both file paths to load_config
exchange_name = args.exchange
strategy_name = args.strategy
account_name = args.account_name
logging.info(f"Trading symbol: {symbol}")
logging.info(f"Exchange name: {exchange_name}")
logging.info(f"Strategy name: {strategy_name}")
logging.info(f"Account name: {account_name}")
market_maker.manager = manager
def fetch_open_positions():
with general_rate_limiter:
return getattr(manager.exchange, f"get_all_open_positions_{args.exchange.lower()}")()
open_position_data = fetch_open_positions()
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
current_long_positions = [standardize_symbol(pos['symbol']) for pos in open_position_data if pos['side'].lower() == 'long']
current_short_positions = [standardize_symbol(pos['symbol']) for pos in open_position_data if pos['side'].lower() == 'short']
logging.info(f"Current long positions: {current_long_positions}")
logging.info(f"Current short positions: {current_short_positions}")
with thread_to_symbol_lock:
is_open_position = symbol in open_position_symbols
if not is_open_position and len(unique_active_symbols) >= symbols_allowed and symbol not in unique_active_symbols:
logging.info(f"Symbols allowed limit reached. Skipping new symbol {symbol}.")
return
thread_to_symbol[current_thread] = symbol
active_symbols.add(symbol)
unique_active_symbols.add(symbol)
if action == "long" or symbol in current_long_positions:
active_long_symbols.add(symbol)
elif action == "short" or symbol in current_short_positions:
active_short_symbols.add(symbol)
try:
if not orders_canceled and hasattr(market_maker.exchange, 'cancel_all_open_orders_bybit'):
market_maker.exchange.cancel_all_open_orders_bybit()
logging.info(f"Cleared all open orders on the exchange upon initialization.")
orders_canceled = True
except Exception as e:
logging.error(f"Exception caught while cancelling orders: {e}")
logging.info(f"Rotator symbols in run_bot: {rotator_symbols_standardized}")
logging.info(f"Latest rotator symbols in run bot: {latest_rotator_symbols}")
time.sleep(2)
with general_rate_limiter:
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
future = market_maker.run_strategy(symbol, args.strategy, config, account_name, symbols_to_trade=symbols_allowed, rotator_symbols_standardized=latest_rotator_symbols, mfirsi_signal=signal, action=action)
future.result() # Wait for the strategy to complete
except Exception as e:
logging.info(f"An error occurred in run_bot for symbol {symbol}: {e}")
logging.info(traceback.format_exc())
finally:
with thread_to_symbol_lock:
if current_thread in thread_to_symbol:
del thread_to_symbol[current_thread]
active_symbols.discard(symbol)
unique_active_symbols.discard(symbol)
active_long_symbols.discard(symbol)
active_short_symbols.discard(symbol)
logging.info(f"Thread for symbol {symbol} with action {action} has completed.")
thread_completed.set()
def bybit_auto_rotation(args, market_maker, manager, symbols_allowed):
global latest_rotator_symbols, long_threads, short_threads, active_symbols, active_long_symbols, active_short_symbols, last_rotator_update_time, unique_active_symbols
max_workers_signals = 1
max_workers_trading = 1
signal_executor = ThreadPoolExecutor(max_workers=max_workers_signals)
trading_executor = ThreadPoolExecutor(max_workers=max_workers_trading)
logging.info(f"Initialized signal executor with max workers: {max_workers_signals}")
logging.info(f"Initialized trading executor with max workers: {max_workers_trading}")
config_file_path = Path('configs/' + args.config) if not args.config.startswith('configs/') else Path(args.config)
account_file_path = Path('configs/account.json')
config = load_config(config_file_path, account_file_path)
market_maker.manager = manager
long_mode = config.bot.linear_grid['long_mode']
short_mode = config.bot.linear_grid['short_mode']
config_graceful_stop_long = config.bot.linear_grid.get('graceful_stop_long', False)
config_graceful_stop_short = config.bot.linear_grid.get('graceful_stop_short', False)
config_auto_graceful_stop = config.bot.linear_grid.get('auto_graceful_stop', False)
target_coins_mode = config.bot.linear_grid.get('target_coins_mode', False)
whitelist = set(config.bot.whitelist) if target_coins_mode else None
logging.info(f"Target coins mode is {'enabled' if target_coins_mode else 'disabled'}")
def fetch_open_positions():
with general_rate_limiter:
return getattr(manager.exchange, f"get_all_open_positions_{args.exchange.lower()}")()
open_position_data = fetch_open_positions()
current_long_positions = sum(1 for pos in open_position_data if pos['side'].lower() == 'long')
current_short_positions = sum(1 for pos in open_position_data if pos['side'].lower() == 'short')
graceful_stop_long = current_long_positions >= symbols_allowed or config_graceful_stop_long
graceful_stop_short = current_short_positions >= symbols_allowed or config_graceful_stop_short
logging.info(f"Long mode: {long_mode}")
logging.info(f"Short mode: {short_mode}")
logging.info(f"Initial Graceful stop long: {graceful_stop_long}")
logging.info(f"Initial Graceful stop short: {graceful_stop_short}")
logging.info(f"Auto graceful stop: {config_auto_graceful_stop}")
def process_futures(futures):
for future in as_completed(futures):
try:
future.result()
except Exception as e:
logging.error(f"Exception in thread: {e}")
logging.debug(traceback.format_exc())
processed_symbols = set()
while True:
try:
current_time = time.time()
open_position_data = fetch_open_positions()
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
current_long_positions = sum(1 for pos in open_position_data if pos['side'].lower() == 'long')
current_short_positions = sum(1 for pos in open_position_data if pos['side'].lower() == 'short')
logging.info(f"Current long positions: {current_long_positions}, Current short positions: {current_short_positions}")
update_active_symbols(open_position_symbols)
unique_active_symbols = active_long_symbols.union(active_short_symbols)
if config_auto_graceful_stop:
if (current_long_positions >= symbols_allowed or len(unique_active_symbols) >= symbols_allowed) and not graceful_stop_long:
graceful_stop_long = True
logging.info(f"GS Auto Check: Automatically enabled graceful stop for long positions. Current long positions: {current_long_positions}, Unique active symbols: {len(unique_active_symbols)}")
elif current_long_positions < symbols_allowed and len(unique_active_symbols) < symbols_allowed and graceful_stop_long:
graceful_stop_long = config_graceful_stop_long
logging.info(f"GS Auto Check: Reverting to config value for graceful stop long. Current long positions: {current_long_positions}, Unique active symbols: {len(unique_active_symbols)}, Config value: {config_graceful_stop_long}")
else:
logging.info(f"GS Auto Check: Current long positions: {current_long_positions}, Unique active symbols: {len(unique_active_symbols)}. Graceful stop long: {graceful_stop_long}")
if (current_short_positions >= symbols_allowed or len(unique_active_symbols) >= symbols_allowed) and not graceful_stop_short:
graceful_stop_short = True
logging.info(f"GS Auto Check: Automatically enabled graceful stop for short positions. Current short positions: {current_short_positions}, Unique active symbols: {len(unique_active_symbols)}")
elif current_short_positions < symbols_allowed and len(unique_active_symbols) < symbols_allowed and graceful_stop_short:
graceful_stop_short = config_graceful_stop_short
logging.info(f"GS Auto Check: Reverting to config value for graceful stop short. Current short positions: {current_short_positions}, Unique active symbols: {len(unique_active_symbols)}, Config value: {config_graceful_stop_short}")
else:
logging.info(f"GS Auto Check: Current short positions: {current_short_positions}, Unique active symbols: {len(unique_active_symbols)}. Graceful stop short: {graceful_stop_short}")
if not latest_rotator_symbols or current_time - last_rotator_update_time >= 60:
with general_rate_limiter:
latest_rotator_symbols = fetch_updated_symbols(args, manager, whitelist)
last_rotator_update_time = current_time
processed_symbols.clear()
logging.info(f"Refreshed latest rotator symbols: {latest_rotator_symbols}")
else:
logging.debug(f"No refresh needed yet. Last update was at {last_rotator_update_time}, less than 60 seconds ago.")
with thread_management_lock:
open_position_futures = []
signal_futures = []
update_active_symbols(open_position_symbols)
unique_active_symbols = active_long_symbols.union(active_short_symbols)
logging.info(f"Active symbols updated. Long symbols allowed: {symbols_allowed}, Short symbols allowed: {symbols_allowed}")
logging.info(f"Active symbols: {active_symbols}")
logging.info(f"Unique active symbols: {unique_active_symbols}")
# Process signals for open positions
for symbol in open_position_symbols.copy():
has_open_long = any(pos['side'].lower() == 'long' for pos in open_position_data if standardize_symbol(pos['symbol']) == symbol)
has_open_short = any(pos['side'].lower() == 'short' for pos in open_position_data if standardize_symbol(pos['symbol']) == symbol)
long_thread_running = symbol in long_threads and long_threads[symbol][0].is_alive()
short_thread_running = symbol in short_threads and short_threads[symbol][0].is_alive()
logging.info(f"Long thread running for {symbol}: {long_thread_running}")
logging.info(f"Short thread running for {symbol}: {short_thread_running}")
# Ensure that we process signals for open positions separately
open_position_futures.append(signal_executor.submit(
process_signal_for_open_position,
symbol, args, market_maker, manager, symbols_allowed, open_position_data, long_mode, short_mode, graceful_stop_long, graceful_stop_short
))
if has_open_long and not long_thread_running:
logging.info(f"Open symbol {symbol} has open long: {has_open_long} and long thread not running {long_thread_running}")
open_position_futures.append(trading_executor.submit(
start_thread_for_open_symbol,
symbol, args, manager, "long", True, False,
long_mode, short_mode, graceful_stop_long, graceful_stop_short
))
active_long_symbols.add(symbol)
unique_active_symbols.add(symbol)
logging.info(f"Submitted long thread for open symbol {symbol}. Has open long: {has_open_long}.")
time.sleep(2)
if has_open_short and not short_thread_running:
logging.info(f"Open symbol {symbol} has open short: {has_open_short} and short thread not running {short_thread_running}")
open_position_futures.append(trading_executor.submit(
start_thread_for_open_symbol,
symbol, args, manager, "short", False, True,
long_mode, short_mode, graceful_stop_long, graceful_stop_short
))
active_short_symbols.add(symbol)
unique_active_symbols.add(symbol)
logging.info(f"Submitted short thread for open symbol {symbol}. Has open short: {has_open_short}.")
time.sleep(2)
# Process new symbols after open positions
if len(unique_active_symbols) < symbols_allowed:
symbols_to_process = whitelist if target_coins_mode else latest_rotator_symbols
logging.info(f"Unique active symbols are less than allowed, processing symbols from {'whitelist' if target_coins_mode else 'latest rotator symbols'}")
logging.info(f"Symbols to process: {symbols_to_process}")
for symbol in symbols_to_process:
if symbol not in processed_symbols and symbol not in unique_active_symbols:
if len(unique_active_symbols) >= symbols_allowed:
logging.info(f"Reached symbols_allowed limit. Stopping processing of new symbols.")
break
can_open_long = len(active_long_symbols) < symbols_allowed and not graceful_stop_long
can_open_short = len(active_short_symbols) < symbols_allowed and not graceful_stop_short
if (can_open_long and long_mode) or (can_open_short and short_mode):
signal_futures.append(signal_executor.submit(
process_signal,
symbol, args, market_maker, manager, symbols_allowed, open_position_data, False, can_open_long, can_open_short, graceful_stop_long, graceful_stop_short
))
logging.info(f"Submitted signal processing for new symbol {symbol}.")
processed_symbols.add(symbol)
unique_active_symbols.add(symbol) # Immediately update unique_active_symbols
time.sleep(2)
logging.info(f"Submitted signal processing for open position symbols: {open_position_symbols}.")
process_futures(open_position_futures + signal_futures)
completed_symbols = []
for symbol, (thread, thread_completed) in {**long_threads, **short_threads}.items():
if thread_completed.is_set():
thread.join()
completed_symbols.append(symbol)
for symbol in completed_symbols:
active_symbols.discard(symbol)
if symbol in long_threads:
del long_threads[symbol]
if symbol in short_threads:
del short_threads[symbol]
active_long_symbols.discard(symbol)
active_short_symbols.discard(symbol)
unique_active_symbols.discard(symbol)
logging.info(f"Thread and symbol management completed for: {symbol}")
except Exception as e:
logging.info(f"Exception caught in bybit_auto_rotation: {str(e)}")
logging.info(traceback.format_exc())
time.sleep(1)
def bybit_auto_rotation_spot(args, market_maker, manager, symbols_allowed):
global latest_rotator_symbols, active_symbols, last_rotator_update_time
# Set max_workers to the number of CPUs
max_workers_signals = 1
max_workers_trading = 1
signal_executor = ThreadPoolExecutor(max_workers=max_workers_signals)
trading_executor = ThreadPoolExecutor(max_workers=max_workers_trading)
logging.info(f"Initialized signal executor with max workers: {max_workers_signals}")
logging.info(f"Initialized trading executor with max workers: {max_workers_trading}")
config_file_path = Path('configs/' + args.config) if not args.config.startswith('configs/') else Path(args.config)
account_file_path = Path('configs/account.json')
config = load_config(config_file_path, account_file_path)
market_maker = DirectionalMarketMaker(config, args.exchange, args.account_name)
market_maker.manager = manager
long_mode = config.bot.linear_grid['long_mode']
short_mode = config.bot.linear_grid['short_mode']
logging.info(f"Long mode: {long_mode}")
logging.info(f"Short mode: {short_mode}")
def fetch_open_positions():
with general_rate_limiter:
return getattr(manager.exchange, f"get_all_open_positions_{args.exchange.lower()}")()
def process_futures(futures):
for future in as_completed(futures):
try:
future.result()
except Exception as e:
logging.error(f"Exception in thread: {e}")
logging.debug(traceback.format_exc())
while True:
try:
current_time = time.time()
open_position_data = fetch_open_positions()
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
if not latest_rotator_symbols or current_time - last_rotator_update_time >= 60:
with general_rate_limiter:
latest_rotator_symbols = fetch_updated_symbols(args, manager)
last_rotator_update_time = current_time
logging.info(f"Refreshed latest rotator symbols: {latest_rotator_symbols}")
else:
logging.debug(f"No refresh needed yet. Last update was at {last_rotator_update_time}, less than 60 seconds ago.")
update_active_symbols(open_position_symbols)
logging.info(f"Active symbols: {active_symbols}")
logging.info(f"Active symbols updated. Symbols allowed: {symbols_allowed}")
with thread_management_lock:
open_position_futures = []
for symbol in open_position_symbols:
with general_rate_limiter:
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
has_open_long = any(pos['side'].lower() == 'long' for pos in open_position_data if standardize_symbol(pos['symbol']) == symbol)
open_position_futures.append(trading_executor.submit(start_thread_for_open_symbol_spot, symbol, args, manager, signal, has_open_long, long_mode, short_mode))
logging.info(f"Submitted thread for symbol {symbol}. Signal: {signal}. Has open long: {has_open_long}.")
signal_futures = [signal_executor.submit(process_signal_for_open_position_spot, symbol, args, manager, symbols_allowed, open_position_data, long_mode, short_mode)
for symbol in open_position_symbols]
logging.info(f"Submitted signal processing for open position symbols: {open_position_symbols}.")
if len(active_symbols) < symbols_allowed:
for symbol in latest_rotator_symbols:
signal_futures.append(signal_executor.submit(process_signal_spot, symbol, args, manager, symbols_allowed, open_position_data, False, long_mode, short_mode))
logging.info(f"Submitted signal processing for new rotator symbol {symbol}.")
time.sleep(2)
process_futures(open_position_futures + signal_futures)
completed_symbols = []
for symbol, (thread, thread_completed) in long_threads.items():
if thread_completed.is_set():
thread.join()
completed_symbols.append(symbol)
for symbol in completed_symbols:
active_symbols.discard(symbol)
if symbol in long_threads:
del long_threads[symbol]
logging.info(f"Thread and symbol management completed for: {symbol}")
except Exception as e:
logging.error(f"Exception caught in bybit_auto_rotation_spot: {str(e)}")
logging.debug(traceback.format_exc())
time.sleep(1)
def process_signal_for_open_position(symbol, args, market_maker, manager, symbols_allowed, open_position_data, long_mode, short_mode, graceful_stop_long, graceful_stop_short):
market_maker.manager = manager
with general_rate_limiter:
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
logging.info(f"Processing signal for open position symbol {symbol}. Signal: {signal}")
action_taken = handle_signal(symbol, args, manager, signal, open_position_data, symbols_allowed, True, long_mode, short_mode, graceful_stop_long, graceful_stop_short)
if action_taken:
logging.info(f"Action taken for open position symbol {symbol}.")
else:
logging.info(f"No action taken for open position symbol {symbol}.")
def process_signal(symbol, args, market_maker, manager, symbols_allowed, open_position_data, is_open_position, long_mode, short_mode, graceful_stop_long, graceful_stop_short):
market_maker.manager = manager
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
if signal == "neutral": # Check for neutral signal
logging.info(f"Skipping signal processing for {symbol} due to neutral signal.")
return False
logging.info(f"Processing signal for {'open position' if is_open_position else 'new rotator'} symbol {symbol}. Signal: {signal}")
action_taken = handle_signal(symbol, args, manager, signal, open_position_data, symbols_allowed, is_open_position, long_mode, short_mode, graceful_stop_long, graceful_stop_short)
if action_taken:
logging.info(f"Action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
else:
logging.info(f"No action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol} due to existing position or lack of clear signal.")
return action_taken
def handle_signal_targetcoin(symbol, args, manager, signal, open_position_data, symbols_allowed, is_open_position, long_mode, short_mode, graceful_stop_long, graceful_stop_short):
global unique_active_symbols, active_long_symbols, active_short_symbols
# Log receipt of the signal and handle neutral signals early
if signal == "neutral":
logging.info(f"Received neutral signal for symbol {symbol}. Checking open positions.")
action_taken = start_thread_for_open_symbol(symbol, args, manager, signal,
has_open_long=symbol in active_long_symbols,
has_open_short=symbol in active_short_symbols,
long_mode=long_mode, short_mode=short_mode,
graceful_stop_long=graceful_stop_long,
graceful_stop_short=graceful_stop_short)
return action_taken
# Gather open position symbols and log the current state
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
# Determine the type of signal (long/short)
signal_long = signal.lower() == "long"
signal_short = signal.lower() == "short"
# Log the status of the bot's current positions
current_long_positions = len(active_long_symbols)
current_short_positions = len(active_short_symbols)
logging.info(f"Handling signal for {'open position' if is_open_position else 'new rotator'} symbol {symbol}. "
f"Current long positions: {current_long_positions}. "
f"Current short positions: {current_short_positions}. "
f"Unique active symbols: {len(unique_active_symbols)}")
logging.info(f"Active long symbols: {active_long_symbols}")
logging.info(f"Active short symbols: {active_short_symbols}")
# Check if there are open long/short positions for the symbol
has_open_long = symbol in active_long_symbols
has_open_short = symbol in active_short_symbols
# Log details about the current state and modes
logging.info(f"{'Open position' if is_open_position else 'New rotator'} symbol {symbol} - "
f"Has open long: {has_open_long}, Has open short: {has_open_short}")
logging.info(f"Signal: {signal}, Long Mode: {long_mode}, Short Mode: {short_mode}")
# Flags to track if actions are taken
action_taken_long = False
action_taken_short = False
# Determine if the bot can add a new long/short symbol
can_add_new_long_symbol = current_long_positions < symbols_allowed
can_add_new_short_symbol = current_short_positions < symbols_allowed
# Handle long signals
if signal_long and long_mode:
if (can_add_new_long_symbol or symbol in unique_active_symbols) and not has_open_long:
if graceful_stop_long and not is_open_position:
logging.info(f"Skipping long signal for {symbol} due to graceful stop long enabled and no open long position.")
elif not (symbol in long_threads and long_threads[symbol][0].is_alive()):
logging.info(f"Starting long thread for symbol {symbol}.")
action_taken_long = start_thread_for_symbol(symbol, args, manager, signal, "long", has_open_long, has_open_short)
else:
logging.info(f"Long thread already running for symbol {symbol}. Skipping.")
else:
logging.info(f"Cannot open long position for {symbol}. Long positions limit reached or position already exists.")
# Handle short signals
if signal_short and short_mode:
if (can_add_new_short_symbol or symbol in unique_active_symbols) and not has_open_short:
if graceful_stop_short and not is_open_position:
logging.info(f"Skipping short signal for {symbol} due to graceful stop short enabled and no open short position.")
elif not (symbol in short_threads and short_threads[symbol][0].is_alive()):
logging.info(f"Starting short thread for symbol {symbol}.")
action_taken_short = start_thread_for_symbol(symbol, args, manager, signal, "short", has_open_long, has_open_short)
else:
logging.info(f"Short thread already running for symbol {symbol}. Skipping.")
else:
logging.info(f"Cannot open short position for {symbol}. Short positions limit reached or position already exists.")
# Update active symbols based on actions taken
if action_taken_long or action_taken_short:
unique_active_symbols.add(symbol)
if action_taken_long:
active_long_symbols.add(symbol)
if action_taken_short:
active_short_symbols.add(symbol)
logging.info(f"Action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
else:
logging.info(f"No action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
# Return the result indicating whether any action was taken
return action_taken_long or action_taken_short
def handle_signal(symbol, args, manager, signal, open_position_data, symbols_allowed, is_open_position, long_mode, short_mode, graceful_stop_long, graceful_stop_short):
global unique_active_symbols, active_long_symbols, active_short_symbols
# Log receipt of the signal and handle neutral signals for open positions early
logging.info(f"Received signal '{signal}' for symbol {symbol}. Checking open positions and starting threads if needed.")
# Gather open position symbols and log the current state
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
# Determine the type of signal (long/short/neutral)
signal_long = signal.lower() == "long"
signal_short = signal.lower() == "short"
signal_neutral = signal.lower() == "neutral"
# Log the status of the bot's current positions
current_long_positions = len(active_long_symbols)
current_short_positions = len(active_short_symbols)
logging.info(f"Handling signal for {'open position' if is_open_position else 'new rotator'} symbol {symbol}. "
f"Current long positions: {current_long_positions}. "
f"Current short positions: {current_short_positions}. "
f"Unique active symbols: {len(unique_active_symbols)}")
logging.info(f"Active long symbols: {active_long_symbols}")
logging.info(f"Active short symbols: {active_short_symbols}")
# Check if there are open long/short positions for the symbol
has_open_long = symbol in active_long_symbols
has_open_short = symbol in active_short_symbols
# Log details about the current state and modes
logging.info(f"{'Open position' if is_open_position else 'New rotator'} symbol {symbol} - "
f"Has open long: {has_open_long}, Has open short: {has_open_short}")
logging.info(f"Signal: {signal}, Long Mode: {long_mode}, Short Mode: {short_mode}")
# Initialize action_taken variables to avoid reference errors
action_taken_long = False
action_taken_short = False
# Handle neutral signals for open positions (optional logic to trigger action on neutral signals)
if signal_neutral and is_open_position:
logging.info(f"Neutral signal received for symbol {symbol}. Managing open position.")
action_taken = start_thread_for_open_symbol(symbol, args, manager, signal,
has_open_long=has_open_long,
has_open_short=has_open_short,
long_mode=long_mode,
short_mode=short_mode,
graceful_stop_long=graceful_stop_long,
graceful_stop_short=graceful_stop_short)
return action_taken
# Handle long signals for open positions or new symbols
if signal_long and long_mode and not has_open_long:
if graceful_stop_long:
logging.info(f"Skipping long signal for {symbol} due to graceful stop long enabled.")
else:
logging.info(f"Starting long thread for symbol {symbol}.")
action_taken_long = start_thread_for_symbol(symbol, args, manager, signal, "long", has_open_long, has_open_short)
if action_taken_long:
active_long_symbols.add(symbol)
unique_active_symbols.add(symbol)
# Handle short signals for open positions or new symbols
if signal_short and short_mode and not has_open_short:
if graceful_stop_short:
logging.info(f"Skipping short signal for {symbol} due to graceful stop short enabled.")
else:
logging.info(f"Starting short thread for symbol {symbol}.")
action_taken_short = start_thread_for_symbol(symbol, args, manager, signal, "short", has_open_long, has_open_short)
if action_taken_short:
active_short_symbols.add(symbol)
unique_active_symbols.add(symbol)
# If no action was taken for long or short, log it
if not action_taken_long and not action_taken_short:
logging.info(f"No action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
# Return the result indicating whether any action was taken
return action_taken_long or action_taken_short
def handle_signal_spot(symbol, args, manager, signal, open_position_data, symbols_allowed, is_open_position, long_mode, short_mode):
open_position_symbols = {standardize_symbol(pos['symbol']) for pos in open_position_data}
logging.info(f"Open position symbols: {open_position_symbols}")
signal_long = signal.lower() == "long"
signal_short = signal.lower() == "short"
current_long_positions = sum(1 for pos in open_position_data if pos['side'].lower() == 'long')
unique_open_symbols = len(open_position_symbols)
logging.info(f"Handling signal for {'open position' if is_open_position else 'new rotator'} symbol {symbol}. Current long positions: {current_long_positions}. Unique open symbols: {unique_open_symbols}")
has_open_long = any(pos['side'].lower() == 'long' for pos in open_position_data if standardize_symbol(pos['symbol']) == symbol)
logging.info(f"{'Open position' if is_open_position else 'New rotator'} symbol {symbol} - Has open long: {has_open_long}")
action_taken_long = False
if signal_long and long_mode and not has_open_long:
logging.info(f"Starting long thread for symbol {symbol}.")
action_taken_long = start_thread_for_symbol_spot(symbol, args, market_maker, manager, signal, "long")
else:
logging.info(f"Long thread already running or long position already open for symbol {symbol}. Skipping.")
if signal_short and short_mode and has_open_long:
logging.info(f"Starting short (sell) thread for symbol {symbol}.")
action_taken_long = start_thread_for_symbol_spot(symbol, args, market_maker, manager, signal, "short")
else:
logging.info(f"Short thread (sell order) already running or no long position open for symbol {symbol}. Skipping.")
if action_taken_long:
logging.info(f"Action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
else:
logging.info(f"Evaluated action for {'open position' if is_open_position else 'new rotator'} symbol {symbol}: No action due to existing position or lack of clear signal.")
return action_taken_long
def process_signal_for_open_position_spot(symbol, args, market_maker, manager, symbols_allowed, open_position_data, long_mode, short_mode):
market_maker.manager = manager
with general_rate_limiter:
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
logging.info(f"Processing signal for open position symbol {symbol}. Signal: {signal}")
action_taken = handle_signal_spot(symbol, args, manager, signal, open_position_data, symbols_allowed, True, long_mode, short_mode)
if action_taken:
logging.info(f"Action taken for open position symbol {symbol}.")
else:
logging.info(f"No action taken for open position symbol {symbol}.")
def process_signal_spot(symbol, args, market_maker, manager, symbols_allowed, open_position_data, is_open_position, long_mode, short_mode):
market_maker.manager = manager
signal = market_maker.get_signal(symbol) # Use the appropriate signal based on the entry_signal_type
logging.info(f"Processing signal for {'open position' if is_open_position else 'new rotator'} symbol {symbol}. Signal: {signal}")
action_taken = handle_signal_spot(symbol, args, manager, signal, open_position_data, symbols_allowed, is_open_position, long_mode, short_mode)
if action_taken:
logging.info(f"Action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
else:
logging.info(f"No action taken for {'open position' if is_open_position else 'new rotator'} symbol {symbol}.")
def start_thread_for_open_symbol_spot(symbol, args, manager, signal, has_open_long, long_mode, short_mode):
action_taken = False
if long_mode and (has_open_long or signal.lower() == "long"):
action_taken |= start_thread_for_symbol_spot(symbol, args, manager, signal, "long")
logging.info(f"[DEBUG] Started long thread for open symbol {symbol}")