-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautotrader-binancelib-WIP.py
More file actions
4402 lines (3816 loc) · 189 KB
/
Copy pathautotrader-binancelib-WIP.py
File metadata and controls
4402 lines (3816 loc) · 189 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 asyncio
import io
import json, os, csv, time, threading, queue, math, subprocess
from dataclasses import dataclass
from decimal import Decimal, ROUND_DOWN
from typing import List, Dict, Optional
import traceback
import statistics
import datetime
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import requests
from binance.client import Client
from binance import ThreadedWebsocketManager
from binance.exceptions import BinanceAPIException, BinanceOrderException, BinanceRequestException
from tkcalendar import DateEntry
import argparse, sys, signal
import matplotlib
import matplotlib.dates as mdates
import matplotlib.ticker
from matplotlib.lines import Line2D
import pandas as pd
import numpy as np
# Choose backend before any matplotlib submodule is imported.
# Headless mode uses the file-output Agg backend; GUI mode uses TkAgg.
matplotlib.use("Agg" if "--headless" in sys.argv else "TkAgg")
from matplotlib.figure import Figure
if "--headless" not in sys.argv:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import mplcursors
from datetime import datetime, timedelta, date as _date
from collections import defaultdict
import pprint
# ----------------------------
# Config and logging utilities
# ----------------------------
@dataclass
class AppConfig:
# Exchange credentials and base settings
api_key: str = ""
api_secret: str = ""
base_asset: str = "BTC"
quote_asset: str = "USDT"
starting_cash: float = 100000.0
starting_cash_live: float = 1100
fee_rate: float = 0.001
telegram_bot_token: str = ""
telegram_chat_id: str = ""
telegram_enabled: bool = True
send_real_orders: bool = False
# Live trading defaults (map directly to GUI widget defaults)
live_symbol: str = "BNBUSD"
live_interval: str = "1h"
# Shared strategy params used by both live and backtest
rsi_period: int = 2
rsi_mode: str = "simple"
rsi_oversold: float = 31.0
rsi_overbought: float = 70.0
# Backtest defaults
backtest_symbol: str = "BNBUSD"
backtest_interval: str = "1h"
backtest_lookback: str = "1 year ago UTC"
# Order execution
order_type: str = "limit" # "limit" or "trailing_stop"
trailing_stop_pct: float = 0.1 # trail trigger distance in % (e.g. 0.1 = 0.1%)
# Trailing-stop limit order settings (used when order_type == "trailing_stop")
trail_limit_offset_pct: float = 0.1 # extra % beyond trigger for limit price; total slippage budget = trailing_stop_pct + trail_limit_offset_pct
trail_limit_timeout_s: int = 60 # seconds to wait for fill before widening
trail_limit_widen_pct: float = 0.05 # % to widen limit per retry
trail_limit_max_retries: int = 1 # retries before falling back to market
# Crash recovery — persisted buy price so P&L survives restarts
buy_price: Optional[float] = None
# Number of recent closed candles to replay through on_price() on startup
warmup_replay_count: int = 5
class ConfigLoader:
@staticmethod
def load(path: str = "config.json") -> AppConfig:
if not os.path.exists(path):
return AppConfig()
with open(path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError as e:
print(f"Config parse error ({e}) — using defaults.")
return AppConfig()
return AppConfig(
api_key=data.get("api_key", ""),
api_secret=data.get("api_secret", ""),
base_asset=data.get("base_asset", "BTC"),
quote_asset=data.get("quote_asset", "USDT"),
starting_cash=float(data.get("starting_cash", 100000.0)),
starting_cash_live=float(data.get("starting_cash_live", 1100.0)),
fee_rate=float(data.get("fee_rate", 0.001)),
telegram_bot_token=data.get("telegram_bot_token", ""),
telegram_chat_id=data.get("telegram_chat_id", ""),
telegram_enabled=bool(data.get("telegram_enabled", True)),
send_real_orders=bool(data.get("send_real_orders", False)),
live_symbol=data.get("live_symbol", "BNBUSD"),
live_interval=data.get("live_interval", "1h"),
rsi_period=int(data.get("rsi_period", 2)),
rsi_mode=data.get("rsi_mode", "simple"),
rsi_oversold=float(data.get("rsi_oversold", 31.0)),
rsi_overbought=float(data.get("rsi_overbought", 70.0)),
backtest_symbol=data.get("backtest_symbol", "BNBUSD"),
backtest_interval=data.get("backtest_interval", "1h"),
backtest_lookback=data.get("backtest_lookback", "1 year ago UTC"),
order_type=data.get("order_type", "limit"),
trailing_stop_pct=float(data.get("trailing_stop_pct", 0.1)),
trail_limit_offset_pct=float(data.get("trail_limit_offset_pct", 0.1)),
trail_limit_timeout_s=int(data.get("trail_limit_timeout_s", 60)),
trail_limit_widen_pct=float(data.get("trail_limit_widen_pct", 0.05)),
trail_limit_max_retries=int(data.get("trail_limit_max_retries", 1)),
buy_price=float(data["buy_price"]) if data.get("buy_price") is not None else None,
warmup_replay_count=int(data.get("warmup_replay_count", 5)),
)
@staticmethod
def save_field(key: str, value, path: str = "config.json") -> None:
"""Persist a single key/value to config.json without touching other fields."""
try:
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
else:
data = {}
data[key] = value
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"ConfigLoader.save_field: failed to write {key}={value}: {e}")
class OrderLogger:
def __init__(self, log_dir: str = "logs"):
os.makedirs(log_dir, exist_ok=True)
self.log_dir = log_dir
# Weekly rotating filenames — a new file is started each calendar week
week_str = datetime.now().strftime("%Y-W%W")
self.session_log_path = os.path.join(log_dir, f"session_{week_str}.log")
self.orders_csv_path = os.path.join(log_dir, f"orders_{week_str}.csv")
if not os.path.exists(self.orders_csv_path) or os.path.getsize(self.orders_csv_path) == 0:
with open(self.orders_csv_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
"timestamp", "side", "size_base", "price",
"fee_quote", "trade_type", "profit_quote", "equity",
])
def log_event(self, msg: str):
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with open(self.session_log_path, "a", encoding="utf-8") as f:
f.write(f"[{ts}] {msg}\n")
print(msg)
def log_trade(self, side: str, size_base: float, price: float,
fee_quote: float, trade_type: str,
profit_quote: float = 0.0) -> None:
"""Append one trade row to orders.csv."""
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with open(self.orders_csv_path, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
ts, side, f"{size_base:.8f}", f"{price:.6f}",
f"{fee_quote:.8f}", trade_type, f"{profit_quote:.8f}",
])
def log_equity_snapshot(self, equity: float) -> None:
"""Append a SNAPSHOT row to orders.csv with the current account equity.
SNAPSHOT rows have side='SNAPSHOT' and zeroed trade fields so that the
summary-image builder can distinguish them from BUY/SELL rows while
keeping all time-series data in a single file.
"""
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with open(self.orders_csv_path, "a", newline="", encoding="utf-8") as f:
csv.writer(f).writerow([ts, "SNAPSHOT", "0", "0", "0", "", "0", f"{equity:.6f}"])
def send_telegram_message(self, bot_token: str, chat_id: str, text: str):
"""Sends a plain-text Telegram message."""
try:
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {"chat_id": chat_id, "text": text}
requests.post(url, data=payload, timeout=5)
except Exception as e:
print(f"Telegram send error: {e}")
def send_telegram_photo(self, bot_token: str, chat_id: str,
image_bytes: bytes, caption: str = "") -> Optional[int]:
"""Send a PNG image to Telegram; returns the message_id for pinning."""
try:
url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
resp = requests.post(
url,
data={"chat_id": chat_id, "caption": caption},
files={"photo": ("summary.png", image_bytes, "image/png")},
timeout=30,
)
data = resp.json()
if data.get("ok"):
return data["result"]["message_id"]
print(f"Telegram photo error: {data.get('description', 'unknown')}")
except Exception as e:
print(f"Telegram photo send error: {e}")
return None
def pin_telegram_message(self, bot_token: str, chat_id: str,
message_id: int) -> None:
"""Pin a Telegram message (bot must be admin in the chat/channel)."""
try:
url = f"https://api.telegram.org/bot{bot_token}/pinChatMessage"
requests.post(
url,
data={
"chat_id": chat_id,
"message_id": message_id,
"disable_notification": True,
},
timeout=10,
)
except Exception as e:
print(f"Telegram pin error: {e}")
# ----------------------------
# Daily summary image builder
# ----------------------------
def build_daily_summary_image(
log_dir: str,
starting_equity: float,
symbol: str,
summary_date: "_date", # the calendar day being summarised (yesterday)
) -> bytes:
"""Render a mobile-optimised portrait summary PNG and return the raw bytes.
Layout (portrait 9×14 in, 120 DPI):
Title bar
──────────────────────────────
Stats panel (day + all-time)
──────────────────────────────
Equity curve (x = hours of summary_date, y = equity, autoscaled)
Data source: ALL orders_YYYY-WNN.csv files found in log_dir.
Only trades on summary_date appear in the chart and 'day' statistics;
all-time figures aggregate every available CSV file.
"""
# ── Read all orders_YYYY-WNN.csv files: split into trades and equity snapshots ─
all_trades: list = [] # side == BUY or SELL
equity_snaps: list = [] # side == SNAPSHOT
try:
for fname in sorted(os.listdir(log_dir)):
if not (fname.startswith("orders_") and fname.endswith(".csv")):
continue
fpath = os.path.join(log_dir, fname)
with open(fpath, "r", encoding="utf-8") as fh:
for row in csv.DictReader(fh):
try:
ts = datetime.strptime(row["timestamp"], "%Y-%m-%d %H:%M:%S")
side = row.get("side", "")
if side == "SNAPSHOT":
eq_val = float(row.get("equity", 0) or 0)
if eq_val > 0:
equity_snaps.append({"ts": ts, "equity": eq_val})
else:
all_trades.append({
"ts": ts,
"side": side,
"size": float(row.get("size_base", 0) or 0),
"price": float(row.get("price", 0) or 0),
"trade_type": row.get("trade_type", ""),
"profit": float(row.get("profit_quote", 0) or 0),
})
except (ValueError, KeyError):
continue
except OSError:
pass
all_trades.sort(key=lambda x: x["ts"])
equity_snaps.sort(key=lambda x: x["ts"])
# ── Partition: summary day vs. all-time (orders) ─────────────────────────
day_trades = [t for t in all_trades if t["ts"].date() == summary_date]
all_sells = [t for t in all_trades if t["side"] == "SELL"]
all_profit = sum(t["profit"] for t in all_sells)
day_sells = [t for t in day_trades if t["side"] == "SELL"]
day_buys = [t for t in day_trades if t["side"] == "BUY"]
day_wins = [t for t in day_sells if t["profit"] > 0]
day_losses = [t for t in day_sells if t["profit"] <= 0]
day_profit = sum(t["profit"] for t in day_sells)
win_rate = 100.0 * len(day_wins) / len(day_sells) if day_sells else 0.0
best_trade = max(day_sells, key=lambda x: x["profit"]) if day_sells else None
worst_trade = min(day_sells, key=lambda x: x["profit"]) if day_sells else None
day_start_dt = datetime(summary_date.year, summary_date.month, summary_date.day, 0, 0, 0)
day_end_dt = datetime(summary_date.year, summary_date.month, summary_date.day, 23, 59, 59)
# Day-start equity: last snapshot strictly before summary_date midnight
pre_snaps = [s for s in equity_snaps if s["ts"].date() < summary_date]
day_snaps = [s for s in equity_snaps if s["ts"].date() == summary_date]
if pre_snaps:
day_start_eq = pre_snaps[-1]["equity"]
else:
# Fallback: synthetic computation from orders history
pre_day_profit = sum(t["profit"] for t in all_sells if t["ts"].date() < summary_date)
day_start_eq = starting_equity + pre_day_profit
day_end_eq = day_snaps[-1]["equity"] if day_snaps else day_start_eq
current_equity = equity_snaps[-1]["equity"] if equity_snaps else (starting_equity + all_profit)
# Equity change for the day (from real snapshots when available)
day_equity_delta = day_end_eq - day_start_eq
day_profit_pct = 100.0 * day_equity_delta / day_start_eq if day_start_eq else 0.0
all_profit_pct = 100.0 * (current_equity - starting_equity) / starting_equity if starting_equity else 0.0
# ── Equity curve for summary_date ────────────────────────────────────────
if day_snaps:
# Real account snapshots: plot them directly as a line
eq_times = [day_start_dt] + [s["ts"] for s in day_snaps] + [day_end_dt]
eq_values = [day_start_eq] + [s["equity"] for s in day_snaps] + [day_snaps[-1]["equity"]]
# Marker y-positions: map each day_trade to nearest preceding equity snapshot
eq_at_trade: list = []
for t in day_trades:
preceding = [s["equity"] for s in day_snaps if s["ts"] <= t["ts"]]
eq_at_trade.append(preceding[-1] if preceding else day_start_eq)
else:
# Fallback: step-function derived from profit_quote in orders.csv
eq_times = [day_start_dt]
eq_values = [day_start_eq]
running_eq = day_start_eq
for t in day_trades:
if t["side"] == "SELL":
running_eq += t["profit"]
eq_times.append(t["ts"])
eq_values.append(running_eq)
eq_times.append(day_end_dt)
eq_values.append(running_eq)
eq_at_trade = []
r2 = day_start_eq
for t in day_trades:
if t["side"] == "SELL":
r2 += t["profit"]
eq_at_trade.append(r2)
running_eq = eq_values[-1] # used in stats display
# ── Colour palette ────────────────────────────────────────────────────────
C_BG = "#0d1117"
C_PANEL = "#161b22"
C_TEXT = "#e6edf3"
C_MUTED = "#8b949e"
C_GREEN = "#3fb950"
C_RED = "#f85149"
C_GOLD = "#e3b341"
C_BLUE = "#58a6ff"
C_GRID = "#21262d"
C_BORDER = "#30363d"
def _pc(v): return C_GREEN if v >= 0 else C_RED
def _ps(v): return "+" if v >= 0 else ""
# ── Figure — portrait, mobile-optimised (9×14 in, 120 DPI → 1080×1680 px) ─
fig = Figure(figsize=(9, 14), dpi=120)
fig.patch.set_facecolor(C_BG)
gs = fig.add_gridspec(2, 1, height_ratios=[1, 1.6],
hspace=0.08,
left=0.06, right=0.97, top=0.93, bottom=0.06)
ax_s = fig.add_subplot(gs[0]) # stats panel
ax_c = fig.add_subplot(gs[1]) # equity chart
fig.text(
0.5, 0.97,
f"AUTOTRADER | {symbol} | {summary_date.strftime('%Y-%m-%d')}",
ha="center", va="top",
color=C_TEXT, fontsize=16, fontweight="bold", fontfamily="monospace",
)
# ── Stats panel ───────────────────────────────────────────────────────────
ax_s.set_facecolor(C_PANEL)
for sp in ax_s.spines.values():
sp.set_edgecolor(C_BORDER); sp.set_linewidth(1.5)
ax_s.set_xticks([]); ax_s.set_yticks([])
rows = [
("DAILY PERFORMANCE", None, C_GOLD, 14, True),
("─" * 34, None, C_BORDER, 8, False),
("Completed trades (today)", str(len(day_sells)), C_TEXT, 13, False),
(" Buys placed", str(len(day_buys)), C_MUTED, 13, False),
(" Wins / Losses", f"{len(day_wins)} / {len(day_losses)}", C_TEXT, 13, False),
(" Win rate", f"{win_rate:.1f}%", _pc(win_rate - 50), 13, False),
("─" * 34, None, C_BORDER, 8, False),
("PROFIT (today)", None, C_GOLD, 13, True),
(" Account change", f"{_ps(day_equity_delta)}{day_equity_delta:.4f}", _pc(day_equity_delta), 13, False),
(" Percent", f"{_ps(day_profit_pct)}{day_profit_pct:.2f}%", _pc(day_equity_delta), 13, False),
(" Realised P&L", f"{_ps(day_profit)}{day_profit:.4f}", _pc(day_profit), 13, False),
("─" * 34, None, C_BORDER, 8, False),
("PROFIT (all time)", None, C_GOLD, 13, True),
(" Realised P&L", f"{_ps(all_profit)}{all_profit:.4f}", _pc(all_profit), 13, False),
(" Percent", f"{_ps(all_profit_pct)}{all_profit_pct:.2f}%", _pc(all_profit), 13, False),
("─" * 34, None, C_BORDER, 8, False),
("EQUITY", None, C_GOLD, 13, True),
(" Start of day", f"{day_start_eq:,.2f}", C_TEXT, 13, False),
(" End of day", f"{day_end_eq:,.2f}", _pc(day_equity_delta), 13, False),
(" Current (account)", f"{current_equity:,.2f}", _pc(current_equity - starting_equity), 13, False),
]
if best_trade:
rows += [
("─" * 34, None, C_BORDER, 8, False),
("BEST TRADE (today)", None, C_GOLD, 13, True),
(" P&L", f"+{best_trade['profit']:.4f}", C_GREEN, 13, False),
(" Signal", best_trade["trade_type"], C_MUTED, 11, False),
]
if worst_trade and worst_trade is not best_trade:
rows += [
("WORST TRADE (today)", None, C_GOLD, 13, True),
(" P&L", f"{worst_trade['profit']:.4f}", C_RED, 13, False),
(" Signal", worst_trade["trade_type"], C_MUTED, 11, False),
]
n = len(rows)
y0, dy = 0.97, 0.97 / (n + 1)
for i, (label, value, color, fs, bold) in enumerate(rows):
y = y0 - i * dy
kw = dict(transform=ax_s.transAxes, va="top", color=color,
fontsize=fs, fontweight="bold" if bold else "normal",
fontfamily="monospace")
if value is None:
ax_s.text(0.5, y, label, ha="center", **kw)
else:
ax_s.text(0.04, y, label, ha="left", **kw)
kw["color"] = color
ax_s.text(0.96, y, value, ha="right", **kw)
# ── Equity chart ──────────────────────────────────────────────────────────
ax_c.set_facecolor(C_PANEL)
for sp in ax_c.spines.values():
sp.set_edgecolor(C_BORDER); sp.set_linewidth(1.5)
ax_c.tick_params(colors=C_MUTED, labelsize=11)
ax_c.grid(True, color=C_GRID, linestyle="--", linewidth=0.6, alpha=0.8)
ax_c.set_title("Equity Curve", color=C_TEXT, pad=8,
fontsize=14, fontweight="bold", fontfamily="monospace")
ax_c.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, _: f"{x:,.2f}")
)
# x-axis: hours of summary_date (fixed range 00:00–23:59, tick every 2 h)
ax_c.set_xlim(day_start_dt, day_end_dt)
ax_c.xaxis.set_major_locator(mdates.HourLocator(interval=2))
ax_c.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
ax_c.tick_params(axis="x", rotation=30)
if len(eq_times) >= 2:
# Real snapshots → smooth line; fallback step-function → steps-post
_using_snaps = bool(day_snaps)
_draw = "default" if _using_snaps else "steps-post"
ax_c.plot(eq_times, eq_values, color=C_BLUE, linewidth=2.5,
drawstyle=_draw, zorder=3)
# y-axis: autoscale to the day's equity range with padding
_lo = min(eq_values)
_hi = max(eq_values)
_pad = (_hi - _lo) * 0.10 or 1.0
ax_c.set_ylim(_lo - _pad, _hi + _pad)
_fb_kw = {"step": "post"} if not _using_snaps else {}
ax_c.fill_between(eq_times, _lo - _pad, eq_values,
alpha=0.13, color=C_BLUE, zorder=2, **_fb_kw)
# Day-start equity reference line
ax_c.axhline(day_start_eq, color=C_MUTED, linestyle=":",
linewidth=1.0, alpha=0.55, zorder=1)
# Trade markers (BUY ▲ green, SELL profit ▼ green, SELL loss ▼ red)
for t, eq in zip(day_trades, eq_at_trade):
if t["side"] == "BUY":
ax_c.scatter(t["ts"], eq, color=C_GREEN, marker="^",
s=100, zorder=6, edgecolors="white", linewidths=0.5)
else:
mc = C_GREEN if t["profit"] >= 0 else C_RED
ax_c.scatter(t["ts"], eq, color=mc, marker="v",
s=100, zorder=6, edgecolors="white", linewidths=0.5)
else:
ax_c.text(0.5, 0.5, "No trade data for this day",
transform=ax_c.transAxes, ha="center", va="center",
color=C_MUTED, fontsize=16, fontfamily="monospace")
legend_elems = [
Line2D([0], [0], marker="^", color="w", markerfacecolor=C_GREEN,
markersize=10, label="BUY", linestyle="None"),
Line2D([0], [0], marker="v", color="w", markerfacecolor=C_GREEN,
markersize=10, label="SELL (profit)", linestyle="None"),
Line2D([0], [0], marker="v", color="w", markerfacecolor=C_RED,
markersize=10, label="SELL (loss)", linestyle="None"),
Line2D([0], [0], color=C_MUTED, linestyle=":", linewidth=1.5,
label="Day-start equity"),
]
ax_c.legend(handles=legend_elems, loc="upper left",
facecolor=C_BG, edgecolor=C_BORDER,
labelcolor=C_MUTED, fontsize=11, framealpha=0.85)
# ── Render ────────────────────────────────────────────────────────────────
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=120, facecolor=C_BG, bbox_inches="tight")
buf.seek(0)
return buf.read()
# ----------------------------
# Binance Exchange
# ----------------------------
class BinanceUSExchange:
"""
Pure exchange wrapper:
- time sync
- safe requests
- reconnection
- buy/sell
- historical prices
No GUI, no queues, no WebSocket here.
"""
def __init__(self, api_key, api_secret, base_asset, quote_asset, logger, max_retries=2):
self.client = Client(api_key, api_secret, tld='us', base_endpoint='')
# self.client._request = self.debug_wrapper(self.client._request)
self.base_asset = base_asset
self.quote_asset = quote_asset
self.symbol = f"{base_asset}{quote_asset}"
self.logger = logger
self.time_offset_ms = 0
self.max_retries = max_retries
self.max_slippage_pct = 0.001 # 0.3% default, adjust as needed
self.info = self._safe_request(self.client.get_symbol_info, symbol=self.symbol)
self.order_manager = OrderManager(exchange=self, logger=logger)
self.toggle_trade_flag = False
self.step = self._parse_lot_step()
def _log(self, msg: str):
if self.logger:
self.logger.log_event(msg)
def force_windows_time_resync(self):
try:
# need to start process before resync
subprocess.run(
["w32tm", "/register"],
capture_output=True,
text=True,
check=True
)
time.sleep(5)
try:
subprocess.run(
["net", "start", "w32time"],
capture_output=True,
text=True,
check=True
)
except Exception as e:
print("Error:", str(e))
time.sleep(5)
subprocess.run(
["w32tm", "/resync"],
capture_output=True,
text=True,
check=True
)
print("Windows time resync triggered successfully.")
except Exception as e:
self._log(f"Windows time resync failed: {e}")
def sync_time(self):
"""
Synchronizes local time with Binance server time using RTT compensation.
"""
time_NOK = True
sync_attempts = 0
try:
while time_NOK:
sync_attempts += 1
if sync_attempts > 5:
self.toggle_trade_flag = True
sync_attempts = 0
break
t0 = int(time.time() * 1000)
# server = self.client.get_server_time()
server = requests.get("https://api.binance.us/api/v3/time").json()
t1 = int(time.time() * 1000)
server_time = server["serverTime"]
# Round-trip latency
rtt = (t1 - t0) // 2
# Corrected server time at t1
corrected_server_time = server_time + rtt
# Offset = server_time - local_time
self.time_offset_ms = corrected_server_time - t1
if abs(self.time_offset_ms) > 1200:
self._log("Large drift detected. Forcing Windows time resync.")
self.force_windows_time_resync()
time_NOK = True
time.sleep(2)
else:
time_NOK = False
self._log(f"TIME SYNC | offset={self.time_offset_ms} ms | rtt={rtt} ms | server time: {server_time} | local time: {time.time() * 1000} | corr local time: {self._timestamp()}")
except Exception as e:
self._log(f"TIME SYNC ERROR: {e}")
def _timestamp(self) -> int:
return int(time.time() * 1000 + self.time_offset_ms)
def debug_wrapper(self, original_request):
def wrapped(method, uri, signed, force_params=False, **kwargs):
print("\n=== OUTGOING REQUEST ===")
print("Method:", method)
print("URI:", uri)
print("Signed:", signed)
print("Params:", kwargs)
print("========================\n")
print("Local corrected timestamp:", self._timestamp())
return original_request(method, uri, signed, force_params, **kwargs)
return wrapped
def _safe_request(self, func, *args, **kwargs):
"""
Wrapper for all Binance API calls.
Ensures timestamp is preserved and retries use a fresh timestamp.
"""
for attempt in range(1, self.max_retries + 1):
try:
# Always refresh timestamp for signed endpoints
if "timestamp" in kwargs:
kwargs["timestamp"] = self._timestamp()
# kwargs['recvWindow'] = 5000
# print(f"SAFE REQUEST CALL: {func.__name__}")
return func(*args, **kwargs)
except BinanceAPIException as e:
self._log(f"BinanceAPIException in {func}: {e}")
print(f"kwargs: {kwargs}")
if e.code in [-1021, -1022]:
self._log("Timestamp error detected. Resyncing time.")
self.sync_time()
time.sleep(1)
except BinanceOrderException as e:
self._log(f"BinanceOrderException: {e}")
return None
except BinanceRequestException as e:
self._log(f"BinanceRequestException: {e}")
time.sleep(2)
except Exception as e:
self._log(f"Unexpected error: {e}\n{traceback.format_exc()}")
time.sleep(2)
self._log(f"Retrying Binance request (attempt {attempt}/{self.max_retries})")
self._log("Max retries reached. Attempting full reconnection.")
self._reconnect_client()
return None
def _reconnect_client(self):
try:
self._log("Reinitializing Binance client...")
api_key = self.client.API_KEY
api_secret = self.client.API_SECRET
self.client = Client(api_key, api_secret, tld="us", requests_params={"timeout": 5})
self.sync_time()
self._log("Reconnection successful.")
except Exception as e:
self._log(f"Failed to reconnect: {e}")
def get_account_snapshot(self):
"""
Retrieves:
- cash (free quote asset)
- position (free base asset)
Returns a dict or None on failure.
"""
try:
# Fetch balances
account = self._safe_request(
self.client.get_account,
timestamp=self._timestamp()
)
if not account:
self._log("ACCOUNT SNAPSHOT ERROR: Failed to fetch account info")
return None
balances = account.get("balances", [])
# Extract free balances for base + quote assets
cash = 0.0
position = 0.0
for b in balances:
asset = b.get("asset")
free_amt = float(b.get("free", 0))
# Base asset of the trading pair
if asset == self.base_asset:
position = free_amt
# Quote asset of the trading pair
if asset == self.quote_asset:
cash = free_amt
continue
local_readable_timestamp = datetime.fromtimestamp(int(self._timestamp()/1000))
local_date = local_readable_timestamp.strftime("%Y-%m-%d")
local_time = local_readable_timestamp.strftime("%H:%M %Z")
# Get current price for equity calculation
price = None
if hasattr(self, 'strat') and self.strat and self.strat.prices:
price = self.strat.prices[-1]
else:
ticker = self._safe_request(self.client.get_symbol_ticker, symbol=self.symbol)
if ticker:
price = float(ticker["price"])
equity = (cash + position * price) if price is not None else None
snapshot = {
"cash": cash,
"position": position,
"equity": equity,
}
equity_str = f"{equity:.2f}" if equity is not None else "N/A"
self._log(
f"[ACCOUNT SNAPSHOT] | {local_date} {local_time} | Cash ({self.quote_asset}): {cash} | Position ({self.base_asset}): {position} | Equity: {equity_str}"
)
if equity is not None and self.logger is not None:
self.logger.log_equity_snapshot(equity)
return snapshot
except Exception as e:
self._log(f"ACCOUNT SNAPSHOT ERROR: {e}")
return None
def buy(self, symbol, quantity, use_market=False, orig_price=None, limit_price=None):
"""
Places a BUY order and handles Binance confirmation response.
Returns a structured dict with order details or None on failure.
limit_price: when provided, the limit order is placed at this price
(tick-rounded) instead of the current ticker price.
Ignored when use_market=True.
"""
try:
# Get current price
ticker = self._safe_request(self.client.get_symbol_ticker, symbol=symbol)
if not ticker:
self._log("BUY ERROR: Failed to fetch ticker")
return None
current_price = float(ticker["price"])
order_price = limit_price if (limit_price is not None and not use_market) else current_price
ok, new_price, new_qty = self.prepare_order(symbol, order_price, quantity)
if not ok:
self._log(f"ORDER VALIDATION FAILED: {new_price}") # new_price holds the error message
return None
if orig_price is not None:
# Slippage check: price must not rise above allowed threshold
max_allowed = orig_price * (1 + self.max_slippage_pct)
if current_price > max_allowed:
self._log(
f"BUY ABORTED: Slippage too high. "
f"Original={orig_price}, Current={current_price}, "
f"MaxAllowed={max_allowed}"
)
return None
# -------------------------
# MARKET BUY
# -------------------------
if use_market:
order = self._safe_request(
self.client.order_market_buy,
symbol=symbol,
quantity=new_qty,
timestamp=self._timestamp()
)
if not order:
self._log("BUY ERROR: Market order failed")
return None
return self._process_order_confirmation(order, "BUY", current_price)
# -------------------------
# MAKER-ONLY LIMIT BUY
# -------------------------
order = self._safe_request(
self.client.order_limit_buy,
symbol=symbol,
price=str(new_price),
quantity=str(new_qty),
timeInForce="GTC",
timestamp=self._timestamp()
)
if not order:
self._log("BUY ERROR: Limit order failed")
return None
if "orderId" not in order:
self._log("Order failed: no orderId returned")
return None
self.order_id = order.get("orderId")
self.order_manager.register(
symbol=symbol,
order_id=self.order_id,
limit_price=float(order["price"]),
timestamp=self._timestamp()
)
return self._process_order_confirmation(order, "BUY", current_price)
except Exception as e:
self._log(f"BUY ERROR: {e}")
return None
def sell(self, symbol, quantity, use_market=False, orig_price=None, limit_price=None):
"""
Places a SELL order and handles Binance confirmation response.
Returns a structured dict with order details or None on failure.
limit_price: when provided, the limit order is placed at this price
(tick-rounded) instead of the current ticker price.
Ignored when use_market=True.
"""
try:
ticker = self._safe_request(self.client.get_symbol_ticker, symbol=symbol)
if not ticker:
self._log("SELL ERROR: Failed to fetch ticker")
return None
current_price = float(ticker["price"])
order_price = limit_price if (limit_price is not None and not use_market) else current_price
ok, new_price, new_qty = self.prepare_order(symbol, order_price, quantity)
if not ok:
self._log(f"ORDER VALIDATION FAILED: {new_price}") # new_price holds the error message
return None
if orig_price is not None:
# Slippage check: price must not fall below allowed threshold
min_allowed = orig_price * (1 - self.max_slippage_pct)
if current_price < min_allowed:
self._log(
f"SELL ABORTED: Slippage too high. "
f"Original={orig_price}, Current={current_price}, "
f"Min. allowed={min_allowed}"
)
return None
# -------------------------
# MARKET SELL
# -------------------------
if use_market:
order = self._safe_request(
self.client.order_market_sell,
symbol=symbol,
quantity=new_qty,
timestamp=self._timestamp()
)
if not order:
self._log("SELL ERROR: Market order failed")
return None
return self._process_order_confirmation(order, "SELL", current_price)
# -------------------------
# MAKER-ONLY LIMIT SELL
# -------------------------
order = self._safe_request(
self.client.order_limit_sell,
symbol=symbol,
quantity=new_qty,
price=str(new_price),
timeInForce="GTC",
timestamp=self._timestamp()
)
# If limit order failed entirely → fallback to market
if not order:
self._log("Maker SELL rejected — falling back to MARKET SELL")
return self._fallback_market_sell(symbol, quantity, current_price)
self.order_id = order.get("orderId")
self.order_manager.register(
symbol=symbol,
order_id=self.order_id,
limit_price=new_price,
timestamp=self._timestamp()
)
# If Binance returns a REJECTED status → fallback
status = order.get("status", "")
if status in ("REJECTED", "EXPIRED", "CANCELED"):
self._log(f"Maker SELL returned status {status} — falling back to MARKET SELL")
return self._fallback_market_sell(symbol, quantity, current_price)
# Otherwise, process normally
return self._process_order_confirmation(order, "SELL", current_price)
except Exception as e:
self._log(f"SELL ERROR: {e}")
return None
def _fallback_market_sell(self, symbol, quantity, original_price):
"""
Executes a fallback MARKET SELL with slippage protection.
Ensures the market price has not moved too far below the original price.
"""
try:
# Re-fetch current price before executing market order
ticker = self._safe_request(self.client.get_symbol_ticker, symbol=symbol)
if not ticker:
self._log("FALLBACK SELL ERROR: Could not fetch ticker for slippage check")
return None
current_price = float(ticker["price"])
ok, new_price, new_qty = self.prepare_order(symbol, current_price, quantity)
if not ok:
self._log("ORDER VALIDATION FAILED 01")
return None
# Slippage check: price must not fall below allowed threshold
min_allowed = original_price * (1 - self.max_slippage_pct)
if current_price < min_allowed:
self._log(
f"FALLBACK SELL ABORTED: Slippage too high. "
f"Original={original_price}, Current={current_price}, "
f"MinAllowed={min_allowed}"
)
return None
# Execute market order safely
order = self._safe_request(
self.client.order_market_sell,
symbol=symbol,
quantity=new_qty,
timestamp=self._timestamp()
)
if not order:
self._log("FALLBACK MARKET SELL FAILED")
return None
return self._process_order_confirmation(order, "SELL", current_price)
except Exception as e:
self._log(f"FALLBACK SELL ERROR: {e}")
return None
def _process_order_confirmation(self, order, side, market_price):
"""
Processes Binance order response and extracts:
- status
- executed quantity
- executed price
- commission
- fills
"""
try:
status = order.get("status", "UNKNOWN")
executed_qty = float(order.get("executedQty", 0))
orig_qty = float(order.get("origQty", 0))
fills = order.get("fills", [])
# Compute weighted-average fill price and total commission from fills.
# Fall back to market_price (ticker at order time) only when Binance
# returns no fills (e.g. for GTC limit orders still pending).
if fills:
total_cost = 0.0
total_qty = 0.0
total_commission = 0.0
for f in fills:
f_price = float(f.get("price", 0))
f_qty = float(f.get("qty", 0))
total_cost += f_price * f_qty
total_qty += f_qty