-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathturtlebot.py
More file actions
1995 lines (1750 loc) · 81.6 KB
/
turtlebot.py
File metadata and controls
1995 lines (1750 loc) · 81.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
"""
╔══════════════════════════════════════════════════════════════════════════════╗
║ ████████╗██╗ ██╗██████╗ ████████╗██╗ ███████╗██████╗ ██████╗ ████████╗ ║
║ ╚══██╔══╝██║ ██║██╔══██╗╚══██╔══╝██║ ██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝ ║
║ ██║ ██║ ██║██████╔╝ ██║ ██║ █████╗ ██████╔╝██║ ██║ ██║ ║
║ ██║ ██║ ██║██╔══██╗ ██║ ██║ ██╔══╝ ██╔══██╗██║ ██║ ██║ ║
║ ██║ ╚██████╔╝██║ ██║ ██║ ███████╗███████╗██████╔╝╚██████╔╝ ██║ ║
║ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ║
║ ║
║ ULTRA ── The Original 1983 Rules, Rebuilt for Crypto ║
║ ══════════════════════════════════════════════════════ ║
║ "We are going to grow traders just like they grow ║
║ turtles in Singapore." ── Richard Dennis, 1983 ║
║ ║
║ System 1: 20-day breakout entry │ 10-day contrary breakout exit ║
║ System 2: 55-day breakout entry │ 20-day contrary breakout exit ║
║ Position Sizing: Volatility-normalized units (1% equity per N) ║
║ Pyramiding: Up to 4 units at ½N intervals ║
║ Stops: 2N from entry, raised ½N per add ║
║ Risk Limits: 4/market, 6/correlated, 10/loose, 12/direction ║
║ Drawdown: -20% notional per -10% equity loss ║
║ ║
║ Paper Trading Engine │ Kraken OHLC Data │ Pydroid3 Compatible ║
╚══════════════════════════════════════════════════════════════════════════════╝
Author : Claude × Jeremy
Version: 1.0.0 ULTRA
License: MIT
"""
import json
import logging
import time
import os
import sys
import threading
from datetime import datetime, timezone, timedelta
from typing import Dict, List, Optional, Tuple
try:
import urllib.request as urlreq
import urllib.error as urlerr
except ImportError:
import urllib2 as urlreq
urlerr = urlreq
# Fleet bus listener
from pathlib import Path as _Path
sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "CommandCenter"))
try:
from bus_listener import BusListener as _BusListener
except ImportError:
_BusListener = None
try:
from event_publisher import EventPublisher as _EventPublisher
except ImportError:
_EventPublisher = None
try:
from expectancy import ExpectancyTracker
_expectancy = ExpectancyTracker()
except Exception:
_expectancy = None
try:
from fleet_config import is_blacklisted as _is_blacklisted
except ImportError:
_is_blacklisted = lambda pair: False
try:
from portfolio_client import PortfolioClient
except ImportError:
PortfolioClient = None
# ═══════════════════════════════════════════════════════════════
# ANSI ESCAPE CODES (Pydroid3 compatible)
# ═══════════════════════════════════════════════════════════════
ESC = "\033["
RESET = f"{ESC}0m"
BOLD = f"{ESC}1m"
DIM = f"{ESC}2m"
ITALIC = f"{ESC}3m"
ULINE = f"{ESC}4m"
# Foreground
BLACK = f"{ESC}30m"
RED = f"{ESC}31m"
GREEN = f"{ESC}32m"
YELLOW = f"{ESC}33m"
BLUE = f"{ESC}34m"
MAGENTA = f"{ESC}35m"
CYAN = f"{ESC}36m"
WHITE = f"{ESC}37m"
# Bright foreground
BRED = f"{ESC}91m"
BGREEN = f"{ESC}92m"
BYELLOW = f"{ESC}93m"
BBLUE = f"{ESC}94m"
BMAGENTA = f"{ESC}95m"
BCYAN = f"{ESC}96m"
BWHITE = f"{ESC}97m"
# Background
BG_BLACK = f"{ESC}40m"
BG_RED = f"{ESC}41m"
BG_GREEN = f"{ESC}42m"
BG_YELLOW = f"{ESC}43m"
BG_BLUE = f"{ESC}44m"
BG_DGRAY = f"{ESC}100m"
CLEAR = f"{ESC}2J{ESC}H"
# ═══════════════════════════════════════════════════════════════
# CONFIGURATION
# ═══════════════════════════════════════════════════════════════
CONFIG = {
# ── Account ──
"starting_equity": 130.00, # Paper trading starting balance
"risk_per_unit_pct": 1.0, # 1% of equity per unit (original rule)
"max_risk_per_trade_pct": 2.0, # 2% max risk per trade (2N stop)
# ── N (ATR) Calculation ──
"n_period": 20, # 20-day EMA for N (original rule)
# ── Entry Rules ──
"s1_entry_days": 20, # System 1: 20-day breakout
"s2_entry_days": 55, # System 2: 55-day breakout
"s1_failsafe_days": 55, # System 1 failsafe breakout
# ── Exit Rules ──
"s1_exit_days": 10, # System 1: 10-day contrary breakout
"s2_exit_days": 20, # System 2: 20-day contrary breakout
# ── Pyramiding ──
"add_interval_n": 0.5, # Add at ½N intervals (original rule)
"max_units_per_market": 4, # Max 4 units per market (original rule)
# ── Stop Loss ──
"stop_n_multiplier": 2.0, # 2N stop (original rule)
"stop_tighten_n": 0.5, # Raise stops ½N per add (original rule)
# ── Portfolio Risk Limits (original rules) ──
"max_units_single_market": 4,
"max_units_closely_correlated": 6,
"max_units_loosely_correlated": 10,
"max_units_single_direction": 12,
# ── Drawdown Adjustment (original rule) ──
"drawdown_threshold_pct": 10.0, # Reduce notional at -10%
"drawdown_reduce_pct": 20.0, # Reduce by 20%
# ── System Allocation ──
"system_mode": "BOTH", # "S1", "S2", or "BOTH" (50/50 split)
# ── Data ──
"ohlc_interval": 1440, # Daily candles (1440 min)
"lookback_days": 120, # Enough for 55-day channels + N calc
"refresh_seconds": 300, # Poll every 5 minutes
# ── Display ──
"terminal_width": 78,
# ── Dashboard ──
"dashboard_port": 5001,
# ── Central Portfolio (Command Center shared capital pool) ──
"use_central_portfolio": False, # Fleet capital pool via Command Center
"command_center_url": "http://127.0.0.1:9000",
}
# ── Markets to Trade ──
# Kraken pairs: [ticker, display_name, correlation_group]
# Correlation groups: BTC, ETH, DEFI, L1, MEME, STABLE
MARKETS = [
("XXBTZUSD", "BTC/USD", "BTC"),
("XETHZUSD", "ETH/USD", "ETH"),
("SOLUSD", "SOL/USD", "L1"),
("XLTCZUSD", "LTC/USD", "BTC"),
("LINKUSD", "LINK/USD", "DEFI"),
("XXLMZUSD", "XLM/USD", "L1"),
("XXRPZUSD", "XRP/USD", "L1"),
("DOTUSD", "DOT/USD", "L1"),
("AAVEUSD", "AAVE/USD", "DEFI"),
("UNIUSD", "UNI/USD", "DEFI"),
]
# Fleet blacklist filter — remove pairs with 0% WR across fleet
MARKETS = [m for m in MARKETS if not _is_blacklisted(m[0])]
# Correlation map for risk limits
CORRELATION_MAP = {
"closely": [
("BTC", "LTC"), # Both PoW store-of-value
("ETH", "DEFI"), # ETH ecosystem
],
"loosely": [
("BTC", "ETH"),
("BTC", "L1"),
("ETH", "L1"),
("DEFI", "L1"),
],
}
# ═══════════════════════════════════════════════════════════════
# DATA LAYER: Kraken OHLC
# ═══════════════════════════════════════════════════════════════
class KrakenData:
"""Fetches and manages OHLC data from Kraken public API."""
BASE_URL = "https://api.kraken.com/0/public"
RATE_LIMIT = 1.0 # seconds between calls (Kraken public API ~1 req/s)
def __init__(self):
self.cache: Dict[str, List[dict]] = {}
self._last_call = 0.0
def _throttle(self):
elapsed = time.time() - self._last_call
if elapsed < self.RATE_LIMIT:
time.sleep(self.RATE_LIMIT - elapsed)
self._last_call = time.time()
def _fetch_json(self, endpoint: str, params: dict) -> dict:
self._throttle()
qs = "&".join(f"{k}={v}" for k, v in params.items())
url = f"{self.BASE_URL}/{endpoint}?{qs}"
try:
req = urlreq.Request(url, headers={"User-Agent": "TurtleBotULTRA/1.0"})
with urlreq.urlopen(req, timeout=15) as resp:
return json.loads(resp.read().decode())
except Exception as e:
return {"error": [str(e)]}
def fetch_ohlc(self, pair: str, interval: int = 1440,
since: Optional[int] = None) -> List[dict]:
"""Fetch OHLC candles. Returns list of dicts with
time, open, high, low, close, volume, vwap, count."""
params = {"pair": pair, "interval": interval}
if since:
params["since"] = since
data = self._fetch_json("OHLC", params)
if data.get("error") and len(data["error"]) > 0:
return []
result = data.get("result", {})
# Kraken returns data under the pair key (varies)
candles = []
for key in result:
if key == "last":
continue
raw = result[key]
for c in raw:
candles.append({
"time": int(c[0]),
"open": float(c[1]),
"high": float(c[2]),
"low": float(c[3]),
"close": float(c[4]),
"vwap": float(c[5]),
"volume": float(c[6]),
"count": int(c[7]),
})
break
candles.sort(key=lambda x: x["time"])
self.cache[pair] = candles
return candles
def fetch_ticker(self, pair: str) -> Optional[dict]:
"""Fetch current ticker data."""
data = self._fetch_json("Ticker", {"pair": pair})
if data.get("error") and len(data["error"]) > 0:
return None
result = data.get("result", {})
for key in result:
t = result[key]
return {
"ask": float(t["a"][0]),
"bid": float(t["b"][0]),
"last": float(t["c"][0]),
"volume": float(t["v"][1]), # 24h volume
"vwap": float(t["p"][1]),
"high": float(t["h"][1]),
"low": float(t["l"][1]),
}
return None
def fetch_all_tickers(self, pairs: List[str]) -> Dict[str, dict]:
"""Fetch tickers for all pairs in a single API call."""
if not pairs:
return {}
self._throttle()
pair_str = ",".join(pairs)
data = self._fetch_json("Ticker", {"pair": pair_str})
if data.get("error") and len(data.get("error", [])) > 0:
logging.warning(f"Ticker batch error: {data['error']}")
return {}
result_data = data.get("result", {})
result = {}
for key, t in result_data.items():
for p in pairs:
if p in key or key in p:
result[p] = {
"ask": float(t["a"][0]),
"bid": float(t["b"][0]),
"last": float(t["c"][0]),
"volume": float(t["v"][1]),
"vwap": float(t["p"][1]),
"high": float(t["h"][1]),
"low": float(t["l"][1]),
}
break
return result
def get_all_ohlc(self, markets: list, interval: int = 1440,
lookback_days: int = 120) -> Dict[str, List[dict]]:
"""Fetch OHLC for all markets."""
since = int((datetime.now(timezone.utc) -
timedelta(days=lookback_days)).timestamp())
result = {}
for pair, name, group in markets:
candles = self.fetch_ohlc(pair, interval, since)
if candles:
result[pair] = candles
return result
# ═══════════════════════════════════════════════════════════════
# TURTLE MATH ENGINE
# ═══════════════════════════════════════════════════════════════
class TurtleMath:
"""Pure calculation functions for the Turtle system."""
@staticmethod
def true_range(high: float, low: float, prev_close: float) -> float:
"""True Range = max(H-L, |H-PDC|, |PDC-L|)"""
return max(high - low, abs(high - prev_close), abs(prev_close - low))
@staticmethod
def compute_n(candles: List[dict], period: int = 20) -> Optional[float]:
"""Compute N = 20-day EMA of True Range (the original ATR).
Uses simple average for initial seed, then EMA formula:
N = (19 * PDN + TR) / 20
"""
if len(candles) < period + 1:
return None
# Initial N: simple average of first `period` true ranges
trs = []
for i in range(1, period + 1):
tr = TurtleMath.true_range(
candles[i]["high"], candles[i]["low"], candles[i-1]["close"]
)
trs.append(tr)
n = sum(trs) / len(trs)
# EMA continuation
for i in range(period + 1, len(candles)):
tr = TurtleMath.true_range(
candles[i]["high"], candles[i]["low"], candles[i-1]["close"]
)
n = (19 * n + tr) / 20 # Original formula from the document
return n
@staticmethod
def compute_n_series(candles: List[dict], period: int = 20) -> List[Optional[float]]:
"""Compute N for every candle (None for insufficient data)."""
n_series = [None] * len(candles)
if len(candles) < period + 1:
return n_series
# Seed
trs = []
for i in range(1, period + 1):
tr = TurtleMath.true_range(
candles[i]["high"], candles[i]["low"], candles[i-1]["close"]
)
trs.append(tr)
n = sum(trs) / len(trs)
n_series[period] = n
for i in range(period + 1, len(candles)):
tr = TurtleMath.true_range(
candles[i]["high"], candles[i]["low"], candles[i-1]["close"]
)
n = (19 * n + tr) / 20
n_series[i] = n
return n_series
@staticmethod
def donchian_channel(candles: List[dict], period: int,
end_idx: int = -1) -> Tuple[float, float]:
"""Compute Donchian Channel (highest high, lowest low) over `period` days.
end_idx is the last candle to consider (exclusive of current for entries)."""
if end_idx == -1:
end_idx = len(candles) - 1
start = max(0, end_idx - period)
subset = candles[start:end_idx]
if not subset:
return (0.0, 0.0)
high = max(c["high"] for c in subset)
low = min(c["low"] for c in subset)
return (high, low)
@staticmethod
def unit_size(equity: float, n: float, risk_pct: float = 1.0) -> float:
"""Calculate unit size in USD notional.
Unit = (risk_pct% of Equity) / N
For crypto spot, Dollars per Point = 1.
Returns number of coins/tokens for 1 unit."""
if n <= 0:
return 0.0
dollar_risk = equity * (risk_pct / 100.0)
return dollar_risk / n
@staticmethod
def market_strength(candles: List[dict], n: float,
lookback: int = 60) -> float:
"""Strength score: (price_now - price_N_days_ago) / N
Higher = stronger uptrend. Used for buy strength / sell weakness."""
if len(candles) < lookback + 1 or n <= 0:
return 0.0
current = candles[-1]["close"]
past = candles[-(lookback + 1)]["close"]
return (current - past) / n
# ═══════════════════════════════════════════════════════════════
# POSITION & TRADE TRACKING
# ═══════════════════════════════════════════════════════════════
class Unit:
"""A single unit within a position (for pyramiding)."""
def __init__(self, entry_price: float, size: float, stop: float,
timestamp: int, unit_num: int, n: float = 0.0):
self.entry_price = entry_price
self.size = size # Quantity of asset
self.stop = stop
self.timestamp = timestamp
self.unit_num = unit_num # 1-4
self.n = n # N (ATR) at time of entry (for persistence)
class Position:
"""A full position in a market, consisting of up to 4 units."""
def __init__(self, pair: str, direction: str, system: int):
self.pair = pair
self.direction = direction # "LONG" or "SHORT"
self.system = system # 1 or 2
self.units: List[Unit] = []
self.entry_n: float = 0.0 # N at time of initial entry
self.opened_at: int = 0
self.reservation_ids: List[str] = [] # Central portfolio reservation IDs
@property
def num_units(self) -> int:
return len(self.units)
@property
def total_size(self) -> float:
return sum(u.size for u in self.units)
@property
def avg_entry(self) -> float:
if not self.units:
return 0.0
total_cost = sum(u.entry_price * u.size for u in self.units)
total_sz = self.total_size
return total_cost / total_sz if total_sz > 0 else 0.0
@property
def current_stop(self) -> float:
"""All units share the tightest stop (2N from most recent add)."""
if not self.units:
return 0.0
return self.units[-1].stop
def unrealized_pnl(self, current_price: float) -> float:
if self.direction == "LONG":
return sum(u.size * (current_price - u.entry_price) for u in self.units)
else:
return sum(u.size * (u.entry_price - current_price) for u in self.units)
def add_unit(self, entry_price: float, size: float, n: float, timestamp: int):
"""Add a unit and update all stops per original rules."""
unit_num = len(self.units) + 1
if self.direction == "LONG":
stop = entry_price - CONFIG["stop_n_multiplier"] * n
else:
stop = entry_price + CONFIG["stop_n_multiplier"] * n
new_unit = Unit(entry_price, size, stop, timestamp, unit_num, n=n)
self.units.append(new_unit)
# Original rule: raise all stops to 2N from most recent unit
for u in self.units:
u.stop = stop
def check_stop(self, current_price: float) -> bool:
"""Returns True if stop is hit."""
if not self.units:
return False
stop = self.current_stop
if self.direction == "LONG":
return current_price <= stop
else:
return current_price >= stop
class TradeLog:
"""Records completed trades for performance analysis."""
def __init__(self):
self.trades: List[dict] = []
def record(self, pair: str, direction: str, system: int,
entry_price: float, exit_price: float, size: float,
n_at_entry: float, pnl: float, entry_time: int,
exit_time: int, exit_reason: str):
self.trades.append({
"pair": pair,
"direction": direction,
"system": system,
"entry": entry_price,
"exit": exit_price,
"size": size,
"n": n_at_entry,
"pnl": pnl,
"pnl_in_n": pnl / (n_at_entry * size) if n_at_entry * size > 0 else 0,
"entry_time": entry_time,
"exit_time": exit_time,
"exit_reason": exit_reason,
})
if len(self.trades) > 1000:
self.trades = self.trades[-1000:]
@property
def total_pnl(self) -> float:
return sum(t["pnl"] for t in self.trades)
@property
def win_rate(self) -> float:
if not self.trades:
return 0.0
wins = sum(1 for t in self.trades if t["pnl"] > 0)
return wins / len(self.trades) * 100
@property
def avg_win(self) -> float:
wins = [t["pnl"] for t in self.trades if t["pnl"] > 0]
return sum(wins) / len(wins) if wins else 0.0
@property
def avg_loss(self) -> float:
losses = [t["pnl"] for t in self.trades if t["pnl"] <= 0]
return sum(losses) / len(losses) if losses else 0.0
@property
def profit_factor(self) -> float:
gross_profit = sum(t["pnl"] for t in self.trades if t["pnl"] > 0)
gross_loss = abs(sum(t["pnl"] for t in self.trades if t["pnl"] < 0))
return gross_profit / gross_loss if gross_loss > 0 else 0.0
@property
def expectancy_r(self) -> float:
"""Expectancy in R-multiples (N units)."""
if not self.trades:
return 0.0
return sum(t["pnl_in_n"] for t in self.trades) / len(self.trades)
def last_breakout_result(self, pair: str) -> Optional[str]:
"""Return 'WIN' or 'LOSS' for the last breakout trade on this pair.
Used for System 1 filter rule."""
for t in reversed(self.trades):
if t["pair"] == pair:
return "WIN" if t["pnl"] > 0 else "LOSS"
return None
# ═══════════════════════════════════════════════════════════════
# THE TURTLE ENGINE
# ═══════════════════════════════════════════════════════════════
class TurtleEngine:
"""Core trading engine implementing ALL original Turtle rules."""
def __init__(self):
self.equity = CONFIG["starting_equity"]
self.starting_equity = CONFIG["starting_equity"]
self.notional_equity = CONFIG["starting_equity"] # For drawdown adj
self.peak_equity = CONFIG["starting_equity"]
self.positions: Dict[str, Position] = {}
self.trade_log = TradeLog()
self.data = KrakenData()
self.market_data: Dict[str, List[dict]] = {}
self.n_values: Dict[str, float] = {}
self.tickers: Dict[str, dict] = {}
self.signals: List[dict] = []
self.all_signals: List[dict] = [] # Full history for dashboard
self.last_scan_time = 0
self.scan_count = 0
self.errors: List[str] = []
self.strength_rank: List[Tuple[str, float]] = []
self.equity_curve: List[dict] = [] # For dashboard charts
# Breakout tracking for System 1 filter
self.last_breakout_outcome: Dict[str, str] = {}
# Snapshot cache — rebuilt only after each scan, not on every 2s poll
self._snapshot_cache = None
self._snapshot_dirty = True
# Central portfolio client (init before position persistence so reconcile works)
self._portfolio_client = None
if CONFIG["use_central_portfolio"]:
self._portfolio_client = PortfolioClient(CONFIG["command_center_url"], "turtlesue")
# Position persistence for crash recovery
self._positions_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "turtle_positions.json")
self._load_positions()
self._load_state()
self._reconcile_positions()
# Fleet bus listener + publisher
self._bus = _BusListener() if _BusListener else None
self._event_pub = _EventPublisher(CONFIG["command_center_url"], "turtlesue") if _EventPublisher else None
# ── Position Persistence ──
def _load_positions(self):
"""Load positions from disk on startup."""
if not os.path.exists(self._positions_file):
return
try:
with open(self._positions_file, "r") as f:
data = json.load(f)
loaded = 0
for pair, pdata in data.get("positions", {}).items():
pos = Position(pdata.get("pair"), pdata.get("direction"), pdata.get("system"))
pos.entry_n = pdata.get("entry_n", 0)
pos.opened_at = pdata.get("opened_at", 0)
pos.reservation_ids = pdata.get("reservation_ids", [])
for udata in pdata.get("units", []):
pos.add_unit(udata["entry_price"], udata["size"], udata["n"], udata["timestamp"])
self.positions[pair] = pos
loaded += 1
if loaded > 0:
logging.info(f"Restored {loaded} position(s) from {self._positions_file}")
except Exception as e:
logging.warning(f"Failed to load positions from {self._positions_file}: {e}")
def _save_positions(self):
"""Atomic save of positions to disk."""
try:
data = {"positions": {}, "saved_at": time.time()}
for pair, pos in self.positions.items():
data["positions"][pair] = {
"pair": pos.pair,
"direction": pos.direction,
"system": pos.system,
"entry_n": pos.entry_n,
"opened_at": pos.opened_at,
"reservation_ids": pos.reservation_ids,
"units": [{"entry_price": u.entry_price, "size": u.size, "n": u.n, "timestamp": u.timestamp} for u in pos.units],
}
tmp = self._positions_file + ".tmp"
with open(tmp, "w") as f:
json.dump(data, f)
os.replace(tmp, self._positions_file)
except Exception as e:
logging.warning(f"Failed to save positions: {e}")
def _save_state(self):
"""Save full engine state for crash recovery (equity, trades, signals)."""
try:
state = {
"equity": self.equity,
"starting_equity": self.starting_equity,
"peak_equity": self.peak_equity,
"notional_equity": self.notional_equity,
"scan_count": self.scan_count,
"last_scan_time": self.last_scan_time,
"last_breakout_outcome": self.last_breakout_outcome,
"equity_curve": self.equity_curve[-500:],
"all_signals": self.all_signals[-200:],
"trades": self.trade_log.trades[-1000:],
"saved_at": time.time(),
}
state_file = self._positions_file.replace("_positions.json", "_state.json")
tmp = state_file + ".tmp"
with open(tmp, "w") as f:
json.dump(state, f)
os.replace(tmp, state_file)
except Exception as e:
logging.warning(f"Failed to save state: {e}")
def _load_state(self):
"""Load full engine state on startup (equity, trades, signals)."""
state_file = self._positions_file.replace("_positions.json", "_state.json")
if not os.path.exists(state_file):
return
try:
with open(state_file, "r") as f:
data = json.load(f)
self.equity = data.get("equity", self.starting_equity)
self.peak_equity = data.get("peak_equity", self.equity)
self.notional_equity = data.get("notional_equity", self.equity)
self.scan_count = data.get("scan_count", 0)
self.last_scan_time = data.get("last_scan_time", 0)
self.last_breakout_outcome = data.get("last_breakout_outcome", {})
self.equity_curve = data.get("equity_curve", [])
self.all_signals = data.get("all_signals", [])
self.trade_log.trades = data.get("trades", [])
logging.info(f"State restored: equity=${self.equity:.2f}, {len(self.trade_log.trades)} trades")
except Exception as e:
logging.warning(f"Failed to load state: {e}")
# ── Portfolio Reconciliation ──
def _reconcile_positions(self):
"""On startup, verify reservations are still valid. Try to re-reserve if stale."""
if not self._portfolio_client:
return
reservations = self._portfolio_client.get_reservations()
if not reservations:
return
for pair, pos in list(self.positions.items()):
stale_rids = [rid for rid in pos.reservation_ids if rid not in reservations]
if not stale_rids:
continue
# Try to re-reserve
amount = pos.total_size * pos.avg_entry
ok, new_rid = self._portfolio_client.reserve(pair, pos.direction, amount)
if ok:
pos.reservation_ids = [new_rid]
self._save_positions()
logging.info(f"Re-reserved {pair}: {new_rid}")
else:
# Close position - no capital; use current price if available
logging.warning(f"Stale reservation for {pair}, re-reserve failed: {new_rid} - closing")
ticker = self.data.fetch_ticker(pair)
exit_price = ticker["last"] if ticker else pos.avg_entry
self._execute_exit(pair, {"type": "stale_reservation", "price": exit_price})
# ── Drawdown Adjustment (Original Rule) ──
def _adjusted_equity(self) -> float:
"""Reduce notional equity by 20% for each 10% drawdown."""
drawdown_pct = 0.0
if self.starting_equity > 0:
drawdown_pct = (self.starting_equity - self.equity) / self.starting_equity * 100
reductions = int(drawdown_pct / CONFIG["drawdown_threshold_pct"])
if reductions <= 0:
return self.equity
reduction_factor = (1 - CONFIG["drawdown_reduce_pct"] / 100) ** reductions
return self.equity * reduction_factor
# ── Risk Limit Checks (Original Rules) ──
def _count_units_for_market(self, pair: str) -> int:
pos = self.positions.get(pair)
return pos.num_units if pos else 0
def _count_units_correlated(self, group: str, direction: str,
correlation_type: str) -> int:
"""Count units in correlated markets for a given direction."""
count = 0
related_groups = set()
related_groups.add(group)
corr_pairs = CORRELATION_MAP.get(correlation_type, [])
for g1, g2 in corr_pairs:
if g1 == group:
related_groups.add(g2)
elif g2 == group:
related_groups.add(g1)
for pair, pos in self.positions.items():
if pos.direction != direction:
continue
mkt = next((m for m in MARKETS if m[0] == pair), None)
if mkt and mkt[2] in related_groups:
count += pos.num_units
return count
def _count_units_direction(self, direction: str) -> int:
return sum(p.num_units for p in self.positions.values()
if p.direction == direction)
def _can_add_unit(self, pair: str, direction: str, group: str) -> bool:
"""Check ALL risk limit levels before adding a unit."""
if self._count_units_for_market(pair) >= CONFIG["max_units_single_market"]:
return False
closely = self._count_units_correlated(group, direction, "closely")
if closely >= CONFIG["max_units_closely_correlated"]:
return False
loosely = self._count_units_correlated(group, direction, "loosely")
if loosely >= CONFIG["max_units_loosely_correlated"]:
return False
if self._count_units_direction(direction) >= CONFIG["max_units_single_direction"]:
return False
return True
# ── Signal Detection ──
def _check_system1_entry(self, pair: str, candles: List[dict],
n: float, current_price: float,
group: str) -> Optional[dict]:
"""System 1: 20-day breakout with winner filter."""
if len(candles) < CONFIG["s1_entry_days"] + 1:
return None
hi, lo = TurtleMath.donchian_channel(
candles, CONFIG["s1_entry_days"], len(candles))
signal = None
if current_price > hi:
signal = {"direction": "LONG", "breakout_price": hi}
elif current_price < lo:
signal = {"direction": "SHORT", "breakout_price": lo}
if not signal:
return None
# ── System 1 Filter: Skip if last breakout was a winner ──
last_result = self.trade_log.last_breakout_result(pair)
if last_result == "WIN":
if len(candles) >= CONFIG["s1_failsafe_days"] + 1:
hi55, lo55 = TurtleMath.donchian_channel(
candles, CONFIG["s1_failsafe_days"], len(candles))
if signal["direction"] == "LONG" and current_price > hi55:
return {
"pair": pair, "system": 1, "type": "FAILSAFE",
"direction": "LONG", "price": current_price,
"breakout": hi55, "n": n, "group": group,
}
elif signal["direction"] == "SHORT" and current_price < lo55:
return {
"pair": pair, "system": 1, "type": "FAILSAFE",
"direction": "SHORT", "price": current_price,
"breakout": lo55, "n": n, "group": group,
}
return None
return {
"pair": pair, "system": 1, "type": "BREAKOUT",
"direction": signal["direction"], "price": current_price,
"breakout": signal["breakout_price"], "n": n, "group": group,
}
def _check_system2_entry(self, pair: str, candles: List[dict],
n: float, current_price: float,
group: str) -> Optional[dict]:
"""System 2: 55-day breakout, take ALL signals."""
if len(candles) < CONFIG["s2_entry_days"] + 1:
return None
hi, lo = TurtleMath.donchian_channel(
candles, CONFIG["s2_entry_days"], len(candles))
if current_price > hi:
return {
"pair": pair, "system": 2, "type": "BREAKOUT",
"direction": "LONG", "price": current_price,
"breakout": hi, "n": n, "group": group,
}
elif current_price < lo:
return {
"pair": pair, "system": 2, "type": "BREAKOUT",
"direction": "SHORT", "price": current_price,
"breakout": lo, "n": n, "group": group,
}
return None
def _check_pyramid(self, pair: str, pos: Position, n: float,
current_price: float, group: str) -> Optional[dict]:
"""Check if we should add a unit (half-N from last entry)."""
if pos.num_units >= CONFIG["max_units_per_market"]:
return None
last_entry = pos.units[-1].entry_price
interval = CONFIG["add_interval_n"] * n
if pos.direction == "LONG":
target = last_entry + interval
if current_price >= target:
return {
"pair": pair, "system": pos.system, "type": "PYRAMID",
"direction": "LONG", "price": current_price,
"unit_num": pos.num_units + 1, "n": n, "group": group,
}
else:
target = last_entry - interval
if current_price <= target:
return {
"pair": pair, "system": pos.system, "type": "PYRAMID",
"direction": "SHORT", "price": current_price,
"unit_num": pos.num_units + 1, "n": n, "group": group,
}
return None
def _check_exit(self, pair: str, pos: Position,
candles: List[dict], current_price: float) -> Optional[dict]:
"""Check exit conditions: Donchian contrary breakout or stop hit."""
# ── Stop Loss Check ──
if pos.check_stop(current_price):
return {
"pair": pair, "type": "STOP_LOSS", "direction": pos.direction,
"price": current_price, "stop": pos.current_stop,
}
# ── Donchian Exit ──
exit_days = (CONFIG["s1_exit_days"] if pos.system == 1
else CONFIG["s2_exit_days"])
if len(candles) < exit_days + 1:
return None
hi, lo = TurtleMath.donchian_channel(
candles, exit_days, len(candles))
if pos.direction == "LONG" and current_price <= lo:
return {
"pair": pair, "type": "EXIT", "direction": "LONG",
"price": current_price, "channel": lo,
"exit_days": exit_days,
}
elif pos.direction == "SHORT" and current_price >= hi:
return {
"pair": pair, "type": "EXIT", "direction": "SHORT",
"price": current_price, "channel": hi,
"exit_days": exit_days,
}
return None
# ── Order Execution ──
def _execute_entry(self, signal: dict):
"""Execute a new position entry."""
pair = signal["pair"]
direction = signal["direction"]
n = signal["n"]
price = signal["price"]
group = signal["group"]
system = signal["system"]
if not self._can_add_unit(pair, direction, group):
return
# Bus intelligence — fleet context for breakout entries
_bus_mult = 1.0
if self._bus:
try:
if self._bus.emergency_active(max_age=300):
self.errors.append(f"BUS SKIP {pair}: emergency active")
return
# ΦTEX CRITICAL + aligned direction = this breakout is real
if self._bus.phitex_critical(pair, max_age=120):
_pt = self._bus.phitex_status(pair)
_pt_dir = (_pt.get("fleet_direction", "") or "").upper() if _pt else ""
if _pt_dir == direction.upper():
_bus_mult *= 1.3
# AEGIS DEPLOY = aggressive breakouts
_a = self._bus.aegis_regime()
if _a == "DEPLOY":
_bus_mult *= 1.2
elif _a == "DEFENSIVE":
_bus_mult *= 0.7
# Whale EXTREME on this pair
_wt = self._bus.whale_tier(pair, max_age=300)
if _wt == "EXTREME":
_bus_mult *= 1.3
# NEWTON: Force alignment
_newton = self._bus.newton_force(pair, max_age=120)
if _newton:
if (_newton["direction"] == "BULL" and direction.upper() == "LONG") or \
(_newton["direction"] == "BEAR" and direction.upper() == "SHORT"):
_bus_mult *= 1 + min(0.3, _newton["inertia"] * 0.4)
elif _newton["direction"] != "NEUTRAL":
_bus_mult *= 0.7
# EUCLID: Support/resistance awareness
_euclid = self._bus.euclid_levels(pair, max_age=120)
for _le in _euclid:
_ld = _le.get("data", {})
if _ld.get("type") == "RESISTANCE_APPROACHING" and direction.upper() == "LONG":
_bus_mult *= 0.7
break
elif _ld.get("type") == "SUPPORT_APPROACHING" and direction.upper() == "SHORT":
_bus_mult *= 0.7
break
_bus_mult = max(0.3, min(2.0, _bus_mult))
except Exception:
_bus_mult = 1.0
adj_equity = self._adjusted_equity()
unit_coins = TurtleMath.unit_size(adj_equity, n, CONFIG["risk_per_unit_pct"])
unit_coins *= _bus_mult
cost = unit_coins * price
# Minimum trade size check - reject trades too small to be viable after fees
if cost < 50:
self.errors.append(f"Trade too small: ${cost:.2f} < $50 minimum")
return
if cost > self.equity * 0.95: