-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathpt_hub.py
More file actions
5333 lines (4252 loc) · 202 KB
/
pt_hub.py
File metadata and controls
5333 lines (4252 loc) · 202 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
from __future__ import annotations
import os
import sys
import json
import time
import math
import queue
import threading
import subprocess
import shutil
import glob
import bisect
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, filedialog, messagebox
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.patches import Rectangle
from matplotlib.ticker import FuncFormatter
from matplotlib.transforms import blended_transform_factory
DARK_BG = "#070B10"
DARK_BG2 = "#0B1220"
DARK_PANEL = "#0E1626"
DARK_PANEL2 = "#121C2F"
DARK_BORDER = "#243044"
DARK_FG = "#C7D1DB"
DARK_MUTED = "#8B949E"
DARK_ACCENT = "#00FF66"
DARK_ACCENT2 = "#00E5FF"
DARK_SELECT_BG = "#17324A"
DARK_SELECT_FG = "#00FF66"
@dataclass
class _WrapItem:
w: tk.Widget
padx: Tuple[int, int] = (0, 0)
pady: Tuple[int, int] = (0, 0)
class WrapFrame(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self._items: List[_WrapItem] = []
self._reflow_pending = False
self._in_reflow = False
self.bind("<Configure>", self._schedule_reflow)
def add(self, widget: tk.Widget, padx=(0, 0), pady=(0, 0)) -> None:
self._items.append(_WrapItem(widget, padx=padx, pady=pady))
self._schedule_reflow()
def clear(self, destroy_widgets: bool = True) -> None:
for it in list(self._items):
try:
it.w.grid_forget()
except Exception:
pass
if destroy_widgets:
try:
it.w.destroy()
except Exception:
pass
self._items = []
self._schedule_reflow()
def _schedule_reflow(self, event=None) -> None:
if self._reflow_pending:
return
self._reflow_pending = True
self.after_idle(self._reflow)
def _reflow(self) -> None:
if self._in_reflow:
self._reflow_pending = False
return
self._reflow_pending = False
self._in_reflow = True
try:
width = self.winfo_width()
if width <= 1:
return
usable_width = max(1, width - 6)
for it in self._items:
it.w.grid_forget()
row = 0
col = 0
x = 0
for it in self._items:
reqw = max(it.w.winfo_reqwidth(), it.w.winfo_width())
needed = 10 + reqw + it.padx[0] + it.padx[1]
if col > 0 and (x + needed) > usable_width:
row += 1
col = 0
x = 0
it.w.grid(row=row, column=col, sticky="w", padx=it.padx, pady=it.pady)
x += needed
col += 1
finally:
self._in_reflow = False
class NeuralSignalTile(ttk.Frame):
def __init__(self, parent: tk.Widget, coin: str, bar_height: int = 52, levels: int = 8, trade_start_level: int = 3):
super().__init__(parent)
self.coin = coin
self._hover_on = False
self._normal_canvas_bg = DARK_PANEL2
self._hover_canvas_bg = DARK_PANEL
self._normal_border = DARK_BORDER
self._hover_border = DARK_ACCENT2
self._normal_fg = DARK_FG
self._hover_fg = DARK_ACCENT2
self._levels = max(2, int(levels))
self._display_levels = self._levels - 1
self._bar_h = int(bar_height)
self._bar_w = 12
self._gap = 16
self._pad = 6
self._base_fill = DARK_PANEL
self._long_fill = "blue"
self._short_fill = "orange"
self.title_lbl = ttk.Label(self, text=coin)
self.title_lbl.pack(anchor="center")
w = (self._pad * 2) + (self._bar_w * 2) + self._gap
h = (self._pad * 2) + self._bar_h
self.canvas = tk.Canvas(
self,
width=w,
height=h,
bg=self._normal_canvas_bg,
highlightthickness=1,
highlightbackground=self._normal_border,
)
self.canvas.pack(padx=2, pady=(2, 0))
x0 = self._pad
x1 = x0 + self._bar_w
x2 = x1 + self._gap
x3 = x2 + self._bar_w
yb = self._pad + self._bar_h
# Build segmented bars: 7 segments for levels 1..7 (level 0 is "no highlight")
self._long_segs: List[int] = []
self._short_segs: List[int] = []
for seg in range(self._display_levels):
# seg=0 is bottom segment (level 1), seg=display_levels-1 is top segment (level 7)
y_top = int(round(yb - ((seg + 1) * self._bar_h / self._display_levels)))
y_bot = int(round(yb - (seg * self._bar_h / self._display_levels)))
self._long_segs.append(
self.canvas.create_rectangle(
x0, y_top, x1, y_bot,
fill=self._base_fill,
outline=DARK_BORDER,
width=1,
)
)
self._short_segs.append(
self.canvas.create_rectangle(
x2, y_top, x3, y_bot,
fill=self._base_fill,
outline=DARK_BORDER,
width=1,
)
)
# Trade-start marker line (boundary before the trade-start level).
# Example: trade_start_level=3 => line after 2nd block (between 2 and 3).
self._trade_line_geom = (x0, x1, x2, x3, yb)
self._trade_line_long = self.canvas.create_line(x0, yb, x1, yb, fill=DARK_FG, width=2)
self._trade_line_short = self.canvas.create_line(x2, yb, x3, yb, fill=DARK_FG, width=2)
self._trade_start_level = 3
self.set_trade_start_level(trade_start_level)
self.value_lbl = ttk.Label(self, text="L:0 S:0")
self.value_lbl.pack(anchor="center", pady=(1, 0))
self.set_values(0, 0)
def set_hover(self, on: bool) -> None:
"""Visually highlight the tile on hover (like a button hover state)."""
if bool(on) == bool(self._hover_on):
return
self._hover_on = bool(on)
try:
if self._hover_on:
self.canvas.configure(
bg=self._hover_canvas_bg,
highlightbackground=self._hover_border,
highlightthickness=2,
)
self.title_lbl.configure(foreground=self._hover_fg)
self.value_lbl.configure(foreground=self._hover_fg)
else:
self.canvas.configure(
bg=self._normal_canvas_bg,
highlightbackground=self._normal_border,
highlightthickness=1,
)
self.title_lbl.configure(foreground=self._normal_fg)
self.value_lbl.configure(foreground=self._normal_fg)
except Exception:
pass
def set_trade_start_level(self, level: Any) -> None:
"""Move the marker line to the boundary before the chosen start level."""
self._trade_start_level = self._clamp_trade_start_level(level)
self._update_trade_lines()
def _clamp_trade_start_level(self, value: Any) -> int:
try:
v = int(float(value))
except Exception:
v = 3
# Trade starts at levels 1..display_levels (usually 1..7)
return max(1, min(v, self._display_levels))
def _update_trade_lines(self) -> None:
try:
x0, x1, x2, x3, yb = self._trade_line_geom
except Exception:
return
k = max(0, min(int(self._trade_start_level) - 1, self._display_levels))
y = int(round(yb - (k * self._bar_h / self._display_levels)))
try:
self.canvas.coords(self._trade_line_long, x0, y, x1, y)
self.canvas.coords(self._trade_line_short, x2, y, x3, y)
except Exception:
pass
def _clamp_level(self, value: Any) -> int:
try:
v = int(float(value))
except Exception:
v = 0
return max(0, min(v, self._levels - 1)) # logical clamp: 0..7
def _set_level(self, seg_ids: List[int], level: int, active_fill: str) -> None:
# Reset all segments to base
for rid in seg_ids:
self.canvas.itemconfigure(rid, fill=self._base_fill)
# Level 0 -> show nothing (no highlight)
if level <= 0:
return
# Level 1..7 -> fill from bottom up through the current level
idx = level - 1 # level 1 maps to seg index 0
if idx < 0:
return
if idx >= len(seg_ids):
idx = len(seg_ids) - 1
for i in range(idx + 1):
self.canvas.itemconfigure(seg_ids[i], fill=active_fill)
def set_values(self, long_sig: Any, short_sig: Any) -> None:
ls = self._clamp_level(long_sig)
ss = self._clamp_level(short_sig)
self.value_lbl.config(text=f"L:{ls} S:{ss}")
self._set_level(self._long_segs, ls, self._long_fill)
self._set_level(self._short_segs, ss, self._short_fill)
# -----------------------------
# Settings / Paths
# -----------------------------
DEFAULT_SETTINGS = {
"main_neural_dir": "",
"coins": ["BTC", "ETH", "XRP", "BNB", "DOGE"],
"trade_start_level": 3, # trade starts when long signal >= this level (1..7)
"start_allocation_pct": 0.005, # % of total account value for initial entry (min $0.50 per coin)
"dca_multiplier": 2.0, # DCA buy size = current value * this (2.0 => total scales ~3x per DCA)
"dca_levels": [-2.5, -5.0, -10.0, -20.0, -30.0, -40.0, -50.0], # Hard DCA triggers (percent PnL)
"max_dca_buys_per_24h": 2, # max DCA buys per coin in rolling 24h window (0 disables DCA buys)
# --- Trailing Profit Margin settings (used by pt_trader.py; shown in GUI settings) ---
"pm_start_pct_no_dca": 5.0,
"pm_start_pct_with_dca": 2.5,
"trailing_gap_pct": 0.5,
"default_timeframe": "1hour",
"timeframes": [
"1min", "5min", "15min", "30min",
"1hour", "2hour", "4hour", "8hour", "12hour",
"1day", "1week"
],
"candles_limit": 120,
"ui_refresh_seconds": 1.0,
"chart_refresh_seconds": 10.0,
"hub_data_dir": "", # if blank, defaults to <this_dir>/hub_data
"script_neural_runner2": "pt_thinker.py",
"script_neural_trainer": "pt_trainer.py",
"script_trader": "pt_trader.py",
"auto_start_scripts": False,
}
SETTINGS_FILE = "gui_settings.json"
def _safe_read_json(path: str) -> Optional[dict]:
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def _safe_write_json(path: str, data: dict) -> None:
tmp = f"{path}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
os.replace(tmp, path)
def _read_trade_history_jsonl(path: str) -> List[dict]:
"""
Reads hub_data/trade_history.jsonl written by pt_trader.py.
Returns a list of dicts (only buy/sell rows).
"""
out: List[dict] = []
try:
if os.path.isfile(path):
with open(path, "r", encoding="utf-8") as f:
for ln in f:
ln = ln.strip()
if not ln:
continue
try:
obj = json.loads(ln)
side = str(obj.get("side", "")).lower().strip()
if side not in ("buy", "sell"):
continue
out.append(obj)
except Exception:
continue
except Exception:
pass
return out
def _ensure_dir(path: str) -> None:
os.makedirs(path, exist_ok=True)
def _fmt_money(x: float) -> str:
"""Format a USD *amount* (account value, position value, etc.) as dollars with 2 decimals."""
try:
return f"${float(x):,.2f}"
except Exception:
return "N/A"
def _fmt_price(x: Any) -> str:
"""
Format a USD *price/level* with dynamic decimals based on magnitude.
Examples:
50234.12 -> $50,234.12
123.4567 -> $123.457
1.234567 -> $1.2346
0.06234567 -> $0.062346
0.00012345 -> $0.00012345
"""
try:
if x is None:
return "N/A"
v = float(x)
if not math.isfinite(v):
return "N/A"
sign = "-" if v < 0 else ""
av = abs(v)
# Choose decimals by magnitude (more detail for smaller prices).
if av >= 1000:
dec = 2
elif av >= 100:
dec = 3
elif av >= 1:
dec = 4
elif av >= 0.1:
dec = 5
elif av >= 0.01:
dec = 6
elif av >= 0.001:
dec = 7
else:
dec = 8
s = f"{av:,.{dec}f}"
if "." in s:
s = s.rstrip("0").rstrip(".")
return f"{sign}${s}"
except Exception:
return "N/A"
def _fmt_pct(x: float) -> str:
try:
return f"{float(x):+.2f}%"
except Exception:
return "N/A"
def _now_str() -> str:
return time.strftime("%Y-%m-%d %H:%M:%S")
# -----------------------------
# Neural folder detection
# -----------------------------
def build_coin_folders(main_dir: str, coins: List[str]) -> Dict[str, str]:
"""
Mirrors your convention:
BTC uses main_dir directly
other coins typically have subfolders inside main_dir (auto-detected)
Returns { "BTC": "...", "ETH": "...", ... }
"""
out: Dict[str, str] = {}
main_dir = main_dir or os.getcwd()
# BTC folder
out["BTC"] = main_dir
# Auto-detect subfolders
if os.path.isdir(main_dir):
for name in os.listdir(main_dir):
p = os.path.join(main_dir, name)
if not os.path.isdir(p):
continue
sym = name.upper().strip()
if sym in coins and sym != "BTC":
out[sym] = p
# Fallbacks for missing ones
for c in coins:
c = c.upper().strip()
if c not in out:
out[c] = os.path.join(main_dir, c) # best-effort fallback
return out
def read_price_levels_from_html(path: str) -> List[float]:
"""
pt_thinker writes a python-list-like string into low_bound_prices.html / high_bound_prices.html.
Example (commas often remain):
"43210.1, 43100.0, 42950.5"
So we normalize separators before parsing.
"""
try:
with open(path, "r", encoding="utf-8") as f:
raw = f.read().strip()
if not raw:
return []
# Normalize common separators that pt_thinker can leave behind
raw = (
raw.replace(",", " ")
.replace("[", " ")
.replace("]", " ")
.replace("'", " ")
)
vals: List[float] = []
for tok in raw.split():
try:
v = float(tok)
# Filter obvious sentinel values used by pt_thinker for "inactive" slots
if v <= 0:
continue
if v >= 9e15: # pt_thinker uses 99999999999999999
continue
vals.append(v)
except Exception:
pass
# De-dupe while preserving order (small rounding to avoid float-noise duplicates)
out: List[float] = []
seen = set()
for v in vals:
key = round(v, 12)
if key in seen:
continue
seen.add(key)
out.append(v)
return out
except Exception:
return []
def read_int_from_file(path: str) -> int:
try:
with open(path, "r", encoding="utf-8") as f:
raw = f.read().strip()
return int(float(raw))
except Exception:
return 0
def read_short_signal(folder: str) -> int:
txt = os.path.join(folder, "short_dca_signal.txt")
if os.path.isfile(txt):
return read_int_from_file(txt)
else:
return 0
# -----------------------------
# Candle fetching (KuCoin)
# -----------------------------
class CandleFetcher:
"""
Uses kucoin-python if available; otherwise falls back to KuCoin REST via requests.
"""
def __init__(self):
self._mode = "kucoin_client"
self._market = None
try:
from kucoin.client import Market # type: ignore
self._market = Market(url="https://api.kucoin.com")
except Exception:
self._mode = "rest"
self._market = None
if self._mode == "rest":
import requests # local import
self._requests = requests
# Small in-memory cache to keep timeframe switching snappy.
# key: (pair, timeframe, limit) -> (saved_time_epoch, candles)
self._cache: Dict[Tuple[str, str, int], Tuple[float, List[dict]]] = {}
self._cache_ttl_seconds: float = 10.0
def get_klines(self, symbol: str, timeframe: str, limit: int = 120) -> List[dict]:
"""
Returns candles oldest->newest as:
[{"ts": int, "open": float, "high": float, "low": float, "close": float}, ...]
"""
symbol = symbol.upper().strip()
# Your neural uses USDT pairs on KuCoin (ex: BTC-USDT)
pair = f"{symbol}-USDT"
limit = int(limit or 0)
now = time.time()
cache_key = (pair, timeframe, limit)
cached = self._cache.get(cache_key)
if cached and (now - float(cached[0])) <= float(self._cache_ttl_seconds):
return cached[1]
# rough window (timeframe-dependent) so we get enough candles
tf_seconds = {
"1min": 60, "5min": 300, "15min": 900, "30min": 1800,
"1hour": 3600, "2hour": 7200, "4hour": 14400, "8hour": 28800, "12hour": 43200,
"1day": 86400, "1week": 604800
}.get(timeframe, 3600)
end_at = int(now)
start_at = end_at - (tf_seconds * max(200, (limit + 50) if limit else 250))
if self._mode == "kucoin_client" and self._market is not None:
try:
# IMPORTANT: limit the server response by passing startAt/endAt.
# This avoids downloading a huge default kline set every switch.
try:
raw = self._market.get_kline(pair, timeframe, startAt=start_at, endAt=end_at) # type: ignore
except Exception:
# fallback if that client version doesn't accept kwargs
raw = self._market.get_kline(pair, timeframe) # returns newest->oldest
candles: List[dict] = []
for row in raw:
# KuCoin kline row format:
# [time, open, close, high, low, volume, turnover]
ts = int(float(row[0]))
o = float(row[1]); c = float(row[2]); h = float(row[3]); l = float(row[4])
candles.append({"ts": ts, "open": o, "high": h, "low": l, "close": c})
candles.sort(key=lambda x: x["ts"])
if limit and len(candles) > limit:
candles = candles[-limit:]
self._cache[cache_key] = (now, candles)
return candles
except Exception:
return []
# REST fallback
try:
url = "https://api.kucoin.com/api/v1/market/candles"
params = {"symbol": pair, "type": timeframe, "startAt": start_at, "endAt": end_at}
resp = self._requests.get(url, params=params, timeout=10)
j = resp.json()
data = j.get("data", []) # newest->oldest
candles: List[dict] = []
for row in data:
ts = int(float(row[0]))
o = float(row[1]); c = float(row[2]); h = float(row[3]); l = float(row[4])
candles.append({"ts": ts, "open": o, "high": h, "low": l, "close": c})
candles.sort(key=lambda x: x["ts"])
if limit and len(candles) > limit:
candles = candles[-limit:]
self._cache[cache_key] = (now, candles)
return candles
except Exception:
return []
# -----------------------------
# Chart widget
# -----------------------------
class CandleChart(ttk.Frame):
def __init__(
self,
parent: tk.Widget,
fetcher: CandleFetcher,
coin: str,
settings_getter,
trade_history_path: str,
):
super().__init__(parent)
self.fetcher = fetcher
self.coin = coin
self.settings_getter = settings_getter
self.trade_history_path = trade_history_path
self.timeframe_var = tk.StringVar(value=self.settings_getter()["default_timeframe"])
top = ttk.Frame(self)
top.pack(fill="x", padx=6, pady=6)
ttk.Label(top, text=f"{coin} chart").pack(side="left")
ttk.Label(top, text="Timeframe:").pack(side="left", padx=(12, 4))
self.tf_combo = ttk.Combobox(
top,
textvariable=self.timeframe_var,
values=self.settings_getter()["timeframes"],
state="readonly",
width=10,
)
self.tf_combo.pack(side="left")
# Debounce rapid timeframe changes so redraws don't stack
self._tf_after_id = None
def _debounced_tf_change(*_):
try:
if self._tf_after_id:
self.after_cancel(self._tf_after_id)
except Exception:
pass
def _do():
# Ask the hub to refresh charts on the next tick (single refresh)
try:
self.event_generate("<<TimeframeChanged>>", when="tail")
except Exception:
pass
self._tf_after_id = self.after(120, _do)
self.tf_combo.bind("<<ComboboxSelected>>", _debounced_tf_change)
self.neural_status_label = ttk.Label(top, text="Neural: N/A")
self.neural_status_label.pack(side="left", padx=(12, 0))
self.last_update_label = ttk.Label(top, text="Last: N/A")
self.last_update_label.pack(side="right")
# Figure
# IMPORTANT: keep a stable DPI and resize the figure to the widget's pixel size.
# On Windows scaling, trying to "sync DPI" via winfo_fpixels("1i") can produce the
# exact right-side blank/covered region you're seeing.
self.fig = Figure(figsize=(6.5, 3.5), dpi=100)
self.fig.patch.set_facecolor(DARK_BG)
# Reserve bottom space so date+time x tick labels are always visible
# Also reserve right space so the price labels (Bid/Ask/DCA/Sell) can sit outside the plot.
# Also reserve a bit of top space so the title never gets clipped.
self.fig.subplots_adjust(bottom=0.20, right=0.87, top=0.8)
self.ax = self.fig.add_subplot(111)
self._apply_dark_chart_style()
self.ax.set_title(f"{coin}", color=DARK_FG)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
canvas_w = self.canvas.get_tk_widget()
canvas_w.configure(bg=DARK_BG)
# Remove horizontal padding here so the chart widget truly fills the container.
canvas_w.pack(fill="both", expand=True, padx=0, pady=(0, 6))
# Keep the matplotlib figure EXACTLY the same pixel size as the Tk widget.
# FigureCanvasTkAgg already sizes its backing PhotoImage to e.width/e.height.
# Multiplying by tk scaling here makes the renderer larger than the PhotoImage,
# which produces the "blank/covered strip" on the right.
self._last_canvas_px = (0, 0)
self._resize_after_id = None
def _on_canvas_configure(e):
try:
w = int(e.width)
h = int(e.height)
if w <= 1 or h <= 1:
return
if (w, h) == self._last_canvas_px:
return
self._last_canvas_px = (w, h)
dpi = float(self.fig.get_dpi() or 100.0)
self.fig.set_size_inches(w / dpi, h / dpi, forward=True)
# Debounce redraws during live resize
if self._resize_after_id:
try:
self.after_cancel(self._resize_after_id)
except Exception:
pass
self._resize_after_id = self.after_idle(self.canvas.draw_idle)
except Exception:
pass
canvas_w.bind("<Configure>", _on_canvas_configure, add="+")
self._last_refresh = 0.0
def _apply_dark_chart_style(self) -> None:
"""Apply dark styling (called on init and after every ax.clear())."""
try:
self.fig.patch.set_facecolor(DARK_BG)
self.ax.set_facecolor(DARK_PANEL)
self.ax.tick_params(colors=DARK_FG)
for spine in self.ax.spines.values():
spine.set_color(DARK_BORDER)
self.ax.grid(True, color=DARK_BORDER, linewidth=0.6, alpha=0.35)
except Exception:
pass
def refresh(
self,
coin_folders: Dict[str, str],
current_buy_price: Optional[float] = None,
current_sell_price: Optional[float] = None,
trail_line: Optional[float] = None,
dca_line_price: Optional[float] = None,
avg_cost_basis: Optional[float] = None,
) -> None:
cfg = self.settings_getter()
tf = self.timeframe_var.get().strip()
limit = int(cfg.get("candles_limit", 120))
candles = self.fetcher.get_klines(self.coin, tf, limit=limit)
folder = coin_folders.get(self.coin, "")
low_path = os.path.join(folder, "low_bound_prices.html")
high_path = os.path.join(folder, "high_bound_prices.html")
# --- Cached neural reads (per path, by mtime) ---
if not hasattr(self, "_neural_cache"):
self._neural_cache = {} # path -> (mtime, value)
def _cached(path: str, loader, default):
try:
mtime = os.path.getmtime(path)
except Exception:
return default
hit = self._neural_cache.get(path)
if hit and hit[0] == mtime:
return hit[1]
v = loader(path)
self._neural_cache[path] = (mtime, v)
return v
long_levels = _cached(low_path, read_price_levels_from_html, []) if folder else []
short_levels = _cached(high_path, read_price_levels_from_html, []) if folder else []
long_sig_path = os.path.join(folder, "long_dca_signal.txt")
long_sig = _cached(long_sig_path, read_int_from_file, 0) if folder else 0
short_sig = read_short_signal(folder) if folder else 0
# --- Avoid full ax.clear() (expensive). Just clear artists. ---
try:
self.ax.lines.clear()
self.ax.patches.clear()
self.ax.collections.clear() # scatter dots live here
self.ax.texts.clear() # labels/annotations live here
except Exception:
# fallback if matplotlib version lacks .clear() on these lists
self.ax.cla()
self._apply_dark_chart_style()
if not candles:
self.ax.set_title(f"{self.coin} ({tf}) - no candles", color=DARK_FG)
self.canvas.draw_idle()
return
# Candlestick drawing (green up / red down) - batch rectangles
xs = getattr(self, "_xs", None)
if not xs or len(xs) != len(candles):
xs = list(range(len(candles)))
self._xs = xs
rects = []
for i, c in enumerate(candles):
o = float(c["open"])
cl = float(c["close"])
h = float(c["high"])
l = float(c["low"])
up = cl >= o
candle_color = "green" if up else "red"
# wick
self.ax.plot([i, i], [l, h], linewidth=1, color=candle_color)
# body
bottom = min(o, cl)
height = abs(cl - o)
if height < 1e-12:
height = 1e-12
rects.append(
Rectangle(
(i - 0.35, bottom),
0.7,
height,
facecolor=candle_color,
edgecolor=candle_color,
linewidth=1,
alpha=0.9,
)
)
for r in rects:
self.ax.add_patch(r)
# Lock y-limits to candle range so overlay lines can go offscreen without expanding the chart.
try:
y_low = min(float(c["low"]) for c in candles)
y_high = max(float(c["high"]) for c in candles)
pad = (y_high - y_low) * 0.03
if not math.isfinite(pad) or pad <= 0:
pad = max(abs(y_low) * 0.001, 1e-6)
self.ax.set_ylim(y_low - pad, y_high + pad)
except Exception:
pass
# Overlay Neural levels (blue long, orange short)
for lv in long_levels:
try:
self.ax.axhline(y=float(lv), linewidth=1, color="blue", alpha=0.8)
except Exception:
pass
for lv in short_levels:
try:
self.ax.axhline(y=float(lv), linewidth=1, color="orange", alpha=0.8)
except Exception:
pass
# Overlay Trailing PM line (sell) and next DCA line
try:
if trail_line is not None and float(trail_line) > 0:
self.ax.axhline(y=float(trail_line), linewidth=1.5, color="green", alpha=0.95)
except Exception:
pass
try:
if dca_line_price is not None and float(dca_line_price) > 0:
self.ax.axhline(y=float(dca_line_price), linewidth=1.5, color="red", alpha=0.95)
except Exception:
pass
# Overlay avg cost basis (yellow)
try:
if avg_cost_basis is not None and float(avg_cost_basis) > 0:
self.ax.axhline(y=float(avg_cost_basis), linewidth=1.5, color="yellow", alpha=0.95)
except Exception:
pass
# Overlay current ask/bid prices
try:
if current_buy_price is not None and float(current_buy_price) > 0:
self.ax.axhline(y=float(current_buy_price), linewidth=1.5, color="purple", alpha=0.95)
except Exception:
pass
try:
if current_sell_price is not None and float(current_sell_price) > 0:
self.ax.axhline(y=float(current_sell_price), linewidth=1.5, color="teal", alpha=0.95)
except Exception:
pass
# Right-side price labels (so you can read Bid/Ask/AVG/DCA/Sell at a glance)
try:
trans = blended_transform_factory(self.ax.transAxes, self.ax.transData)
used_y: List[float] = []
y0, y1 = self.ax.get_ylim()
y_pad = max((y1 - y0) * 0.012, 1e-9)
def _label_right(y: Optional[float], tag: str, color: str) -> None:
if y is None:
return
try:
yy = float(y)
if (not math.isfinite(yy)) or yy <= 0:
return
except Exception:
return
# Nudge labels apart if levels are very close
for prev in used_y:
if abs(yy - prev) < y_pad:
yy = prev + y_pad