-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinance_trading_v3_1.py
More file actions
1490 lines (1268 loc) · 55.6 KB
/
binance_trading_v3_1.py
File metadata and controls
1490 lines (1268 loc) · 55.6 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.1
# 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.
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
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 normalize_number_str(value: Any, decimals: Optional[int] = None) -> Optional[str]:
if value is None:
return None
try:
if decimals is None:
d = Decimal(str(value))
s = format(d, "f")
return s.rstrip("0").rstrip(".") or "0"
return f"{float(value):.{decimals}f}".rstrip("0").rstrip(".") or "0"
except Exception:
return str(value)
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 floor_to_step(value: float, step: Optional[str]) -> Optional[str]:
if value is None or step in (None, "", "0", "0.0"):
return normalize_number_str(value)
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"
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 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
# =========================
# 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 timeframe_summary(candles: List[Dict[str, Any]], recent_window: int = 20) -> Dict[str, Any]:
closes = [c["close"] for c in candles]
recent = candles[-recent_window:] if len(candles) >= recent_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)
return {
"candles_count": len(candles),
"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,
"recent_high": max(c["high"] for c in recent) if recent else None,
"recent_low": min(c["low"] for c in recent) if recent else None,
"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),
}
# =========================
# 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",
"MIN_NOTIONAL",
"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", {})
min_notional = filters.get("MIN_NOTIONAL", {})
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": min_notional.get("minNotional") or 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)
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"),
"stopPrice": o.get("stopPrice"),
"origQty": o.get("origQty"),
"executedQty": o.get("executedQty"),
"status": o.get("status"),
}
)
out.append(summary)
return out
def build_position_snapshot(
symbol: str,
base_asset: str,
quote_asset: str,
ticker: Dict[str, Any],
private_data: Optional[Dict[str, Any]],
manual_entry_price: Optional[float],
manual_quote_size: Optional[float],
) -> Dict[str, Any]:
last_price = float(ticker["lastPrice"])
position: Dict[str, Any] = {
"symbol": symbol,
"base_asset": base_asset,
"quote_asset": quote_asset,
"last_price": normalize_number_str(last_price, 8),
"base_qty_total": None,
"quote_free": None,
"quote_locked": None,
"quote_total": None,
"entry_price": None,
"position_notional_quote": None,
"unrealized_pnl_quote": None,
"unrealized_pnl_pct": None,
"source": None,
"notes": [],
}
if not private_data:
if manual_entry_price is not None and manual_quote_size is not None:
base_qty = manual_quote_size / manual_entry_price
position.update(
{
"base_qty_total": normalize_number_str(base_qty, 8),
"entry_price": normalize_number_str(manual_entry_price, 8),
"position_notional_quote": normalize_number_str(base_qty * last_price, 8),
"unrealized_pnl_quote": normalize_number_str(base_qty * (last_price - manual_entry_price), 8),
"unrealized_pnl_pct": normalize_number_str(((last_price / manual_entry_price) - 1.0) * 100.0, 4),
"source": "manual",
}
)
position["notes"].append("Posición calculada desde --precio y --inversion.")
else:
position["notes"].append("Sin datos privados ni parámetros manuales; no se pudo construir la posición.")
return position
balances = private_data.get("balances", {})
base_balance = balances.get(base_asset, {"free": "0", "locked": "0", "total": "0"})
quote_balance = balances.get(quote_asset, {"free": "0", "locked": "0", "total": "0"})
base_qty_total = float(base_balance.get("total", "0") or 0.0)
position["base_qty_total"] = normalize_number_str(base_qty_total, 8)
position["quote_free"] = quote_balance.get("free")
position["quote_locked"] = quote_balance.get("locked")
position["quote_total"] = quote_balance.get("total")
trade_summary = summarize_trades(private_data.get("recent_trades", []))
estimate = estimate_position_from_recent_trades(base_qty_total, private_data.get("recent_trades", []))
position["trade_summary"] = trade_summary
position["estimate"] = estimate
chosen_entry: Optional[float] = None
source = None
if manual_entry_price is not None:
chosen_entry = manual_entry_price
source = "manual"
position["notes"].append("Se priorizó --precio sobre la estimación automática.")
elif estimate.get("estimated_avg_entry") is not None:
chosen_entry = float(estimate["estimated_avg_entry"])
source = "estimado_desde_trades"
if estimate.get("warning"):
position["notes"].append(estimate["warning"])
elif trade_summary.get("last_buy"):
chosen_entry = float(trade_summary["last_buy"]["price"])
source = "ultimo_buy_fallback"
position["notes"].append("No se pudo estimar promedio; se usó el último BUY como fallback.")
if chosen_entry is not None and base_qty_total > EPS:
pnl_quote = base_qty_total * (last_price - chosen_entry)
pnl_pct = ((last_price / chosen_entry) - 1.0) * 100.0 if chosen_entry > EPS else None
position["entry_price"] = normalize_number_str(chosen_entry, 8)
position["position_notional_quote"] = normalize_number_str(base_qty_total * last_price, 8)
position["unrealized_pnl_quote"] = normalize_number_str(pnl_quote, 8)
position["unrealized_pnl_pct"] = normalize_number_str(pnl_pct, 4)
position["source"] = source
if manual_quote_size is not None:
position["manual_quote_size"] = normalize_number_str(manual_quote_size, 8)
return position
# =========================
# Lógica de compra límite (mejorada)
# =========================
def suggest_limit_buy(
public_data: Dict[str, Any],
min_distance_pct: float = 0.8,
ideal_distance_pct: float = 3.5,
max_distance_pct: float = 6.0,
) -> Dict[str, Any]:
ticker = public_data["ticker"]
t15 = public_data["timeframes"]["15m"]
t1 = public_data["timeframes"]["1h"]
t4 = public_data["timeframes"]["4h"]
rules = public_data.get("symbol_info", {}).get("rules_short", {})
tick_size = rules.get("tickSize")
last_price = safe_float(ticker.get("lastPrice"))
if last_price is None:
return {
"suggested_limit_buy": None,
"reference": None,
"second_support": None,
"distance_pct_from_last": None,
"note": "No se pudo leer el precio actual.",
"candidates_debug": [],
}
raw_candidates = [
("1h_ma25", safe_float(t1.get("ma25")), 8),
("1h_recent_low", safe_float(t1.get("recent_low")), 7),
("4h_ma25", safe_float(t4.get("ma25")), 6),
("1h_ma99", safe_float(t1.get("ma99")), 5),
("4h_ma99", safe_float(t4.get("ma99")), 4),
("15m_recent_low", safe_float(t15.get("recent_low")), 3),
("4h_recent_low", safe_float(t4.get("recent_low")), 2),
]
candidates: List[Dict[str, Any]] = []
for name, value, base_score in raw_candidates:
if value is None or value >= last_price:
continue
dist_pct = ((last_price / value) - 1.0) * 100.0
score = base_score
if dist_pct < min_distance_pct:
score -= 4
elif dist_pct <= ideal_distance_pct:
score += 3
elif dist_pct <= max_distance_pct:
score += 1
else:
score -= 2
if name.startswith("15m") and dist_pct < 1.2:
score -= 1
if name.startswith("4h_ma99") and dist_pct < 0.7:
score -= 1
candidates.append(
{
"name": name,
"value": value,
"distance_pct": dist_pct,
"score": score,
}
)
if not candidates:
return {
"suggested_limit_buy": None,
"reference": None,
"second_support": None,
"distance_pct_from_last": None,
"note": "No se encontraron soportes válidos por debajo del precio actual.",
"candidates_debug": [],
}
candidates_sorted = sorted(
candidates,
key=lambda x: (x["score"], -abs(x["distance_pct"] - 1.8), x["value"]),
reverse=True,
)
chosen = candidates_sorted[0]
if chosen["distance_pct"] < min_distance_pct:
alt = next(
(c for c in candidates_sorted[1:] if min_distance_pct <= c["distance_pct"] <= max_distance_pct),
None
)
if alt:
chosen = alt
second = next((c for c in candidates_sorted if c["name"] != chosen["name"]), None)
note_parts = ["Sugerencia mecánica basada en soportes por debajo del precio actual."]
if chosen["distance_pct"] < min_distance_pct:
note_parts.append("La entrada está bastante pegada al precio actual.")
elif chosen["distance_pct"] > max_distance_pct:
note_parts.append("La entrada queda bastante lejos; el rebote podría darse antes.")
else:
note_parts.append("La distancia al precio actual luce razonable para buscar retroceso.")
return {
"suggested_limit_buy": floor_to_step(chosen["value"], tick_size),
"reference": chosen["name"],
"second_support": {
"name": second["name"],
"value": normalize_number_str(second["value"], 8),
"distance_pct": normalize_number_str(second["distance_pct"], 4),
} if second else None,
"distance_pct_from_last": normalize_number_str(chosen["distance_pct"], 4),
"note": " ".join(note_parts),
"candidates_debug": [
{
"name": c["name"],
"value": normalize_number_str(c["value"], 8),
"distance_pct": normalize_number_str(c["distance_pct"], 4),
"score": c["score"],
}
for c in candidates_sorted
],
}
# =========================
# Ranking de watchlist (mejorado)
# =========================
def score_rebound_candidate(symbol: str, public_data: Dict[str, Any], capital_quote: float = 35.0) -> Dict[str, Any]:
ticker = public_data["ticker"]
depth = public_data["depth_summary"]
t15 = public_data["timeframes"]["15m"]
t1 = public_data["timeframes"]["1h"]
t4 = public_data["timeframes"]["4h"]
last_price = safe_float(ticker.get("lastPrice"))
score = 0
reasons: List[str] = []
c4 = safe_float(t4.get("last_close"))
ma25_4 = safe_float(t4.get("ma25"))
ma99_4 = safe_float(t4.get("ma99"))
c1 = safe_float(t1.get("last_close"))
ma7_1 = safe_float(t1.get("ma7"))
ma25_1 = safe_float(t1.get("ma25"))
ma99_1 = safe_float(t1.get("ma99"))
c15 = safe_float(t15.get("last_close"))
ma7_15 = safe_float(t15.get("ma7"))
ma25_15 = safe_float(t15.get("ma25"))
recent_high_1 = safe_float(t1.get("recent_high"))
spread_pct = safe_float(depth.get("spread_pct"))
min_side_notional = safe_float(depth.get("min_side_notional_top10"))
# 4h: estructura principal
if c4 is not None and ma25_4 is not None:
if c4 > ma25_4:
score += 2
reasons.append("4h por encima de MA25")
else:
score -= 2
reasons.append("4h por debajo de MA25")
# Penalización más fuerte por debilidad frente a MA99 de 4h
dist_4h_vs_ma99 = pct_change(c4, ma99_4)
if c4 is not None and ma99_4 is not None:
if c4 > ma99_4:
score += 3
reasons.append("4h por encima de MA99")
else:
if dist_4h_vs_ma99 is not None:
if dist_4h_vs_ma99 >= -1.5:
score -= 2
reasons.append("4h ligeramente por debajo de MA99")
elif dist_4h_vs_ma99 >= -4.0:
score -= 4
reasons.append("4h claramente por debajo de MA99")
else:
score -= 6
reasons.append("4h muy débil frente a MA99")
else:
score -= 3
reasons.append("4h por debajo de MA99")
if ma25_4 is not None and ma99_4 is not None:
if ma25_4 > ma99_4:
score += 2
reasons.append("sesgo alcista en 4h (MA25 > MA99)")
else:
score -= 2
reasons.append("sesgo flojo en 4h (MA25 <= MA99)")
# 1h: estructura táctica
if c1 is not None and ma99_1 is not None:
if c1 > ma99_1:
score += 2
reasons.append("1h aún por encima de MA99")
else:
score -= 2
reasons.append("1h perdió MA99")
if c1 is not None and ma7_1 is not None and c1 < ma7_1:
score += 1
reasons.append("hay retroceso corto en 1h")
if c1 is not None and ma25_1 is not None:
dist_1h_ma25 = pct_change(c1, ma25_1)
if dist_1h_ma25 is not None and -2.5 <= dist_1h_ma25 <= 1.0:
score += 2
reasons.append("retroceso razonable cerca de MA25 de 1h")
elif dist_1h_ma25 is not None and dist_1h_ma25 < -5.0:
score -= 2
reasons.append("retroceso demasiado profundo vs MA25 de 1h")
# Pullback desde máximo reciente
if last_price is not None and recent_high_1 is not None and recent_high_1 > EPS:
pullback_pct = ((recent_high_1 - last_price) / recent_high_1) * 100.0
if 0.8 <= pullback_pct <= 4.5:
score += 3