-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
2333 lines (2009 loc) · 98 KB
/
bot.py
File metadata and controls
2333 lines (2009 loc) · 98 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
"""
╔══════════════════════════════════════════════════════════════════════════╗
║ AthenaAI TRADING BOT v5.0 — BinaryOptionsToolsV2 / PocketOption ║
║ Online-learning engine that improves with every trade it makes. ║
║ ║
║ Features: ║
║ • 5-model ensemble (SGD, PA, NB + GBM, RandomForest) ║
║ • 40+ engineered features from raw candle data ║
║ • AI EXPIRY SELECTION — picks optimal duration per trade ║
║ • Automatic regime detection (trending / ranging / volatile) ║
║ • Rolling performance tracker with adaptive cooldowns ║
║ • Brain persistence — models survive restarts ║
║ • Full trade journal persisted to SQLite ║
║ ║
║ ⚠ USE ON DEMO FIRST. Binary options carry extreme risk. ║
╚══════════════════════════════════════════════════════════════════════════╝
"""
from __future__ import annotations
import asyncio
import json
import logging
import math
import os
import sqlite3
import sys
import time
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Optional
import json
import numpy as np
import pickle
# ---------------------------------------------------------------------------
# BinaryOptionsToolsV2 imports
# ---------------------------------------------------------------------------
try:
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
except ImportError:
print("ERROR: BinaryOptionsToolsV2 not installed.")
print("Install with: pip install binaryoptionstoolsv2")
sys.exit(1)
# ---------------------------------------------------------------------------
# Optional heavy imports — graceful fallback
# ---------------------------------------------------------------------------
try:
from sklearn.linear_model import SGDClassifier, PassiveAggressiveClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
SKLEARN_OK = True
except ImportError:
SKLEARN_OK = False
print("WARNING: scikit-learn not found. Install with: pip install scikit-learn")
print("The bot will run with a simplified rule-based fallback.\n")
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
LOG_FMT = "%(asctime)s │ %(levelname)-7s │ %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FMT, datefmt="%H:%M:%S")
log = logging.getLogger("AIBot")
# ═══════════════════════════════════════════════════════════════════════════
# CONFIGURATION
# ═══════════════════════════════════════════════════════════════════════════
@dataclass
class BotConfig:
"""All tuneable knobs in one place."""
# --- connection ---
ssid: str = "" # PocketOption session ID
asset: str = "EURUSD" # trading pair
timeframe: int = 60 # candle period (60s for data)
# --- AI expiry selection ---
expiry_options: tuple = (60, 120, 180, 300) # seconds AI can pick from
default_expiry: int = 60 # fallback / training label horizon
# --- money management ---
base_stake: float = 10.0 # minimum trade size ($)
max_stake: float = 100.0 # hard ceiling ($)
kelly_fraction: float = 0.50 # fraction of Kelly to use
max_daily_loss: float = 300.0 # stop-loss for the day ($)
max_concurrent_trades: int = 1 # max open trades
# --- ML & signals ---
warmup_candles: int = 60 # candles before first trade
min_confidence: float = 0.60 # lowered — batch models handle quality
retrain_every: int = 10 # partial_fit after N new samples
lookback: int = 200 # max candle history to keep
feature_window: int = 20 # rolling window for features
# --- signal readiness ---
signal_confirmations: int = 1 # 1 = instant (no multi-candle wait)
require_indicator_alignment: bool = False # disabled — ML already uses these
skip_volatile_regime: bool = False # let ML decide
min_wait_between_trades: int = 60 # 1 min between trades
# --- dataset pre-training ---
dataset_path: str = "" # path to CSV for pre-training (optional)
# --- risk / cooldown ---
max_consec_losses: int = 3 # pause after 5 consecutive losses
cooldown_seconds: int = 300 # 5 min cooldown
regime_window: int = 30 # candles for regime detection
# --- persistence ---
db_path: str = "trade_journal.db"
brain_path: str = "athena_po_brain.pkl" # saved models
# --- misc ---
poll_interval: float = 2.0 # check every 2s
# ═══════════════════════════════════════════════════════════════════════════
# ENUMS & DATA CLASSES
# ═══════════════════════════════════════════════════════════════════════════
class Direction(Enum):
CALL = "call"
PUT = "put"
class Regime(Enum):
TRENDING_UP = "trending_up"
TRENDING_DOWN = "trending_down"
RANGING = "ranging"
VOLATILE = "volatile"
@dataclass
class Candle:
timestamp: float
open: float
high: float
low: float
close: float
volume: float = 0.0
@dataclass
class TradeRecord:
id: str
direction: str
asset: str
stake: float
confidence: float
regime: str
entry_time: float
expiry: int = 120 # AI-chosen expiry in seconds
result: Optional[str] = None # "win" / "loss" / "draw"
profit: Optional[float] = None
exit_time: Optional[float] = None
features_json: Optional[str] = None # stored feature vector as JSON
# ═══════════════════════════════════════════════════════════════════════════
# FEATURE ENGINEERING (40 core + experimental features from raw OHLCV)
# ═══════════════════════════════════════════════════════════════════════════
class FeatureEngine:
"""Converts a window of candles into a numeric feature vector.
Core features (always on) + experimental features (can be masked)."""
# Names for logging — core features (indices 0-39)
CORE_NAMES = [
"body", "range", "mom_1", "mom_5",
"ret_last", "ret_mean", "volatility",
"price_sma5", "price_sma10", "price_sma20", "ma_cross", "macd_line",
"macd_hist",
"rsi", "rsi_zone",
"bb_width", "bb_pos",
"atr", "range_vs_atr",
"stoch_k", "stoch_d", "stoch_diff",
"cci", "williams_r", "adx",
"rel_volume", "vol_std",
"doji", "hammer", "engulfing",
"ret_p25", "ret_p75", "skew", "kurt",
"fractal_dim",
"streak",
"time_sin_h", "time_cos_h", "time_sin_d", "time_cos_d",
]
# Experimental feature names (indices 40+)
EXPERIMENTAL_NAMES = [
"shooting_star", "bearish_engulfing", # candlestick
"sma50_dist", "sma50_above", # long trend
"momentum_ratio", # 14/28 MA ratio
"fib_dist_236", "fib_dist_382", # fibonacci
"fib_dist_500", "fib_dist_618",
"support_dist", "resist_dist", # S/R
"hl_ratio", "oc_ratio", # price ratios
"rsi_divergence", "volume_spike", # divergence & spike
"candle_wick_ratio", "body_vs_avg", # candle anatomy
]
NUM_CORE = len(CORE_NAMES) # 40
NUM_EXPERIMENTAL = len(EXPERIMENTAL_NAMES) # 17
def __init__(self):
# Mask: 1.0 = active, 0.0 = masked off. Core always 1.0
self.feature_mask = np.ones(self.NUM_CORE + self.NUM_EXPERIMENTAL, dtype=np.float64)
self.experimental_enabled = True # master switch
def compute(self, candles: list[Candle], window: int = 20) -> Optional[np.ndarray]:
if len(candles) < max(window, 26):
return None
closes = np.array([c.close for c in candles])
highs = np.array([c.high for c in candles])
lows = np.array([c.low for c in candles])
opens = np.array([c.open for c in candles])
vols = np.array([c.volume for c in candles])
feats: list[float] = []
# ============ CORE FEATURES (0-39) — always active ============
# --- Price-action ---
feats.append(closes[-1] - opens[-1]) # current body
feats.append(highs[-1] - lows[-1]) # current range
feats.append(closes[-1] - closes[-2]) # 1-bar momentum
feats.append(closes[-1] - closes[-5] if len(closes) >= 5 else 0) # 5-bar mom
# --- Returns ---
rets = np.diff(closes) / (closes[:-1] + 1e-10)
feats.append(rets[-1]) # latest return
feats.append(np.mean(rets[-window:])) # mean return
feats.append(np.std(rets[-window:])) # volatility
# --- Moving averages ---
sma5 = np.mean(closes[-5:])
sma10 = np.mean(closes[-10:])
sma20 = np.mean(closes[-window:])
ema12 = FeatureEngine._ema(closes, 12)
ema26 = FeatureEngine._ema(closes, 26)
feats.append(closes[-1] - sma5)
feats.append(closes[-1] - sma10)
feats.append(closes[-1] - sma20)
feats.append(sma5 - sma20) # MA cross
feats.append(ema12 - ema26) # MACD line
# --- MACD signal & histogram ---
macd_line_arr = FeatureEngine._ema_array(closes, 12) - FeatureEngine._ema_array(closes, 26)
signal_line = FeatureEngine._ema(macd_line_arr, 9)
feats.append(macd_line_arr[-1] - signal_line) # MACD histogram
# --- RSI ---
rsi = FeatureEngine._rsi(closes, 14)
feats.append(rsi)
feats.append(1.0 if rsi > 70 else (-1.0 if rsi < 30 else 0.0)) # overbought/sold
# --- Bollinger Bands ---
bb_mid = sma20
bb_std = np.std(closes[-window:])
bb_upper = bb_mid + 2 * bb_std
bb_lower = bb_mid - 2 * bb_std
bb_width = (bb_upper - bb_lower) / (bb_mid + 1e-10)
bb_pos = (closes[-1] - bb_lower) / (bb_upper - bb_lower + 1e-10)
feats.append(bb_width)
feats.append(bb_pos)
# --- ATR ---
atr = FeatureEngine._atr(highs, lows, closes, 14)
feats.append(atr)
feats.append((highs[-1] - lows[-1]) / (atr + 1e-10)) # current range vs ATR
# --- Stochastic %K / %D ---
stoch_k, stoch_d = FeatureEngine._stochastic(highs, lows, closes, 14, 3)
feats.append(stoch_k)
feats.append(stoch_d)
feats.append(stoch_k - stoch_d)
# --- CCI ---
cci = FeatureEngine._cci(highs, lows, closes, 20)
feats.append(cci)
# --- Williams %R ---
will_r = FeatureEngine._williams_r(highs, lows, closes, 14)
feats.append(will_r)
# --- ADX (simplified) ---
adx = FeatureEngine._adx(highs, lows, closes, 14)
feats.append(adx)
# --- Volume features ---
if np.any(vols > 0):
feats.append(vols[-1] / (np.mean(vols[-window:]) + 1e-10)) # relative volume
feats.append(np.std(vols[-window:]) / (np.mean(vols[-window:]) + 1e-10))
else:
feats.extend([1.0, 0.0])
# --- Candle patterns (encoded) ---
feats.append(FeatureEngine._doji(opens, highs, lows, closes))
feats.append(FeatureEngine._hammer(opens, highs, lows, closes))
feats.append(FeatureEngine._engulfing(opens, closes))
# --- Higher-order stats ---
feats.append(float(np.percentile(rets[-window:], 25)))
feats.append(float(np.percentile(rets[-window:], 75)))
skew = FeatureEngine._skewness(rets[-window:])
kurt = FeatureEngine._kurtosis(rets[-window:])
feats.append(skew)
feats.append(kurt)
# --- Fractal dimension (Higuchi approx) ---
feats.append(FeatureEngine._higuchi_fd(closes[-window:]))
# --- Streak features ---
streak = 0
for i in range(len(closes) - 1, 0, -1):
if closes[i] > closes[i - 1]:
streak += 1
elif closes[i] < closes[i - 1]:
streak -= 1
else:
break
if abs(streak) >= 10:
break
feats.append(float(streak))
# --- Time features (cyclical) ---
ts = candles[-1].timestamp
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
hour = dt.hour + dt.minute / 60.0
feats.append(math.sin(2 * math.pi * hour / 24))
feats.append(math.cos(2 * math.pi * hour / 24))
dow = dt.weekday()
feats.append(math.sin(2 * math.pi * dow / 7))
feats.append(math.cos(2 * math.pi * dow / 7))
# ============ EXPERIMENTAL FEATURES (40+) — can be masked ============
if self.experimental_enabled:
# Shooting star pattern
body = abs(closes[-1] - opens[-1])
upper_wick = highs[-1] - max(opens[-1], closes[-1])
lower_wick = min(opens[-1], closes[-1]) - lows[-1]
feats.append(1.0 if (body > 1e-10 and upper_wick > 2 * body and lower_wick < body) else 0.0)
# Bearish engulfing
if len(opens) >= 2:
prev_bull = closes[-2] > opens[-2]
curr_bear = closes[-1] < opens[-1]
engulfs = opens[-1] > closes[-2] and closes[-1] < opens[-2]
feats.append(1.0 if (prev_bull and curr_bear and engulfs) else 0.0)
else:
feats.append(0.0)
# SMA 50
if len(closes) >= 50:
sma50 = np.mean(closes[-50:])
feats.append(closes[-1] - sma50)
feats.append(1.0 if closes[-1] > sma50 else -1.0)
else:
feats.extend([0.0, 0.0])
# Price momentum ratio (14/28 MA)
if len(closes) >= 28:
feats.append(np.mean(closes[-14:]) / (np.mean(closes[-28:]) + 1e-10))
else:
feats.append(1.0)
# Fibonacci distances
if len(highs) >= 50:
recent_high = np.max(highs[-50:])
recent_low = np.min(lows[-50:])
fib_range = recent_high - recent_low
price = closes[-1]
feats.append((price - (recent_high - 0.236 * fib_range)) / (fib_range + 1e-10))
feats.append((price - (recent_high - 0.382 * fib_range)) / (fib_range + 1e-10))
feats.append((price - (recent_high - 0.500 * fib_range)) / (fib_range + 1e-10))
feats.append((price - (recent_high - 0.618 * fib_range)) / (fib_range + 1e-10))
else:
feats.extend([0.0, 0.0, 0.0, 0.0])
# Support / Resistance distance
support = np.min(lows[-window:])
resistance = np.max(highs[-window:])
price = closes[-1]
feats.append((price - support) / (support + 1e-10))
feats.append((resistance - price) / (price + 1e-10))
# High/Low ratio & Open/Close ratio
feats.append(highs[-1] / (lows[-1] + 1e-10))
feats.append(opens[-1] / (closes[-1] + 1e-10))
# RSI divergence (price making higher highs but RSI making lower highs)
if len(closes) >= 28:
rsi_arr = []
for j in range(max(0, len(closes) - 14), len(closes)):
rsi_arr.append(FeatureEngine._rsi(closes[:j+1], 14))
price_trend = closes[-1] - closes[-14]
rsi_trend = rsi_arr[-1] - rsi_arr[0] if len(rsi_arr) >= 2 else 0
feats.append(1.0 if (price_trend > 0 and rsi_trend < -5) else
(-1.0 if (price_trend < 0 and rsi_trend > 5) else 0.0))
else:
feats.append(0.0)
# Volume spike (current volume vs 20-period average)
if np.any(vols > 0):
avg_vol = np.mean(vols[-window:])
feats.append(vols[-1] / (avg_vol + 1e-10) if avg_vol > 0 else 1.0)
else:
feats.append(1.0)
# Candle wick ratio (total wicks / body)
body = abs(closes[-1] - opens[-1])
total_wick = (highs[-1] - lows[-1]) - body
feats.append(total_wick / (body + 1e-10))
# Body vs average body (is this candle unusually big/small?)
avg_body = np.mean(np.abs(closes[-window:] - opens[-window:]))
feats.append(body / (avg_body + 1e-10))
else:
# Experimental disabled — fill with zeros to keep dimensions
feats.extend([0.0] * self.NUM_EXPERIMENTAL)
# ============ APPLY MASK ============
result = np.array(feats, dtype=np.float64)
if len(result) == len(self.feature_mask):
result *= self.feature_mask
return result
# ---- Helpers ----
@staticmethod
def _ema(data: np.ndarray, span: int) -> float:
if len(data) < span:
return float(np.mean(data))
alpha = 2.0 / (span + 1)
val = float(data[0])
for d in data[1:]:
val = alpha * d + (1 - alpha) * val
return val
@staticmethod
def _ema_array(data: np.ndarray, span: int) -> np.ndarray:
alpha = 2.0 / (span + 1)
out = np.empty_like(data, dtype=np.float64)
out[0] = data[0]
for i in range(1, len(data)):
out[i] = alpha * data[i] + (1 - alpha) * out[i - 1]
return out
@staticmethod
def _rsi(closes: np.ndarray, period: int = 14) -> float:
if len(closes) < period + 1:
return 50.0
deltas = np.diff(closes[-(period + 1):])
gain = np.mean(np.maximum(deltas, 0))
loss = np.mean(np.maximum(-deltas, 0))
if loss < 1e-10:
return 100.0
rs = gain / loss
return 100.0 - 100.0 / (1.0 + rs)
@staticmethod
def _atr(highs, lows, closes, period=14):
if len(closes) < period + 1:
return float(np.mean(highs[-period:] - lows[-period:]))
tr = np.maximum(
highs[1:] - lows[1:],
np.maximum(
np.abs(highs[1:] - closes[:-1]),
np.abs(lows[1:] - closes[:-1])
)
)
return float(np.mean(tr[-period:]))
@staticmethod
def _stochastic(highs, lows, closes, k_period=14, d_period=3):
if len(closes) < k_period:
return 50.0, 50.0
low_min = np.min(lows[-k_period:])
high_max = np.max(highs[-k_period:])
k = 100.0 * (closes[-1] - low_min) / (high_max - low_min + 1e-10)
# Simple %D
k_vals = []
for i in range(min(d_period, len(closes) - k_period + 1)):
idx = -(1 + i)
lm = np.min(lows[idx - k_period + 1: len(lows) + idx + 1]) if idx != -1 else low_min
hm = np.max(highs[idx - k_period + 1: len(highs) + idx + 1]) if idx != -1 else high_max
k_vals.append(100.0 * (closes[idx] - lm) / (hm - lm + 1e-10))
d = float(np.mean(k_vals)) if k_vals else k
return k, d
@staticmethod
def _cci(highs, lows, closes, period=20):
if len(closes) < period:
return 0.0
tp = (highs[-period:] + lows[-period:] + closes[-period:]) / 3.0
sma = np.mean(tp)
mad = np.mean(np.abs(tp - sma))
return (tp[-1] - sma) / (0.015 * mad + 1e-10)
@staticmethod
def _williams_r(highs, lows, closes, period=14):
if len(closes) < period:
return -50.0
hh = np.max(highs[-period:])
ll = np.min(lows[-period:])
return -100.0 * (hh - closes[-1]) / (hh - ll + 1e-10)
@staticmethod
def _adx(highs, lows, closes, period=14):
if len(closes) < period + 1:
return 25.0
up = highs[1:] - highs[:-1]
down = lows[:-1] - lows[1:]
plus_dm = np.where((up > down) & (up > 0), up, 0.0)
minus_dm = np.where((down > up) & (down > 0), down, 0.0)
atr = FeatureEngine._atr(highs, lows, closes, period)
plus_di = 100 * np.mean(plus_dm[-period:]) / (atr + 1e-10)
minus_di = 100 * np.mean(minus_dm[-period:]) / (atr + 1e-10)
dx = 100 * abs(plus_di - minus_di) / (plus_di + minus_di + 1e-10)
return dx
@staticmethod
def _doji(opens, highs, lows, closes):
body = abs(closes[-1] - opens[-1])
rng = highs[-1] - lows[-1]
return 1.0 if rng > 0 and body / rng < 0.1 else 0.0
@staticmethod
def _hammer(opens, highs, lows, closes):
body = abs(closes[-1] - opens[-1])
lower_wick = min(opens[-1], closes[-1]) - lows[-1]
upper_wick = highs[-1] - max(opens[-1], closes[-1])
rng = highs[-1] - lows[-1]
if rng < 1e-10:
return 0.0
if lower_wick > 2 * body and upper_wick < body:
return 1.0
if upper_wick > 2 * body and lower_wick < body:
return -1.0
return 0.0
@staticmethod
def _engulfing(opens, closes):
if len(opens) < 2:
return 0.0
prev_body = closes[-2] - opens[-2]
curr_body = closes[-1] - opens[-1]
if prev_body < 0 and curr_body > 0 and curr_body > abs(prev_body):
return 1.0 # bullish engulfing
if prev_body > 0 and curr_body < 0 and abs(curr_body) > prev_body:
return -1.0 # bearish engulfing
return 0.0
@staticmethod
def _skewness(arr):
m = np.mean(arr)
s = np.std(arr)
if s < 1e-10:
return 0.0
return float(np.mean(((arr - m) / s) ** 3))
@staticmethod
def _kurtosis(arr):
m = np.mean(arr)
s = np.std(arr)
if s < 1e-10:
return 0.0
return float(np.mean(((arr - m) / s) ** 4) - 3.0)
@staticmethod
def _higuchi_fd(series, kmax=5):
n = len(series)
if n < kmax * 2:
return 1.5
lk = []
for k in range(1, kmax + 1):
lengths = []
for m in range(1, k + 1):
idxs = np.arange(m - 1, n, k)
if len(idxs) < 2:
continue
vals = series[idxs]
length = np.sum(np.abs(np.diff(vals))) * (n - 1) / (k * len(idxs) * k)
lengths.append(length)
if lengths:
lk.append(np.mean(lengths))
if len(lk) < 2 or any(l <= 0 for l in lk):
return 1.5
log_k = np.log(np.arange(1, len(lk) + 1, dtype=np.float64))
log_l = np.log(np.array(lk))
slope = np.polyfit(log_k, log_l, 1)[0]
return float(-slope)
# ═══════════════════════════════════════════════════════════════════════════
# ONLINE LEARNING ENSEMBLE
# ═══════════════════════════════════════════════════════════════════════════
class EnsemblePredictor:
"""
5-model ensemble: 3 online learners + 2 batch powerhouses.
Online: SGD, Passive-Aggressive, Naive Bayes (adapt in real-time)
Batch: GradientBoosting, RandomForest (trained once, high accuracy)
Batch models get 2× vote weight since they're stronger.
"""
def __init__(self):
if not SKLEARN_OK:
self.models = []
self.scaler = None
return
self.scaler = StandardScaler()
# Online models — support partial_fit for live learning
self.models = [
{
"name": "SGD",
"clf": SGDClassifier(
loss="modified_huber", penalty="l2",
alpha=1e-4, warm_start=True, random_state=42,
),
"accuracy_ema": 0.5,
},
{
"name": "PA",
"clf": SGDClassifier(
loss="hinge", penalty=None,
learning_rate="pa1", eta0=1.0,
warm_start=True, random_state=42,
),
"accuracy_ema": 0.5,
},
{
"name": "NB",
"clf": GaussianNB(),
"accuracy_ema": 0.5,
},
]
# Batch models — much stronger, trained once on full dataset
self._batch_models = [
{
"name": "GBM",
"clf": GradientBoostingClassifier(
n_estimators=200, max_depth=4, learning_rate=0.1,
subsample=0.8, random_state=42,
),
"accuracy_ema": 0.5,
},
{
"name": "RF",
"clf": RandomForestClassifier(
n_estimators=200, max_depth=8,
random_state=42, n_jobs=-1,
),
"accuracy_ema": 0.5,
},
]
self._batch_fitted = False
self._batch_X: list[np.ndarray] = []
self._batch_y: list[int] = []
self._fitted = False
self._X_buffer: list[np.ndarray] = []
self._y_buffer: list[int] = [] # 1 = CALL-win, 0 = PUT-win
self._classes = np.array([0, 1])
# -- incremental training --
def add_sample(self, features: np.ndarray, label: int):
self._X_buffer.append(features)
self._y_buffer.append(label)
self._batch_X.append(features)
self._batch_y.append(label)
def partial_fit(self):
"""Train online models on buffered samples, then clear."""
if not SKLEARN_OK or len(self._X_buffer) == 0:
return
X = np.vstack(self._X_buffer)
y = np.array(self._y_buffer)
# Reset if feature dimension changed
if self._fitted and hasattr(self.scaler, 'n_features_in_'):
if self.scaler.n_features_in_ != X.shape[1]:
log.warning("Feature dimension changed (%d → %d) — resetting.",
self.scaler.n_features_in_, X.shape[1])
self.__init__()
return
if not self._fitted:
self.scaler.fit(X)
else:
self.scaler.partial_fit(X)
X_scaled = self.scaler.transform(X)
for m in self.models:
clf = m["clf"]
if hasattr(clf, "partial_fit"):
clf.partial_fit(X_scaled, y, classes=self._classes)
else:
clf.fit(X_scaled, y)
if self._fitted:
preds = clf.predict(X_scaled)
acc = float(np.mean(preds == y))
m["accuracy_ema"] = 0.9 * m["accuracy_ema"] + 0.1 * acc
self._fitted = True
self._X_buffer.clear()
self._y_buffer.clear()
log.info(
"Models updated | acc EMAs: %s",
{m["name"]: f'{m["accuracy_ema"]:.3f}' for m in self.models},
)
def train_batch_models(self):
"""Train GBM + RF on ALL accumulated data. Call after dataset load."""
if len(self._batch_X) < 100:
log.warning("Not enough data for batch models (%d)", len(self._batch_X))
return
X = np.vstack(self._batch_X)
y = np.array(self._batch_y)
X_scaled = self.scaler.transform(X)
log.info("🧠 Training batch models (GBM + RF) on %d samples …", len(X))
for m in self._batch_models:
try:
m["clf"].fit(X_scaled, y)
preds = m["clf"].predict(X_scaled)
acc = float(np.mean(preds == y))
m["accuracy_ema"] = acc
log.info(" %s trained — accuracy: %.1f%%", m["name"], acc * 100)
except Exception as e:
log.warning(" %s failed: %s", m["name"], e)
self._batch_fitted = True
# -- persistence --
def save_brain(self, path="athena_po_brain.pkl"):
if not self._fitted:
log.warning("No trained models to save.")
return
state = {
"scaler": self.scaler,
"models": [(m["name"], m["clf"], m["accuracy_ema"]) for m in self.models],
"batch_models": [(m["name"], m["clf"], m["accuracy_ema"]) for m in self._batch_models],
"batch_fitted": self._batch_fitted,
"fitted": self._fitted,
}
with open(path, "wb") as f:
pickle.dump(state, f)
log.info("🧠 Brain saved to %s", path)
def load_brain(self, path="athena_po_brain.pkl") -> bool:
if not os.path.exists(path):
return False
try:
with open(path, "rb") as f:
state = pickle.load(f)
self.scaler = state["scaler"]
for saved, m in zip(state.get("models", []), self.models):
m["name"], m["clf"], m["accuracy_ema"] = saved[0], saved[1], saved[2]
if "batch_models" in state:
for saved, m in zip(state["batch_models"], self._batch_models):
m["name"], m["clf"], m["accuracy_ema"] = saved[0], saved[1], saved[2]
self._batch_fitted = state.get("batch_fitted", False)
self._fitted = state["fitted"]
log.info("🧠 Brain loaded (fitted=%s, batch=%s, models: %s)",
self._fitted, self._batch_fitted,
{m["name"]: f'{m["accuracy_ema"]:.3f}' for m in self.models})
return True
except Exception as e:
log.warning("Failed to load brain: %s", e)
return False
# -- prediction --
def predict(self, features: np.ndarray) -> tuple[Direction, float]:
if not SKLEARN_OK or not self._fitted:
return self._fallback_predict(features)
try:
if not hasattr(self.scaler, 'n_features_in_'):
return self._fallback_predict(features)
if self.scaler.n_features_in_ != len(features):
return self._fallback_predict(features)
except Exception:
return self._fallback_predict(features)
try:
X = self.scaler.transform(features.reshape(1, -1))
except Exception:
return self._fallback_predict(features)
weighted_call = 0.0
total_weight = 0.0
# Online models vote
for m in self.models:
w = m["accuracy_ema"]
clf = m["clf"]
if hasattr(clf, "predict_proba"):
try:
proba = clf.predict_proba(X)[0]
p_call = proba[1] if len(proba) > 1 else 0.5
except Exception:
p_call = 0.5
else:
pred = clf.predict(X)[0]
p_call = 1.0 if pred == 1 else 0.0
weighted_call += w * p_call
total_weight += w
# Batch models vote (2× weight — they're stronger)
if self._batch_fitted:
for m in self._batch_models:
w = m["accuracy_ema"] * 2.0
try:
if hasattr(m["clf"], "predict_proba"):
proba = m["clf"].predict_proba(X)[0]
p_call = proba[1] if len(proba) > 1 else 0.5
else:
p_call = 1.0 if m["clf"].predict(X)[0] == 1 else 0.0
except Exception:
p_call = 0.5
weighted_call += w * p_call
total_weight += w
p = weighted_call / (total_weight + 1e-10)
if p >= 0.5:
return Direction.CALL, p
else:
return Direction.PUT, 1.0 - p
@staticmethod
def _fallback_predict(features: np.ndarray) -> tuple[Direction, float]:
"""Rule-based fallback when sklearn is missing or models untrained."""
rsi = features[14] if len(features) > 14 else 50.0
macd_hist = features[12] if len(features) > 12 else 0.0
sma_cross = features[10] if len(features) > 10 else 0.0
score = 0.0
if rsi < 30:
score += 0.3
elif rsi > 70:
score -= 0.3
if macd_hist > 0:
score += 0.2
elif macd_hist < 0:
score -= 0.2
if sma_cross > 0:
score += 0.15
elif sma_cross < 0:
score -= 0.15
conf = 0.5 + min(abs(score), 0.45)
if score > 0:
return Direction.CALL, conf
else:
return Direction.PUT, conf
# ═══════════════════════════════════════════════════════════════════════════
# REGIME DETECTOR
# ═══════════════════════════════════════════════════════════════════════════
class RegimeDetector:
@staticmethod
def detect(candles: list[Candle], window: int = 30) -> Regime:
if len(candles) < window:
return Regime.RANGING
closes = np.array([c.close for c in candles[-window:]])
rets = np.diff(closes) / (closes[:-1] + 1e-10)
trend = np.polyfit(np.arange(len(closes)), closes, 1)[0]
vol = np.std(rets)
mean_ret = np.mean(rets)
# Normalise trend by price level
rel_trend = trend / (closes[-1] + 1e-10) * window
if vol > 0.005:
return Regime.VOLATILE
if rel_trend > 0.002:
return Regime.TRENDING_UP
if rel_trend < -0.002:
return Regime.TRENDING_DOWN
return Regime.RANGING
# ═══════════════════════════════════════════════════════════════════════════
# EXPIRY SELECTOR — AI picks optimal trade duration per-trade
# ═══════════════════════════════════════════════════════════════════════════
class ExpirySelector:
"""
Chooses the best expiry for each trade based on:
• Regime → trending = longer, volatile/ranging = shorter
• ATR / volatility → high vol = shorter exposure
• ADX (trend strength) → strong trend = ride it longer
• Confidence → high confidence = can go longer
• RSI extremes → overbought/oversold = shorter (reversal)
• Past performance → learns which durations actually win
PocketOption expiry options: 60s, 120s, 180s, 300s (configurable)
"""
def __init__(self, expiry_options: tuple = (60, 120, 180, 300)):
self.options = sorted(expiry_options)
# Track win/loss per expiry duration — this learns over time
self.stats: dict[int, dict] = {e: {"wins": 0, "losses": 0} for e in self.options}
def select(self, regime: Regime, features: np.ndarray, confidence: float) -> int:
"""Pick the best expiry given current market conditions.
Returns expiry in seconds."""
# Extract key indicators from feature vector (see FeatureEngine.CORE_NAMES)
volatility = features[6] if len(features) > 6 else 0.01 # idx 6
rsi = features[13] if len(features) > 13 else 50.0 # idx 13
atr = features[17] if len(features) > 17 else 0.001 # idx 17
adx = features[24] if len(features) > 24 else 25.0 # idx 24
scores: dict[int, float] = {}
for exp in self.options:
score = 0.0
# ── 1. Regime ──
if regime in (Regime.TRENDING_UP, Regime.TRENDING_DOWN):
# Trending → prefer longer (ride the wave)
if exp >= 300: score += 3.0
elif exp >= 180: score += 2.0
elif exp >= 120: score += 1.0
else: score += 0.5
elif regime == Regime.VOLATILE:
# Volatile → prefer shorter (less exposure to reversals)
if exp <= 60: score += 3.0
elif exp <= 120: score += 2.0
elif exp <= 180: score += 1.0
else: score -= 1.0
else:
# Ranging → short to medium
if exp <= 120: score += 2.5
elif exp <= 180: score += 2.0
elif exp <= 300: score += 1.0
else: score += 0.5
# ── 2. Volatility (return std) ──
if volatility > 0.003:
# High vol → shorter is safer
if exp <= 120: score += 1.5
if exp >= 300: score -= 1.0
elif volatility < 0.001:
# Low vol → need longer to see movement
if exp >= 180: score += 1.0
if exp <= 60: score -= 0.5
# ── 3. ADX (trend strength) ──
if adx > 30:
# Strong trend → go longer
if exp >= 180: score += 1.5
if exp >= 300: score += 0.5
elif adx < 15:
# No trend → stay short
if exp <= 120: score += 1.0
# ── 4. Confidence ──
if confidence >= 0.75:
# Very confident → can afford longer expiry
if exp >= 180: score += 1.5
elif confidence >= 0.65:
if exp >= 120: score += 0.5
else:
# Lower confidence → shorter = less risk
if exp <= 120: score += 1.0
if exp >= 300: score -= 1.0
# ── 5. RSI extremes → reversal likely → shorter ──
if rsi > 75 or rsi < 25:
if exp <= 120: score += 1.0
if exp >= 300: score -= 0.5
# ── 6. Past performance (adaptive learning) ──
st = self.stats.get(exp, {"wins": 0, "losses": 0})
total = st["wins"] + st["losses"]
if total >= 5:
wr = st["wins"] / total
# Boost winners, penalise losers: 60% WR → +0.5, 40% → -0.5
score += (wr - 0.50) * 5.0
scores[exp] = score
best = max(scores, key=scores.get)
return best
def record_result(self, expiry: int, result: str):
"""Feed trade result back — learn which expiries work."""
if expiry not in self.stats: