-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathPBCoinData.py
More file actions
2787 lines (2421 loc) · 114 KB
/
PBCoinData.py
File metadata and controls
2787 lines (2421 loc) · 114 KB
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 psutil
import subprocess
from time import sleep
from requests import Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import configparser
from pathlib import Path, PurePath
from datetime import datetime
import platform
import sys
import os
import re
from Exchange import Exchange, Exchanges, V7
from logging_helpers import human_log as _log
def remove_powers_of_ten(text):
"""
Remove any variant of "10", "100", "1000", "10000", etc. from a string.
Handles cases like "1000SHIB" -> "SHIB", "1000000BABYDOGE" -> "BABYDOGE".
Same logic as passivbot's utils.py.
"""
pattern = r"(?<!\d)1(?:0+)(?!\d)"
return re.sub(pattern, "", text)
_HYPERLIQUID_K_PREFIX_COINS = {"BONK", "FLOKI", "LUNC", "PEPE", "SHIB", "DOGS", "NEIRO"}
_HYPERLIQUID_HIP3_DEX_PREFIXES = {"XYZ", "FLX", "CASH", "HYNA", "KM", "VNTL", "ABCD"}
def _strip_hyperliquid_k_prefix(name: str) -> str:
"""Normalize Hyperliquid k/K prefix coins to short name (kPEPE/ KPEPE -> PEPE)."""
if not name:
return name
if len(name) <= 1:
return name
if name[0] in ("k", "K"):
tail = name[1:]
if tail.upper() in _HYPERLIQUID_K_PREFIX_COINS:
return tail
return name
def _is_hyperliquid_hip3_base_symbol(name: str) -> bool:
s = str(name or "").strip().upper()
if not s or "-" not in s:
return False
prefix, tail = s.split("-", 1)
if not prefix or not tail:
return False
return prefix in _HYPERLIQUID_HIP3_DEX_PREFIXES
def _normalize_hyperliquid_hip3_alias(symbol: str) -> str:
"""Normalize supported Hyperliquid HIP-3 aliases to PBGui's XYZ-TICKER form."""
value = str(symbol or "").strip().upper()
if not value:
return ""
base = value.split("/", 1)[0].strip()
if base.startswith("XYZ:") and len(base) > 4:
return f"XYZ-{base[4:].strip()}"
if _is_hyperliquid_hip3_base_symbol(base):
return base
return ""
def compute_coin_name(market_id, quote=""):
"""
Compute PB7-compatible coin name from exchange market_id and quote currency.
Derives the coin name the same way the ini pipeline does:
1. Strip contract type suffixes (-SWAP, -PERP, _PERP)
2. Remove exchange-specific separators (dashes, underscores)
3. Strip quote currency suffix (USDT, USDC, etc.)
4. Strip bare PERP suffix (Bybit/Bitget USDC: BTCPERP → BTC)
5. Handle k-prefix (Hyperliquid: kPEPE → PEPE)
6. Strip 1000x multiplier prefixes (1000SHIB → SHIB)
Uses market_id (not CCXT base) because CCXT sometimes returns display
names that differ from the trading symbol (e.g. DegenReborn for DEGENUSDT
on Bitget, RedLang for RED_USDT on Gateio).
Args:
market_id: Exchange market ID (e.g., "DEGENUSDT", "BTC-USDT-SWAP",
"BTC_USDT", "1000SHIBUSDT", "BTCPERP")
quote: Quote currency to strip (e.g., "USDT", "USDC", "SUSDT")
Returns:
str: Normalized coin name, uppercase (e.g., "DEGEN", "BTC", "SHIB")
"""
if not market_id:
return ""
name = market_id
# Strip contract type suffixes (OKX: -SWAP; some: -PERP, _PERP)
for suffix in ("-SWAP", "-PERP", "_PERP"):
if name.endswith(suffix):
name = name[:-len(suffix)]
break
# Remove exchange-specific separators (OKX dashes, Gateio underscores)
name = name.replace("-", "").replace("_", "")
# Strip quote currency suffix
if quote and name.upper().endswith(quote.upper()):
name = name[:-len(quote)]
# Strip bare PERP suffix (Bybit/Bitget USDC markets: BTCPERP -> BTC)
if name.upper().endswith("PERP") and len(name) > 4:
name = name[:-4]
# Handle Hyperliquid k/K-prefix (kPEPE/KPEPE -> PEPE)
name = _strip_hyperliquid_k_prefix(name)
# Strip 1000x multiplier prefixes (1000SHIB -> SHIB)
name = remove_powers_of_ten(name)
return name.upper()
def build_symbol_mappings(symbols):
"""
Build dynamic symbol mappings from exchange symbols.
Creates variants like passivbot does:
- Original symbol
- Without 'k' prefix (kSHIB -> SHIB)
- Without powers of ten (1000SHIB -> SHIB)
- Combined (k1000SHIB -> SHIB)
Args:
symbols: List of trading pair symbols (e.g., ["1000SHIBUSDT", "BTCUSDT"])
Returns:
dict: Mapping of symbol variants to normalized base coin
"""
mappings = {}
for symbol in symbols:
# Remove quote currency suffixes
base = symbol
# Check for stablecoin/quote-like patterns
if base in ["USDC", "USDT", "BUSD", "TUSD", "DAI"]:
continue
for quote in ["USDT", "USDC", "BUSD", "USD"]:
if base.endswith(quote):
remaining = base[:-len(quote)]
if not remaining:
continue
# After stripping, check if result looks like a quote-based coin
if remaining.startswith(("USD", "EUR", "GBP")) and len(remaining) <= 5:
base = remaining
break
base = remaining
break
# Create variants like passivbot
variants = set()
variants.add(base) # Original: 1000SHIB
variants.add(base.replace("k", "")) # Without k: 1000SHIB
variants.add(remove_powers_of_ten(base)) # Without 1000: SHIB
cleaned = remove_powers_of_ten(base.replace("k", "")) # Both: SHIB
variants.add(cleaned)
# Map all variants to the cleaned base coin
for variant in variants:
if variant: # Skip empty strings
mappings[variant] = cleaned
return mappings
def normalize_symbol(symbol, symbol_mappings=None):
"""
Normalize a trading symbol to its base coin name.
Args:
symbol: Trading pair symbol (e.g., "1000SHIBUSDT", "kPEPE", "BTCUSDT")
symbol_mappings: Optional pre-built mapping dict from build_symbol_mappings()
Returns:
str: Normalized base coin (e.g., "SHIB", "PEPE", "BTC")
"""
if not symbol:
return ""
# Remove quote currency suffixes
base = str(symbol).strip().upper()
hip3_alias = _normalize_hyperliquid_hip3_alias(base)
if hip3_alias:
return hip3_alias
# Check for stablecoin/quote-like patterns that should NOT be stripped further
# These are coins whose names resemble quotes (USDe, USDC as trading pair, etc.)
if base in ["USDC", "USDT", "BUSD", "TUSD", "DAI"]:
# These are either stablecoins traded as pairs or the coin itself
return base
# Preserve Hyperliquid HIP-3 base symbols (XYZ-TSLA, XYZ-HYUNDAI, FLX-GOLD, ...)
# as-is to avoid accidental quote stripping (e.g. XYZ-HYUNDAI -> XYZ-HYUN).
if _is_hyperliquid_hip3_base_symbol(base):
return str(base).upper()
for quote in ["USDT", "USDC", "BUSD", "TUSD", "USD", "EUR", "GBP", "DAI"]:
if base.endswith(quote):
remaining = base[:-len(quote)]
if not remaining:
continue # Don't strip if nothing remains
# Avoid over-stripping when quote appears as a hyphenated/base suffix,
# e.g. "XYZ-EUR" -> keep as-is instead of producing "XYZ-".
if remaining.endswith(("-", "_", ":", "/")):
continue
# After stripping, check if result looks like a quote-based coin (USDe, USD1, EURo)
# Pattern: starts with quote prefix + has only 1-2 additional chars
if remaining.startswith(("USD", "EUR", "GBP")) and len(remaining) <= 5:
# This is likely a coin with quote prefix (USDe, USD1, etc.), keep it
base = remaining
break
# Strip the quote
base = remaining
break
# Handle Hyperliquid format: kPEPE/KPEPE -> PEPE
base = _strip_hyperliquid_k_prefix(base)
# Use dynamic mappings if provided (already contains all normalization logic)
if symbol_mappings and base in symbol_mappings:
return symbol_mappings[base]
# NOTE: CMC symbol matching is handled in CoinData.build_mapping() using
# data-driven matching heuristics (no static SYMBOLMAP).
# Dynamic pattern matching for multiplier prefixes (e.g., 1000X, 10000X, 1000000X)
# This handles cases like 10000ELON -> ELON, 1000PEPE -> PEPE, etc.
import re
multiplier_match = re.match(r'^(\d+)([A-Z].*)$', base)
if multiplier_match:
multiplier, coin = multiplier_match.groups()
# Only normalize if multiplier is 1000, 10000, 100000, 1000000, 10000000, etc.
if multiplier in ['1000', '10000', '100000', '1000000', '10000000', '1000000000']:
return coin
# Last resort: return base as-is (should rarely happen if mappings are built correctly)
return base
def get_normalized_coins(symbols, symbol_mappings=None):
"""
Get unique normalized coin names from a list of trading symbols.
Removes duplicates (e.g., BTCUSDT and BTCUSDC both become BTC).
Args:
symbols: List of trading pair symbols
symbol_mappings: Optional pre-built mapping dict
Returns:
list: Sorted list of unique normalized coin names
Examples:
["BTCUSDT", "BTCUSDC", "1000SHIBUSDT", "kPEPE"] -> ["BTC", "PEPE", "SHIB"]
"""
if not symbols:
return []
coins = set()
for symbol in symbols:
normalized = normalize_symbol(symbol, symbol_mappings)
if normalized:
coins.add(normalized)
return sorted(list(coins))
# Cache for coin_to_symbol mappings
_COIN_TO_SYMBOL_CACHE = {}
_COIN_TO_SYMBOL_CACHE_SIG = {}
def _read_json_with_retry(path: Path, retries: int = 1, delay_s: float = 0.2):
"""Read JSON file with a short retry window for transient partial writes."""
attempts = max(0, int(retries)) + 1
last_error = None
for attempt in range(1, attempts + 1):
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception as e:
last_error = e
if attempt < attempts:
_log('PBCoinData', f'Retrying JSON read for {path} ({attempt}/{attempts - 1}) after error: {e}', level='WARNING')
sleep(delay_s)
continue
break
_log('PBCoinData', f'Failed to read JSON file {path}: {last_error}', level='WARNING')
return None
def get_symbol_for_coin(coin: str, exchange: str, use_cache=True) -> str:
"""
Convert normalized coin back to exchange-specific trading symbol.
This function performs the reverse operation of normalize_symbol():
- BTC + binance.swap → BTCUSDT
- PEPE + binance.swap → 1000PEPEUSDT
- PEPE + hyperliquid.swap → kPEPEUSDC
Args:
coin: Normalized coin name (e.g., "BTC", "PEPE", "SHIB")
exchange: Exchange key from pbgui.ini (e.g., "binance.swap", "hyperliquid.swap")
use_cache: Whether to use cached mappings (default: True)
Returns:
Trading symbol for the exchange (e.g., "BTCUSDT", "1000PEPEUSDT")
Falls back to {coin}USDT if no mapping found.
Examples:
>>> get_symbol_for_coin("BTC", "binance.swap")
"BTCUSDT"
>>> get_symbol_for_coin("PEPE", "binance.swap")
"1000PEPEUSDT"
>>> get_symbol_for_coin("PEPE", "hyperliquid.swap")
"kPEPEUSDC"
"""
exchange_key = str(exchange or "").strip().lower()
exchange_id, _, market_type = exchange_key.partition(".")
if not exchange_id:
exchange_id = exchange_key
market_type = market_type or "swap"
coin_key = str(coin or "").upper()
mapping_path = Path.cwd() / "data" / "coindata" / exchange_id / "mapping.json"
mapping_sig = None
if mapping_path.exists():
stat = mapping_path.stat()
mapping_sig = (stat.st_mtime_ns, stat.st_size)
# Check cache first
if (
use_cache
and exchange_key in _COIN_TO_SYMBOL_CACHE
and _COIN_TO_SYMBOL_CACHE_SIG.get(exchange_key) == mapping_sig
):
coin_map = _COIN_TO_SYMBOL_CACHE[exchange_key]
if coin_key in coin_map:
return coin_map[coin_key]
coin_map = {}
if mapping_path.exists():
mapping = _read_json_with_retry(mapping_path, retries=1, delay_s=0.1)
if not isinstance(mapping, list):
mapping = []
for record in mapping if isinstance(mapping, list) else []:
symbol = str(record.get("symbol") or "").strip().upper()
if not symbol:
continue
if market_type == "swap" and not bool(record.get("swap", False)):
continue
if market_type == "spot" and not bool(record.get("spot", False)):
continue
quote = str(record.get("quote") or "").strip().upper()
normalized = str(record.get("coin") or "").strip().upper()
if not normalized:
normalized = compute_coin_name(symbol, quote)
if normalized and normalized not in coin_map:
coin_map[normalized] = symbol
# Cache the mapping
if use_cache:
_COIN_TO_SYMBOL_CACHE[exchange_key] = coin_map
_COIN_TO_SYMBOL_CACHE_SIG[exchange_key] = mapping_sig
# Return symbol or fallback
if coin_key in coin_map:
return coin_map[coin_key]
else:
# Fallback: guess quote currency
quote = "USDC" if "hyperliquid" in exchange_key else "USDT"
# Special handling for Hyperliquid k-prefix coins
if "hyperliquid" in exchange_key and coin_key in _HYPERLIQUID_K_PREFIX_COINS:
return f"K{coin_key}{quote}"
return f"{coin_key}{quote}"
class CoinData:
def __init__(self):
pbgdir = Path.cwd()
self.piddir = Path(f'{pbgdir}/data/pid')
if not self.piddir.exists():
self.piddir.mkdir(parents=True)
self.pidfile = Path(f'{self.piddir}/pbcoindata.pid')
self.my_pid = None
self._api_key = None
self.api_error = None
self._fetch_limit = 5000
self._fetch_interval = 24
self._metadata_interval = 1
self._mapping_interval = 24
self.ini_ts = 0
self._cleanup_legacy_exchange_ini_entries()
self.load_config()
self.data = None
self.metadata = None
self.data_ts = 0
self.metadata_ts = 0
self._exchange = Exchanges.list()[0]
self.exchanges = Exchanges.list()
self.exchange_index = self.exchanges.index(self.exchange)
self.update_symbols_ts = 0
self.update_mappings_ts = 0
self._symbols = []
self._symbols_cpt = []
self._symbols_all = []
self._symbols_notice = []
self._symbols_notices = {}
self._symbols_data = []
self.approved_coins = []
self.ignored_coins = []
self._all_tags = []
self._tags = []
self._symbol_mappings = {}
# HIP-3: Exchange-specific data caches
self._ccxt_markets = {} # {exchange: markets_dict}
self._exchange_mappings = {} # {exchange: [mapping_records]}
self._exchange_mapping_ts = {} # {exchange: (mtime_ns, size)}
self._copy_trading_cache = {} # {exchange: [symbol_ids]}
self._mapping_self_heal_state = {} # {exchange: {fails:int, next_retry_ts:float}}
self._last_build_mapping_stats = {} # {exchange: {unmatched_* counters}}
self._tradfi_symbol_map: list = []
self._tradfi_symbol_map_ts: tuple | None = None
self._cmc_metrics = {
"listings_ok": 0,
"listings_fail": 0,
"metadata_ok": 0,
"metadata_fail": 0,
"status_ok": 0,
"status_fail": 0,
}
self._cmc_metrics_last_log_ts = 0.0
self._cmc_metrics_log_interval_s = 0
self._sync_cmc_metrics_log_interval()
self.load_symbols()
self._market_cap = 0
self._vol_mcap = 10.0
self._only_cpt = False
self._notices_ignore = False
def _sync_cmc_metrics_log_interval(self):
"""Align metrics health-log cadence with data-fetch cadence."""
try:
fetch_hours = max(1, int(self._fetch_interval))
except Exception:
fetch_hours = 24
self._cmc_metrics_log_interval_s = fetch_hours * 3600
def _get_exchange_dir(self, exchange: str) -> Path:
"""Get coindata directory for a specific exchange."""
pbgdir = Path.cwd()
exchange_dir = pbgdir / "data" / "coindata" / exchange
return exchange_dir
def _ensure_exchange_dir(self, exchange: str) -> Path:
"""Ensure exchange directory exists and return path."""
exchange_dir = self._get_exchange_dir(exchange)
if not exchange_dir.exists():
exchange_dir.mkdir(parents=True, exist_ok=True)
return exchange_dir
def load_ccxt_markets(self, exchange: str) -> dict:
"""Load CCXT markets from cache for a specific exchange."""
if exchange in self._ccxt_markets:
return self._ccxt_markets[exchange]
markets_file = self._get_exchange_dir(exchange) / "ccxt_markets.json"
if not markets_file.exists():
return {}
try:
markets = _read_json_with_retry(markets_file, retries=1, delay_s=0.2)
if isinstance(markets, dict):
self._ccxt_markets[exchange] = markets
return markets
_log('PBCoinData', f'CCXT markets for {exchange} are not a dict, ignoring cache', level='WARNING')
except Exception as e:
_log('PBCoinData', f'Error loading CCXT markets for {exchange}: {e}', level='ERROR')
return {}
return {}
def save_ccxt_markets(self, exchange: str, markets: dict):
"""Save CCXT markets to cache. Only writes on success."""
if not markets:
_log('PBCoinData', f'Empty markets data for {exchange}, not saving', level='WARNING')
return
exchange_dir = self._ensure_exchange_dir(exchange)
markets_file = exchange_dir / "ccxt_markets.json"
try:
# Atomic write: temp file + rename
temp_file = markets_file.with_suffix('.json.tmp')
with temp_file.open('w') as f:
json.dump(markets, f, indent=4)
temp_file.replace(markets_file)
self._ccxt_markets[exchange] = markets
_log('PBCoinData', f'Saved CCXT markets for {exchange}', level='DEBUG')
except Exception as e:
_log('PBCoinData', f'Error saving CCXT markets for {exchange}: {e}', level='ERROR')
if temp_file.exists():
temp_file.unlink()
def load_mapping(self, exchange: str, use_cache: bool = True) -> list:
"""Load mapping.json for an exchange with optional mtime-aware caching."""
if not exchange:
return []
mapping_file = self._get_exchange_dir(exchange) / "mapping.json"
if not mapping_file.exists():
self._exchange_mapping_ts.pop(exchange, None)
self._exchange_mappings.pop(exchange, None)
return []
stat = mapping_file.stat()
file_sig = (stat.st_mtime_ns, stat.st_size)
if use_cache and exchange in self._exchange_mappings and self._exchange_mapping_ts.get(exchange) == file_sig:
return self._exchange_mappings[exchange]
try:
mapping = _read_json_with_retry(mapping_file, retries=1, delay_s=0.2)
if isinstance(mapping, list):
self._exchange_mappings[exchange] = mapping
self._exchange_mapping_ts[exchange] = file_sig
return mapping
_log('PBCoinData', f'Mapping for {exchange} is not a list, ignoring cache file', level='WARNING')
return []
except Exception as e:
_log('PBCoinData', f'Error loading mapping for {exchange}: {e}', level='ERROR')
return []
def load_exchange_mapping(self, exchange: str) -> list:
"""Backward-compatible wrapper for load_mapping()."""
return self.load_mapping(exchange=exchange, use_cache=True)
def save_exchange_mapping(self, exchange: str, mapping: list):
"""Save exchange mapping to cache. Only writes on success."""
if not mapping:
_log('PBCoinData', f'Empty mapping data for {exchange}, not saving', level='WARNING')
return
exchange_dir = self._ensure_exchange_dir(exchange)
mapping_file = exchange_dir / "mapping.json"
try:
# Atomic write: temp file + rename
temp_file = mapping_file.with_suffix('.json.tmp')
with temp_file.open('w') as f:
json.dump(mapping, f, indent=4)
temp_file.replace(mapping_file)
self._exchange_mappings[exchange] = mapping
stat = mapping_file.stat()
self._exchange_mapping_ts[exchange] = (stat.st_mtime_ns, stat.st_size)
_log('PBCoinData', f'Saved mapping for {exchange}', level='DEBUG')
except Exception as e:
_log('PBCoinData', f'Error saving mapping for {exchange}: {e}', level='ERROR')
if temp_file.exists():
temp_file.unlink()
# ------------------------------------------------------------------
# TradFi symbol map (Hyperliquid XYZ stock-perps)
# ------------------------------------------------------------------
def _tradfi_symbol_map_path(self) -> Path:
"""Path to tradfi_symbol_map.json for Hyperliquid."""
return self._get_exchange_dir("hyperliquid") / "tradfi_symbol_map.json"
def load_tradfi_symbol_map(self, use_cache: bool = True) -> list:
"""Load tradfi_symbol_map.json with optional mtime-aware caching."""
path = self._tradfi_symbol_map_path()
if not path.exists():
self._tradfi_symbol_map_ts = None
self._tradfi_symbol_map = []
return []
stat = path.stat()
file_sig = (stat.st_mtime_ns, stat.st_size)
if use_cache and self._tradfi_symbol_map_ts == file_sig and self._tradfi_symbol_map is not None:
return self._tradfi_symbol_map
try:
data = _read_json_with_retry(path, retries=1, delay_s=0.2)
if isinstance(data, list):
self._tradfi_symbol_map = data
self._tradfi_symbol_map_ts = file_sig
return data
_log('PBCoinData', 'tradfi_symbol_map.json is not a list, ignoring', level='WARNING')
return []
except Exception as e:
_log('PBCoinData', f'Error loading tradfi_symbol_map.json: {e}', level='ERROR')
return []
def save_tradfi_symbol_map(self, records: list):
"""Save tradfi_symbol_map.json atomically. Preserves existing file on failure."""
if records is None:
_log('PBCoinData', 'tradfi_symbol_map: nothing to save (None)', level='WARNING')
return
path = self._tradfi_symbol_map_path()
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix('.json.tmp')
try:
with temp_path.open('w') as f:
json.dump(records, f, indent=4)
temp_path.replace(path)
self._tradfi_symbol_map = records
stat = path.stat()
self._tradfi_symbol_map_ts = (stat.st_mtime_ns, stat.st_size)
_log('PBCoinData', f'Saved tradfi_symbol_map.json ({len(records)} entries)', level='DEBUG')
except Exception as e:
_log('PBCoinData', f'Error saving tradfi_symbol_map.json: {e}', level='ERROR')
if temp_path.exists():
try:
temp_path.unlink()
except Exception:
pass
def get_tradfi_map_entry(self, xyz_coin: str) -> dict | None:
"""Return the tradfi_symbol_map entry for an xyz_coin (case-insensitive), or None."""
key = str(xyz_coin or '').strip().upper()
if not key:
return None
records = self.load_tradfi_symbol_map(use_cache=True)
for r in records:
if str(r.get('xyz_coin') or '').upper() == key:
return r
return None
def get_mapping_symbols(self, exchange: str, quote_filter: list[str] | None = None, use_cache: bool = True) -> list[str]:
"""Return symbol strings from mapping.json for an exchange."""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
symbols = []
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_filter and quote not in {q.upper() for q in quote_filter}:
continue
symbol = record.get("symbol")
if symbol:
symbols.append(symbol)
return sorted(set(symbols))
def get_mapping_coins(self, exchange: str, quote_filter: list[str] | None = None, use_cache: bool = True) -> list[str]:
"""Return normalized coin names computed from mapping symbols."""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
coins = []
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_filter and quote not in {q.upper() for q in quote_filter}:
continue
coin = (record.get("coin") or "").upper()
if not coin:
symbol = record.get("symbol") or ""
coin = compute_coin_name(symbol, quote)
if coin:
coins.append(coin.upper())
return sorted(set(coins))
def get_cpt_coins(self, exchange: str, quote_filter: list[str] | None = None, use_cache: bool = True) -> list[str]:
"""Return normalized coin names where mapping marks copy_trading=True."""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
coins = []
for record in mapping:
if not record.get("copy_trading", False):
continue
quote = (record.get("quote") or "").upper()
if quote_filter and quote not in {q.upper() for q in quote_filter}:
continue
coin = (record.get("coin") or "").upper()
if not coin:
symbol = record.get("symbol") or ""
coin = compute_coin_name(symbol, quote)
if coin:
coins.append(coin.upper())
return sorted(set(coins))
def _to_float(self, value):
try:
if value is None:
return None
return float(value)
except (TypeError, ValueError):
return None
def _passes_active_filter(self, exchange: str, record: dict) -> bool:
if not bool(record.get("active", True)):
return False
if not bool(record.get("swap", False)):
return False
if not bool(record.get("linear", True)):
return False
if exchange == "hyperliquid":
if bool(record.get("is_hip3", False)):
dex = str(record.get("dex") or "").strip().lower()
if dex != "xyz":
return False
open_interest = self._to_float(record.get("open_interest"))
if open_interest is not None and open_interest <= 0.0:
return False
return True
def filter_mapping(
self,
exchange: str,
market_cap_min_m: int | float | None = None,
vol_mcap_max: float | None = None,
only_cpt: bool | None = None,
notices_ignore: bool | None = None,
tags: list[str] | None = None,
active_only: bool | None = None,
quote_filter: list[str] | None = None,
use_cache: bool = True,
) -> tuple[list[str], list[str]]:
"""Filter mapping records and return (approved_coins, ignored_coins).
Args mirror existing CoinData filter knobs:
- market_cap_min_m: minimum market cap in millions of USD (defaults to self.market_cap)
- vol_mcap_max: maximum volume/market_cap ratio (defaults to self.vol_mcap)
- only_cpt: include only copy-trading symbols (defaults to self.only_cpt)
- notices_ignore: exclude records with a notice (defaults to self.notices_ignore)
- tags: any-tag match; empty means no tag filter (defaults to self.tags)
- active_only: apply passivbot market eligibility (active/swap/linear and
exchange-specific checks; defaults to False)
- quote_filter: optional quote whitelist (e.g. ["USDT"])
"""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
market_cap_min_m = self.market_cap if market_cap_min_m is None else market_cap_min_m
vol_mcap_max = self.vol_mcap if vol_mcap_max is None else vol_mcap_max
only_cpt = self.only_cpt if only_cpt is None else only_cpt
notices_ignore = self.notices_ignore if notices_ignore is None else notices_ignore
tags = self.tags if tags is None else tags
active_only = False if active_only is None else active_only
quote_whitelist = {q.upper() for q in quote_filter} if quote_filter else None
approved = set()
ignored = set()
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_whitelist and quote not in quote_whitelist:
continue
coin = (record.get("coin") or "").upper()
if not coin:
symbol = record.get("symbol") or ""
coin = compute_coin_name(symbol, quote)
if not coin:
continue
coin = coin.upper()
market_cap = float(record.get("market_cap") or 0)
volume_24h = float(record.get("volume_24h") or 0)
vol_mcap = volume_24h / market_cap if market_cap > 0 else 0.0
has_notice = bool(record.get("notice"))
is_cpt = bool(record.get("copy_trading", False))
record_tags = record.get("tags") or []
is_eligible = self._passes_active_filter(exchange, record)
passes = (
(not active_only or is_eligible)
and market_cap >= float(market_cap_min_m) * 1_000_000
and vol_mcap < float(vol_mcap_max)
and (not only_cpt or is_cpt)
and (not notices_ignore or not has_notice)
and (not tags or any(tag in record_tags for tag in tags))
)
if passes:
approved.add(coin)
else:
ignored.add(coin)
ignored -= approved
return sorted(approved), sorted(ignored)
def get_mapping_tags(
self,
exchange: str,
quote_filter: list[str] | None = None,
use_cache: bool = True,
) -> list[str]:
"""Return sorted unique tags from mapping records for an exchange."""
if not exchange:
return []
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
quote_whitelist = {q.upper() for q in quote_filter} if quote_filter else None
tags = set()
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_whitelist and quote not in quote_whitelist:
continue
for tag in (record.get("tags") or []):
if tag:
tags.add(tag)
return sorted(tags)
def filter_mapping_rows(
self,
exchange: str,
market_cap_min_m: int | float | None = None,
vol_mcap_max: float | None = None,
only_cpt: bool | None = None,
notices_ignore: bool | None = None,
tags: list[str] | None = None,
active_only: bool | None = None,
quote_filter: list[str] | None = None,
use_cache: bool = True,
) -> list[dict]:
"""Filter mapping and return row dicts for table display.
Uses the same pass/fail logic as filter_mapping(), but returns records
(one per mapping row) enriched with derived display fields.
"""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
market_cap_min_m = self.market_cap if market_cap_min_m is None else market_cap_min_m
vol_mcap_max = self.vol_mcap if vol_mcap_max is None else vol_mcap_max
only_cpt = self.only_cpt if only_cpt is None else only_cpt
notices_ignore = self.notices_ignore if notices_ignore is None else notices_ignore
tags = self.tags if tags is None else tags
active_only = False if active_only is None else active_only
quote_whitelist = {q.upper() for q in quote_filter} if quote_filter else None
filtered_rows = []
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_whitelist and quote not in quote_whitelist:
continue
coin = (record.get("coin") or "").upper()
if not coin:
symbol = record.get("symbol") or ""
coin = compute_coin_name(symbol, quote)
if not coin:
continue
market_cap = float(record.get("market_cap") or 0)
volume_24h = float(record.get("volume_24h") or 0)
vol_mcap = volume_24h / market_cap if market_cap > 0 else 0.0
has_notice = bool(record.get("notice"))
is_cpt = bool(record.get("copy_trading", False))
record_tags = record.get("tags") or []
is_eligible = self._passes_active_filter(exchange, record)
passes = (
(not active_only or is_eligible)
and market_cap >= float(market_cap_min_m) * 1_000_000
and vol_mcap < float(vol_mcap_max)
and (not only_cpt or is_cpt)
and (not notices_ignore or not has_notice)
and (not tags or any(tag in record_tags for tag in tags))
)
if not passes:
continue
row = dict(record)
row["coin"] = coin.upper()
row["vol/mcap"] = vol_mcap
row["price"] = row.get("price_last")
filtered_rows.append(row)
filtered_rows.sort(key=lambda x: float(x.get("market_cap") or 0), reverse=True)
return filtered_rows
def filter_by_market_cap_mapping(
self,
exchange: str,
mc: int,
active_only: bool | None = None,
quote_filter: list[str] | None = None,
use_cache: bool = True,
) -> tuple[list[str], list[str]]:
"""Return (approved, ignored) using only an absolute market-cap threshold in USD."""
mapping = self.load_mapping(exchange=exchange, use_cache=use_cache)
active_only = False if active_only is None else active_only
quote_whitelist = {q.upper() for q in quote_filter} if quote_filter else None
approved = set()
ignored = set()
for record in mapping:
quote = (record.get("quote") or "").upper()
if quote_whitelist and quote not in quote_whitelist:
continue
if active_only and not self._passes_active_filter(exchange, record):
continue
coin = (record.get("coin") or "").upper()
if not coin:
symbol = record.get("symbol") or ""
coin = compute_coin_name(symbol, quote)
if not coin:
continue
coin = coin.upper()
market_cap = float(record.get("market_cap") or 0)
if market_cap > float(mc):
approved.add(coin)
else:
ignored.add(coin)
ignored -= approved
return sorted(approved), sorted(ignored)
def load_copy_trading_symbols(self, exchange: str) -> list:
"""Load cached copy trading symbols for an exchange."""
if exchange in self._copy_trading_cache:
return self._copy_trading_cache[exchange]
cpt_file = self._get_exchange_dir(exchange) / "copy_trading.json"
if not cpt_file.exists():
return []
try:
symbols = _read_json_with_retry(cpt_file, retries=1, delay_s=0.2)
if isinstance(symbols, list):
self._copy_trading_cache[exchange] = symbols
return symbols
_log('PBCoinData', f'Copy trading cache for {exchange} is not a list, ignoring cache file', level='WARNING')
return []
except Exception as e:
_log('PBCoinData', f'Error loading copy trading symbols for {exchange}: {e}', level='ERROR')
return []
def save_copy_trading_symbols(self, exchange: str, symbols: list):
"""Save copy trading symbols to cache."""
exchange_dir = self._ensure_exchange_dir(exchange)
cpt_file = exchange_dir / "copy_trading.json"
try:
temp_file = cpt_file.with_suffix('.json.tmp')
with temp_file.open('w') as f:
json.dump(sorted(symbols), f, indent=4)
temp_file.replace(cpt_file)
self._copy_trading_cache[exchange] = sorted(symbols)
_log('PBCoinData', f'Saved {len(symbols)} copy trading symbols for {exchange}', level='DEBUG')
except Exception as e:
_log('PBCoinData', f'Error saving copy trading symbols for {exchange}: {e}', level='ERROR')
if temp_file.exists():
temp_file.unlink()
def fetch_copy_trading_symbols(self, exchange_id: str, markets: dict = None) -> list:
"""Fetch copy trading symbols for an exchange.
Sources per exchange:
- bybit: CCXT market data (info.copyTrading == "both"), no auth needed
- binance: sapi copy trading endpoint (requires authenticated user)
- bitget: copy trading endpoint (requires authenticated user)
- others: no known copy trading API
For binance/bitget: remembers working user in pbgui.ini and tries
that user first on subsequent runs. Falls back to scanning all users
if the remembered user no longer works.
Args:
exchange_id: Exchange identifier
markets: Pre-loaded CCXT markets dict (used for bybit to avoid re-fetch)
Returns:
List of market IDs (exchange format, e.g. "BTCUSDT")
"""
cpt_symbols = []
try:
if exchange_id == 'bybit':
# bybit: copy trading info is in CCXT market data
if not markets:
markets = self.load_ccxt_markets(exchange_id)
if not markets:
_log('PBCoinData', f'No markets available for bybit copy trading detection', level='WARNING')
return []
for symbol, market in markets.items():
if not market.get("swap", False) or not market.get("active", True):
continue
if not market.get("linear", False):
continue
info = market.get("info", {})
if info.get("copyTrading") == "both":
market_id = market.get("id", "")
if market_id:
cpt_symbols.append(market_id)
_log('PBCoinData', f'Found {len(cpt_symbols)} copy trading symbols for bybit (from market data)', level='INFO')
elif exchange_id in ('binance', 'bitget'):
cpt_symbols = self._fetch_cpt_with_user_discovery(exchange_id)
else:
# No copy trading API known for this exchange
_log('PBCoinData', f'No copy trading API for {exchange_id}', level='DEBUG')
# Cache the result
if cpt_symbols:
self.save_copy_trading_symbols(exchange_id, cpt_symbols)
except Exception as e:
_log('PBCoinData', f'Error fetching copy trading symbols for {exchange_id}: {e}', level='ERROR')