-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinance_trading_v3_9.py
More file actions
2834 lines (2421 loc) · 112 KB
/
binance_trading_v3_9.py
File metadata and controls
2834 lines (2421 loc) · 112 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Binance Trading Tools v3.9.0
# Copyright (c) 2026 David Ramirez Chiappe
#
# Este archivo forma parte del proyecto Binance Trading Tools.
# Distribuido bajo la licencia MIT.
#
# Se permite su uso, copia, modificación, publicación, distribución
# y sublicenciamiento, conforme a los términos de la licencia MIT.
#
# Consulta el archivo LICENSE en la raíz del proyecto para el texto completo.
# Este software se proporciona "tal cual", sin garantías de ningún tipo.
"""
Binance Trading Tools v3.9
Novedades:
- Mejora significativa en el ranking: ahora penaliza activamente estados "degradado" e "invalido"
- Incorpora pullback_quality en el cálculo del score
- Incorpora rr_estructural_preliminar en el score (premia buen riesgo/recompensa)
- Nuevo filtro --only-vigent para mostrar solo activos con setup "vigente"
- Nuevo score_final que combina score base con multiplicador por calidad del setup
- Ranking más preciso y alineado con la verdadera operabilidad de cada activo
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import hmac
import json
import os
import sys
from datetime import datetime, timezone
from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
PUBLIC_BASE = "https://data-api.binance.vision"
PRIVATE_BASE = "https://api.binance.com"
EPS = 1e-12
# =========================
# Utilidades generales
# =========================
def now_utc_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def http_get_json(
base_url: str,
path: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
timeout: int = 20,
) -> Any:
params = params or {}
headers = headers or {}
query = urlencode(params, doseq=True)
url = f"{base_url}{path}"
if query:
url = f"{url}?{query}"
req = Request(url, headers=headers, method="GET")
try:
with urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw)
except HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"HTTP {e.code} al consultar {url}\n{body}") from e
except URLError as e:
raise RuntimeError(f"Error de red al consultar {url}: {e}") from e
def get_server_time_ms() -> int:
data = http_get_json(PRIVATE_BASE, "/api/v3/time")
return int(data["serverTime"])
def signed_get_json(
path: str,
api_key: str,
api_secret: str,
params: Optional[Dict[str, Any]] = None,
timeout: int = 20,
) -> Any:
params = params.copy() if params else {}
params["timestamp"] = get_server_time_ms()
params["recvWindow"] = 10000
query = urlencode(params, doseq=True)
signature = hmac.new(
api_secret.encode("utf-8"),
query.encode("utf-8"),
hashlib.sha256,
).hexdigest()
url = f"{PRIVATE_BASE}{path}?{query}&signature={signature}"
req = Request(url, headers={"X-MBX-APIKEY": api_key}, method="GET")
try:
with urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw)
except HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"HTTP {e.code} al consultar {url}\n{body}") from e
except URLError as e:
raise RuntimeError(f"Error de red al consultar {url}: {e}") from e
def safe_float(value: Any) -> Optional[float]:
if value is None:
return None
try:
return float(value)
except Exception:
return None
def to_decimal(value: Any) -> Decimal:
return Decimal(str(value))
def normalize_number_str(value: Any, decimals: Optional[int] = None) -> Optional[str]:
if value is None:
return None
try:
d = Decimal(str(value))
if decimals is not None:
q = Decimal("1").scaleb(-decimals)
d = d.quantize(q, rounding=ROUND_HALF_UP)
s = format(d, "f")
return s.rstrip("0").rstrip(".") or "0"
except Exception:
return str(value)
def pct_change(a: Optional[float], b: Optional[float]) -> Optional[float]:
if a is None or b is None or abs(b) <= EPS:
return None
return ((a / b) - 1.0) * 100.0
def save_csv(filepath: Path, rows: List[Dict[str, Any]]) -> None:
if not rows:
return
with filepath.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
def write_json(filepath: Path, payload: Dict[str, Any]) -> None:
with filepath.open("w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
def write_text(filepath: Path, content: str) -> None:
with filepath.open("w", encoding="utf-8") as f:
f.write(content)
def extract_assets(symbol: str, quote_asset: str = "USDT") -> Dict[str, str]:
if not symbol.endswith(quote_asset):
return {"base_asset": symbol, "quote_asset": quote_asset}
return {"base_asset": symbol[: -len(quote_asset)], "quote_asset": quote_asset}
def moving_average(values: List[float], period: int) -> Optional[float]:
if len(values) < period:
return None
return sum(values[-period:]) / period
def true_range(curr: Dict[str, Any], prev_close: Optional[float]) -> float:
high = float(curr["high"])
low = float(curr["low"])
if prev_close is None:
return high - low
return max(high - low, abs(high - prev_close), abs(low - prev_close))
def average_true_range(candles: List[Dict[str, Any]], period: int = 14) -> Optional[float]:
if len(candles) < period + 1:
return None
trs: List[float] = []
prev_close = None
for candle in candles:
trs.append(true_range(candle, prev_close))
prev_close = float(candle["close"])
if len(trs) < period:
return None
return sum(trs[-period:]) / period
def slope_pct(values: List[float], period: int) -> Optional[float]:
if len(values) < period + 1:
return None
base = values[-period - 1]
curr = values[-1]
if abs(base) <= EPS:
return None
return ((curr / base) - 1.0) * 100.0
def find_last_swing_low(candles: List[Dict[str, Any]], left: int = 2, right: int = 2) -> Optional[float]:
if len(candles) < left + right + 1:
return None
lows = [float(c["low"]) for c in candles]
last_idx = None
for i in range(left, len(lows) - right):
center = lows[i]
if all(center < lows[j] for j in range(i - left, i)) and all(center <= lows[j] for j in range(i + 1, i + right + 1)):
last_idx = i
return lows[last_idx] if last_idx is not None else None
def find_last_swing_high(candles: List[Dict[str, Any]], left: int = 2, right: int = 2) -> Optional[float]:
if len(candles) < left + right + 1:
return None
highs = [float(c["high"]) for c in candles]
last_idx = None
for i in range(left, len(highs) - right):
center = highs[i]
if all(center > highs[j] for j in range(i - left, i)) and all(center >= highs[j] for j in range(i + 1, i + right + 1)):
last_idx = i
return highs[last_idx] if last_idx is not None else None
def candidate_price_key(value: float, tick_size: Optional[str]) -> str:
formatted = format_price(value, tick_size)
return formatted if formatted is not None else normalize_number_str(value, 8) or str(value)
def dedupe_candidates(
candidates: List[Dict[str, Any]],
tick_size: Optional[str],
) -> List[Dict[str, Any]]:
grouped: Dict[str, Dict[str, Any]] = {}
for c in candidates:
key = candidate_price_key(float(c["value"]), tick_size)
existing = grouped.get(key)
if existing is None:
clone = dict(c)
clone["aliases"] = [c["name"]]
grouped[key] = clone
continue
existing["aliases"] = sorted(set(existing.get("aliases", []) + [c["name"]]))
if c["score"] > existing["score"] or (
c["score"] == existing["score"] and c["distance_pct"] > existing["distance_pct"]
):
keep_aliases = existing["aliases"]
grouped[key] = dict(c)
grouped[key]["aliases"] = keep_aliases
return list(grouped.values())
def pick_best_by_names(
candidates: List[Dict[str, Any]],
preferred_names: List[str],
used_names: Optional[set] = None,
) -> Optional[Dict[str, Any]]:
used_names = used_names or set()
valid = [c for c in candidates if c["name"] not in used_names]
for name in preferred_names:
matches = [c for c in valid if c["name"] == name]
if matches:
return sorted(matches, key=lambda x: (-x["score"], x["distance_pct"], x["value"]))[0]
return None
def pick_distinct_candidate(
candidates: List[Dict[str, Any]],
used_names: set,
min_distance_pct: Optional[float] = None,
prefer_farthest: bool = False,
) -> Optional[Dict[str, Any]]:
valid = [c for c in candidates if c["name"] not in used_names]
if min_distance_pct is not None:
valid = [c for c in valid if c["distance_pct"] >= min_distance_pct]
if not valid:
return None
if prefer_farthest:
valid = sorted(valid, key=lambda x: (x["distance_pct"], x["score"], -x["value"]), reverse=True)
else:
valid = sorted(valid, key=lambda x: (-x["score"], x["distance_pct"], x["value"]))
return valid[0]
def level_separation_pct(last_price: Optional[float], atr1: Optional[float], tick_size: Optional[str]) -> float:
atr_component = 0.0
if last_price is not None and atr1 is not None and atr1 > EPS and last_price > EPS:
atr_component = (atr1 / last_price) * 100.0 * 0.25
tick_component = 0.0
if last_price is not None and last_price > EPS and tick_size not in (None, '', '0', '0.0'):
try:
tick_component = (float(tick_size) / last_price) * 100.0 * 6.0
except Exception:
tick_component = 0.0
return max(0.12, atr_component, tick_component)
def candidate_pref_index(name: str, preferred_names: List[str]) -> int:
try:
return preferred_names.index(name)
except ValueError:
return len(preferred_names) + 10
def pick_entry_with_constraints(
candidates: List[Dict[str, Any]],
preferred_names: List[str],
tick_size: Optional[str],
min_distance_pct: Optional[float] = None,
max_distance_pct: Optional[float] = None,
min_gap_from: Optional[List[Tuple[float, str]]] = None,
used_price_keys: Optional[set] = None,
mode: str = 'balanced',
) -> Optional[Dict[str, Any]]:
used_price_keys = used_price_keys or set()
min_gap_from = min_gap_from or []
valid: List[Dict[str, Any]] = []
for c in candidates:
if min_distance_pct is not None and c['distance_pct'] < min_distance_pct:
continue
if max_distance_pct is not None and c['distance_pct'] > max_distance_pct:
continue
price_key = candidate_price_key(float(c['value']), tick_size)
if price_key in used_price_keys:
continue
ok = True
for ref_dist, gap in min_gap_from:
if c['distance_pct'] < ref_dist + gap:
ok = False
break
if ok:
valid.append(c)
if not valid:
return None
def sort_key(c: Dict[str, Any]):
pref = candidate_pref_index(c['name'], preferred_names)
if mode == 'nearest':
return (pref, c['distance_pct'], -c['score'], c['value'])
if mode == 'deep':
return (pref, -c['distance_pct'], -c['score'], c['value'])
return (pref, abs(c['distance_pct'] - 2.0), -c['score'], c['value'])
valid = sorted(valid, key=sort_key)
return valid[0]
def decimal_places_from_step(step: Optional[str]) -> Optional[int]:
if not step or step in ("0", "0.0"):
return None
try:
d = Decimal(str(step)).normalize()
exp = d.as_tuple().exponent
return max(0, -exp)
except Exception:
return None
def format_with_step(value: Any, step: Optional[str], rounding=ROUND_HALF_UP) -> Optional[str]:
if value is None:
return None
if not step or step in ("0", "0.0"):
return normalize_number_str(value, 8)
try:
d = Decimal(str(value))
q = Decimal(str(step))
d = d.quantize(q, rounding=rounding)
s = format(d, "f")
return s.rstrip("0").rstrip(".") or "0"
except (InvalidOperation, ValueError):
return normalize_number_str(value, 8)
def format_price(value: Any, tick_size: Optional[str]) -> Optional[str]:
return format_with_step(value, tick_size, rounding=ROUND_HALF_UP)
def format_qty(value: Any, step_size: Optional[str]) -> Optional[str]:
return format_with_step(value, step_size, rounding=ROUND_DOWN)
def format_quote(value: Any, decimals: int = 6) -> Optional[str]:
return normalize_number_str(value, decimals)
def format_pct(value: Any, decimals: int = 4) -> Optional[str]:
return normalize_number_str(value, decimals)
def floor_to_step(value: float, step: Optional[str]) -> Optional[str]:
if value is None:
return None
if step in (None, "", "0", "0.0"):
return normalize_number_str(value, 8)
v = to_decimal(value)
s = to_decimal(step)
floored = (v / s).to_integral_value(rounding=ROUND_DOWN) * s
return format(floored, "f").rstrip("0").rstrip(".") or "0"
# =========================
# Progreso visual en consola
# =========================
def render_progress_bar(current: int, total: int, width: int = 20) -> str:
if total <= 0:
total = 1
ratio = max(0.0, min(1.0, current / total))
filled = int(round(ratio * width))
return f"[{'#' * filled}{'.' * (width - filled)}] {int(ratio * 100):>3}%"
def print_progress_header(total: int) -> None:
print(f"Iniciando análisis de {total} par(es)...", flush=True)
def print_symbol_progress(index: int, total: int, symbol: str, stage: str) -> None:
bar = render_progress_bar(index, total)
print(f"{bar} | Analizando {symbol} ({index}/{total}) | {stage}", flush=True)
def print_symbol_done(index: int, total: int, symbol: str, status: str = 'OK') -> None:
bar = render_progress_bar(index, total)
print(f"{bar} | {symbol} -> {status}", flush=True)
# =========================
# Lectura de .env
# =========================
def load_dotenv_file(env_path: Path) -> Dict[str, str]:
values: Dict[str, str] = {}
if not env_path.exists():
return values
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if len(value) >= 2 and (
(value.startswith('"') and value.endswith('"')) or
(value.startswith("'") and value.endswith("'"))
):
value = value[1:-1]
values[key] = value
return values
def resolve_binance_credentials(env_file_arg: Optional[str]) -> Tuple[str, str, str]:
env_key = os.getenv("BINANCE_API_KEY", "").strip()
env_secret = os.getenv("BINANCE_API_SECRET", "").strip()
if env_key and env_secret:
return env_key, env_secret, "variables_de_entorno"
candidate_paths: List[Path] = []
if env_file_arg:
candidate_paths.append(Path(env_file_arg).expanduser().resolve())
script_dir = Path(__file__).resolve().parent
candidate_paths.append(script_dir / ".env")
candidate_paths.append(Path.cwd() / ".env")
seen = set()
unique_paths: List[Path] = []
for p in candidate_paths:
p_str = str(p)
if p_str not in seen:
seen.add(p_str)
unique_paths.append(p)
for path in unique_paths:
data = load_dotenv_file(path)
key = data.get("BINANCE_API_KEY", "").strip()
secret = data.get("BINANCE_API_SECRET", "").strip()
if key and secret:
return key, secret, f"archivo_env:{path}"
return "", "", "no_encontrado"
# =========================
# Klines y resúmenes
# =========================
def parse_klines(raw_klines: List[List[Any]]) -> List[Dict[str, Any]]:
rows: List[Dict[str, Any]] = []
for k in raw_klines:
rows.append(
{
"open_time_ms": int(k[0]),
"open_time_utc": datetime.fromtimestamp(int(k[0]) / 1000, tz=timezone.utc).isoformat(),
"open": float(k[1]),
"high": float(k[2]),
"low": float(k[3]),
"close": float(k[4]),
"volume": float(k[5]),
"close_time_ms": int(k[6]),
"close_time_utc": datetime.fromtimestamp(int(k[6]) / 1000, tz=timezone.utc).isoformat(),
"quote_asset_volume": float(k[7]),
"number_of_trades": int(k[8]),
"taker_buy_base_volume": float(k[9]),
"taker_buy_quote_volume": float(k[10]),
}
)
return rows
def is_support_reliable(price_level: float, candles: List[Dict[str, Any]], volume_threshold: float = 10000) -> bool:
"""Verifica si el nivel de soporte ha sido validado por volumen significativo en las últimas velas."""
if not candles or price_level <= EPS:
return True
check_candles = candles[-20:] if len(candles) >= 20 else candles
touches = 0
for candle in check_candles:
low = candle.get("low")
volume = candle.get("volume", 0)
if low is None:
continue
if abs(low - price_level) / price_level < 0.01:
if volume > volume_threshold:
touches += 1
return touches >= 2
def timeframe_summary(
candles: List[Dict[str, Any]],
recent_window: int = 20,
absolute_window: Optional[int] = None,
atr_period: int = 14,
volume_threshold: float = 10000,
) -> Dict[str, Any]:
closes = [float(c["close"]) for c in candles]
recent = candles[-recent_window:] if len(candles) >= recent_window else candles
absolute = candles[-absolute_window:] if absolute_window and len(candles) >= absolute_window else candles
last_close = closes[-1] if closes else None
ma7 = moving_average(closes, 7)
ma25 = moving_average(closes, 25)
ma99 = moving_average(closes, 99)
atr14 = average_true_range(candles, atr_period)
last_swing_low = find_last_swing_low(candles[-max(recent_window * 2, 12):]) if candles else None
last_swing_high = find_last_swing_high(candles[-max(recent_window * 2, 12):]) if candles else None
ma7_slope_pct_5 = slope_pct([v for v in closes if v is not None], 5) if closes else None
zone_candidates = [
("ma25", ma25),
("ma99", ma99),
("recent_low", min(float(c["low"]) for c in recent) if recent else None),
("swing_low", last_swing_low),
]
zone_values = []
for name, value in zone_candidates:
if value is not None and last_close is not None and value <= last_close:
if is_support_reliable(value, candles, volume_threshold):
zone_values.append(value)
support_zone = None
if zone_values:
support_zone = {
"low": min(zone_values),
"high": max(zone_values),
}
return {
"candles_count": len(candles),
"recent_window": recent_window,
"absolute_window": absolute_window or len(candles),
"atr_period": atr_period,
"last_open_time_utc": candles[-1]["open_time_utc"] if candles else None,
"last_close": last_close,
"last_high": candles[-1]["high"] if candles else None,
"last_low": candles[-1]["low"] if candles else None,
"last_volume": candles[-1]["volume"] if candles else None,
"ma7": ma7,
"ma25": ma25,
"ma99": ma99,
"ma7_slope_pct_5": ma7_slope_pct_5,
"atr14": atr14,
"recent_high": max(float(c["high"]) for c in recent) if recent else None,
"recent_low": min(float(c["low"]) for c in recent) if recent else None,
"absolute_high": max(float(c["high"]) for c in absolute) if absolute else None,
"absolute_low": min(float(c["low"]) for c in absolute) if absolute else None,
"last_swing_low": last_swing_low,
"last_swing_high": last_swing_high,
"swing_low_definition": {"left": 2, "right": 2, "method": "pivot_low"},
"swing_high_definition": {"left": 2, "right": 2, "method": "pivot_high"},
"support_zone": support_zone,
"dist_pct_vs_ma7": pct_change(last_close, ma7),
"dist_pct_vs_ma25": pct_change(last_close, ma25),
"dist_pct_vs_ma99": pct_change(last_close, ma99),
"atr_pct_of_price": pct_change((last_close + atr14) if last_close is not None and atr14 is not None else None, last_close),
}
# =========================
# Exchange info y profundidad
# =========================
def extract_symbol_filters(exchange_info: Dict[str, Any], symbol: str) -> Dict[str, Any]:
symbols = exchange_info.get("symbols", [])
match = next((s for s in symbols if s.get("symbol") == symbol), None)
if not match:
return {}
filters = {f["filterType"]: f for f in match.get("filters", []) if "filterType" in f}
out = {
"symbol": match.get("symbol"),
"status": match.get("status"),
"baseAsset": match.get("baseAsset"),
"quoteAsset": match.get("quoteAsset"),
"baseAssetPrecision": match.get("baseAssetPrecision"),
"quotePrecision": match.get("quotePrecision"),
"permissions": match.get("permissions", []),
"allowTrailingStop": match.get("allowTrailingStop"),
"cancelReplaceAllowed": match.get("cancelReplaceAllowed"),
"filters": {},
}
wanted = [
"PRICE_FILTER",
"LOT_SIZE",
"MARKET_LOT_SIZE",
"NOTIONAL",
"MAX_NUM_ORDERS",
"MAX_NUM_ALGO_ORDERS",
"TRAILING_DELTA",
]
for name in wanted:
if name in filters:
out["filters"][name] = filters[name]
price_filter = filters.get("PRICE_FILTER", {})
lot_size = filters.get("LOT_SIZE", {})
market_lot_size = filters.get("MARKET_LOT_SIZE", {})
notional = filters.get("NOTIONAL", {})
out["rules_short"] = {
"tickSize": price_filter.get("tickSize"),
"minPrice": price_filter.get("minPrice"),
"maxPrice": price_filter.get("maxPrice"),
"stepSize": lot_size.get("stepSize"),
"minQty": lot_size.get("minQty"),
"maxQty": lot_size.get("maxQty"),
"marketStepSize": market_lot_size.get("stepSize"),
"marketMinQty": market_lot_size.get("minQty"),
"marketMaxQty": market_lot_size.get("maxQty"),
"minNotional": notional.get("minNotional"),
"maxNotional": notional.get("maxNotional"),
"maxNumOrders": (filters.get("MAX_NUM_ORDERS") or {}).get("maxNumOrders"),
"maxNumAlgoOrders": (filters.get("MAX_NUM_ALGO_ORDERS") or {}).get("maxNumAlgoOrders"),
}
return out
def depth_summary(depth: Dict[str, Any], levels: int = 10) -> Dict[str, Any]:
bids = depth.get("bids", [])[:levels]
asks = depth.get("asks", [])[:levels]
def sum_notional(rows: List[List[str]]) -> float:
total = 0.0
for price, qty in rows:
total += float(price) * float(qty)
return total
best_bid = float(bids[0][0]) if bids else None
best_ask = float(asks[0][0]) if asks else None
spread_abs = (best_ask - best_bid) if best_bid is not None and best_ask is not None else None
spread_pct = (spread_abs / best_bid * 100.0) if spread_abs is not None and best_bid else None
bid_notional = sum_notional(bids)
ask_notional = sum_notional(asks)
return {
"best_bid": best_bid,
"best_ask": best_ask,
"spread_abs": spread_abs,
"spread_pct": spread_pct,
"bid_notional_top10": bid_notional,
"ask_notional_top10": ask_notional,
"min_side_notional_top10": min(bid_notional, ask_notional) if bids and asks else None,
"bids": bids,
"asks": asks,
}
# =========================
# Datos públicos por símbolo
# =========================
def fetch_public_market_data(symbol: str, limit: int) -> Dict[str, Any]:
ticker = http_get_json(PUBLIC_BASE, "/api/v3/ticker/24hr", params={"symbol": symbol})
depth = http_get_json(PUBLIC_BASE, "/api/v3/depth", params={"symbol": symbol, "limit": 20})
exchange_info = http_get_json(PUBLIC_BASE, "/api/v3/exchangeInfo", params={"symbol": symbol})
raw_tfs = {
"15m": http_get_json(PUBLIC_BASE, "/api/v3/klines", params={"symbol": symbol, "interval": "15m", "limit": limit}),
"1h": http_get_json(PUBLIC_BASE, "/api/v3/klines", params={"symbol": symbol, "interval": "1h", "limit": limit}),
"4h": http_get_json(PUBLIC_BASE, "/api/v3/klines", params={"symbol": symbol, "interval": "4h", "limit": limit}),
}
csv_rows: Dict[str, List[Dict[str, Any]]] = {}
tf_summary: Dict[str, Any] = {}
for tf, raw in raw_tfs.items():
parsed = parse_klines(raw)
csv_rows[tf] = parsed
tf_summary[tf] = timeframe_summary(parsed, recent_window=20, absolute_window=min(len(parsed), limit), atr_period=14)
return {
"ticker": ticker,
"depth_summary": depth_summary(depth, levels=10),
"symbol_info": extract_symbol_filters(exchange_info, symbol),
"csv_rows": csv_rows,
"timeframes": tf_summary,
}
# =========================
# Datos privados
# =========================
def fetch_private_data(
symbol: str,
base_asset: str,
quote_asset: str,
api_key: str,
api_secret: str,
trades_limit: int,
) -> Dict[str, Any]:
account = signed_get_json(
"/api/v3/account",
api_key,
api_secret,
params={"omitZeroBalances": "true"},
)
balances_map: Dict[str, Dict[str, str]] = {}
for b in account.get("balances", []):
if b["asset"] in {base_asset, quote_asset}:
free_val = float(b["free"])
locked_val = float(b["locked"])
balances_map[b["asset"]] = {
"free": b["free"],
"locked": b["locked"],
"total": normalize_number_str(free_val + locked_val, 8),
}
recent_trades_raw = signed_get_json(
"/api/v3/myTrades",
api_key,
api_secret,
params={"symbol": symbol, "limit": trades_limit},
)
open_orders_raw = signed_get_json(
"/api/v3/openOrders",
api_key,
api_secret,
params={"symbol": symbol},
)
open_order_lists_raw = signed_get_json(
"/api/v3/openOrderList",
api_key,
api_secret,
)
recent_trades: List[Dict[str, Any]] = []
for t in recent_trades_raw:
recent_trades.append(
{
"id": t["id"],
"orderId": t["orderId"],
"price": t["price"],
"qty": t["qty"],
"quoteQty": t["quoteQty"],
"commission": t["commission"],
"commissionAsset": t["commissionAsset"],
"isBuyer": t["isBuyer"],
"isMaker": t["isMaker"],
"time_ms": t["time"],
"time_utc": datetime.fromtimestamp(t["time"] / 1000, tz=timezone.utc).isoformat(),
}
)
open_orders: List[Dict[str, Any]] = []
for o in open_orders_raw:
open_orders.append(
{
"symbol": o.get("symbol"),
"orderId": o.get("orderId"),
"orderListId": o.get("orderListId"),
"clientOrderId": o.get("clientOrderId"),
"price": o.get("price"),
"origQty": o.get("origQty"),
"executedQty": o.get("executedQty"),
"status": o.get("status"),
"type": o.get("type"),
"side": o.get("side"),
"stopPrice": o.get("stopPrice"),
"timeInForce": o.get("timeInForce"),
"workingTime": o.get("workingTime"),
}
)
open_order_lists: List[Dict[str, Any]] = []
for ol in open_order_lists_raw:
if ol.get("symbol") != symbol:
continue
open_order_lists.append(ol)
return {
"account_flags": {
"makerCommission": account.get("makerCommission"),
"takerCommission": account.get("takerCommission"),
"buyerCommission": account.get("buyerCommission"),
"sellerCommission": account.get("sellerCommission"),
"canTrade": account.get("canTrade"),
"requireSelfTradePrevention": account.get("requireSelfTradePrevention"),
"updateTime": account.get("updateTime"),
},
"balances": balances_map,
"recent_trades": recent_trades,
"open_orders": open_orders,
"open_order_lists": open_order_lists,
}
def summarize_trades(recent_trades: List[Dict[str, Any]]) -> Dict[str, Any]:
if not recent_trades:
return {}
ordered = sorted(recent_trades, key=lambda x: x["time_ms"])
last_trade = ordered[-1]
last_buy = next((t for t in reversed(ordered) if t["isBuyer"]), None)
last_sell = next((t for t in reversed(ordered) if not t["isBuyer"]), None)
buy_quote = sum(float(t["quoteQty"]) for t in ordered if t["isBuyer"])
sell_quote = sum(float(t["quoteQty"]) for t in ordered if not t["isBuyer"])
buy_qty = sum(float(t["qty"]) for t in ordered if t["isBuyer"])
sell_qty = sum(float(t["qty"]) for t in ordered if not t["isBuyer"])
return {
"last_trade": last_trade,
"last_buy": last_buy,
"last_sell": last_sell,
"recent_aggregate": {
"buy_qty": normalize_number_str(buy_qty, 8),
"sell_qty": normalize_number_str(sell_qty, 8),
"buy_quote": normalize_number_str(buy_quote, 8),
"sell_quote": normalize_number_str(sell_quote, 8),
"net_qty": normalize_number_str(buy_qty - sell_qty, 8),
"net_quote_flow": normalize_number_str(sell_quote - buy_quote, 8),
},
}
def estimate_position_from_recent_trades(current_qty: float, recent_trades: List[Dict[str, Any]]) -> Dict[str, Any]:
if current_qty <= EPS:
return {
"current_qty": 0.0,
"estimated_avg_entry": None,
"covered_qty": 0.0,
"missing_qty": 0.0,
"warning": "Sin posición base actual.",
"method": "recent-trades-backward-estimate",
"lots_used": [],
}
ordered_desc = sorted(recent_trades, key=lambda x: x["time_ms"], reverse=True)
target_qty = current_qty
lots: List[Dict[str, Any]] = []
for t in ordered_desc:
qty = float(t["qty"])
price = float(t["price"])
if t["isBuyer"]:
alloc = min(qty, target_qty)
if alloc > EPS:
lots.append(
{
"trade_id": t["id"],
"orderId": t["orderId"],
"time_utc": t["time_utc"],
"qty_used": normalize_number_str(alloc, 8),
"price": normalize_number_str(price, 8),
}
)
target_qty -= alloc
if target_qty <= EPS:
break
else:
target_qty += qty
covered_qty = sum(float(l["qty_used"]) for l in lots)
avg_entry = None
if covered_qty > EPS:
total_cost = sum(float(l["qty_used"]) * float(l["price"]) for l in lots)
avg_entry = total_cost / covered_qty
warning = None
missing = max(0.0, current_qty - covered_qty)
if missing > EPS:
warning = (
"El historial reciente no alcanzó para reconstruir toda la posición actual. "
"Usa --precio / --inversion si quieres un snapshot más exacto."
)
return {
"current_qty": normalize_number_str(current_qty, 8),
"estimated_avg_entry": normalize_number_str(avg_entry, 8),
"covered_qty": normalize_number_str(covered_qty, 8),
"missing_qty": normalize_number_str(missing, 8),
"warning": warning,
"method": "recent-trades-backward-estimate",
"lots_used": list(reversed(lots)),
}
def summarize_open_oco(open_order_lists: List[Dict[str, Any]], open_orders: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
out = []
open_orders = open_orders or []
by_list_id: Dict[Any, List[Dict[str, Any]]] = {}
for o in open_orders:
by_list_id.setdefault(o.get("orderListId"), []).append(o)
for ol in open_order_lists:
orders = ol.get("orders", [])
reports = ol.get("orderReports", [])
summary = {
"orderListId": ol.get("orderListId"),
"contingencyType": ol.get("contingencyType"),
"listStatusType": ol.get("listStatusType"),
"listOrderStatus": ol.get("listOrderStatus"),
"listClientOrderId": ol.get("listClientOrderId"),
"transactionTime": ol.get("transactionTime"),
"symbol": ol.get("symbol"),
"legs": [],
"orders": orders,
}
if reports:
for r in reports:
summary["legs"].append(
{
"orderId": r.get("orderId"),
"type": r.get("type"),
"side": r.get("side"),
"price": r.get("price"),
"stopPrice": r.get("stopPrice"),
"origQty": r.get("origQty"),
"executedQty": r.get("executedQty"),
"status": r.get("status"),
}
)
else:
list_id = ol.get("orderListId")
for o in by_list_id.get(list_id, []):
summary["legs"].append(
{
"orderId": o.get("orderId"),
"type": o.get("type"),
"side": o.get("side"),
"price": o.get("price"),