gionuibk commited on
Commit
782d2ac
·
verified ·
1 Parent(s): e58e69b

Upload apex_trail_optuna.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. apex_trail_optuna.py +306 -0
apex_trail_optuna.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Apex Trail v7 - Numba JIT Optuna Optimization
3
+ ~50-100x faster than pure Python
4
+ """
5
+ import pyarrow.parquet as pq
6
+ import numpy as np
7
+ import optuna
8
+ import time as time_mod
9
+ from numba import njit
10
+ optuna.logging.set_verbosity(optuna.logging.WARNING)
11
+
12
+ PT = 0.01; PV = 1.0 # 0.01lot * 100
13
+
14
+ # Load data
15
+ print("Loading tickflow_M1...")
16
+ df = pq.read_table("C:/Users/Black/Downloads/MT5EA/tick_data/tickflow_M1.parquet").to_pandas()
17
+ tr = np.maximum(df['high']-df['low'],
18
+ np.maximum(np.abs(df['high']-df['close'].shift(1).fillna(df['close'])),
19
+ np.abs(df['low']-df['close'].shift(1).fillna(df['close']))))
20
+ df['atr'] = (tr.rolling(210, min_periods=14).mean() / PT).fillna(300)
21
+ dm_s = df['close'].diff().abs() / PT
22
+ df['adx'] = (dm_s.rolling(210, min_periods=14).mean() / df['atr'].clip(lower=1) * 50).clip(upper=60).fillna(25)
23
+ df['tv'] = df['tick_count'].rolling(5, min_periods=1).mean() / 60.0
24
+ df['sp'] = df['spread_avg']
25
+
26
+ G_o=df['open'].values.astype(np.float64)
27
+ G_h=df['high'].values.astype(np.float64)
28
+ G_l=df['low'].values.astype(np.float64)
29
+ G_c=df['close'].values.astype(np.float64)
30
+ G_sp=df['sp'].values.astype(np.float64)
31
+ G_tv=df['tv'].values.astype(np.float64)
32
+ G_atr=df['atr'].values.astype(np.float64)
33
+ G_adx=df['adx'].values.astype(np.float64)
34
+ G_ao=df['ask_open'].values.astype(np.float64)
35
+ G_ac=df['ask_close'].values.astype(np.float64)
36
+ G_tc=df['tick_count'].values.astype(np.float64)
37
+ G_N=len(df)
38
+ del df
39
+ print(f" {G_N} bars ready")
40
+
41
+ @njit(cache=True)
42
+ def sim_core(c, h, l, ac, ao, o, sp, tv, atr, adx, tc, N,
43
+ sl_atr, trail_start, p2_trend, p2_norm, p2_side, p3_sq,
44
+ entry_interval, tick_thresh, use_be_floor, tv_exhaust, tv_recover):
45
+ MX = 50000
46
+ p_s = np.zeros(MX, np.int8)
47
+ p_e = np.zeros(MX, np.float64)
48
+ p_sl = np.zeros(MX, np.float64)
49
+ p_ph = np.zeros(MX, np.int8)
50
+ p_pk = np.zeros(MX, np.float64)
51
+ p_pkp = np.zeros(MX, np.float64)
52
+ p_op = np.zeros(MX, np.bool_)
53
+ p_pnl = np.zeros(MX, np.float64)
54
+ p_atr_e = np.zeros(MX, np.float64)
55
+ pc = 0
56
+ last_e = -999
57
+
58
+ for i in range(N):
59
+ B = c[i]; A = ac[i]; BH = h[i]; BL = l[i]
60
+ SP = sp[i]; TV = tv[i]; ATR = atr[i]; ADX = adx[i]
61
+ AH = BH + SP * PT; AL = BL + SP * PT
62
+
63
+ for j in range(pc):
64
+ if not p_op[j]:
65
+ continue
66
+ si = p_s[j]; en = p_e[j]; ea = p_atr_e[j]
67
+ sl_pts = ea * sl_atr
68
+
69
+ if si == 1:
70
+ pp_w = (BL - en) / PT
71
+ pp_b = (BH - en) / PT
72
+ else:
73
+ pp_w = (en - AH) / PT
74
+ pp_b = (en - AL) / PT
75
+
76
+ if pp_b > p_pkp[j]:
77
+ p_pkp[j] = pp_b
78
+ if si == 1:
79
+ p_pk[j] = BH
80
+ else:
81
+ p_pk[j] = AL
82
+
83
+ # SL
84
+ if pp_w <= -sl_pts:
85
+ p_op[j] = False
86
+ p_pnl[j] = -(sl_pts * PV / 100.0)
87
+ continue
88
+
89
+ # Phase 0 → 2
90
+ if p_ph[j] == 0 and pp_b >= ATR * trail_start:
91
+ p_ph[j] = 2
92
+ if ADX > 30:
93
+ m = p2_trend
94
+ elif ADX > 20:
95
+ m = p2_norm
96
+ else:
97
+ m = p2_side
98
+ pk = p_pk[j]
99
+ if si == 1:
100
+ ns = pk - ATR * m * PT
101
+ if use_be_floor and ns < en:
102
+ ns = en
103
+ p_sl[j] = ns
104
+ else:
105
+ ns = pk + ATR * m * PT
106
+ if use_be_floor and ns > en:
107
+ ns = en
108
+ p_sl[j] = ns
109
+
110
+ # Phase 2
111
+ if p_ph[j] == 2:
112
+ if ADX > 30:
113
+ m = p2_trend
114
+ elif ADX > 20:
115
+ m = p2_norm
116
+ else:
117
+ m = p2_side
118
+ td = ATR * m * PT
119
+ pk = p_pk[j]
120
+ if si == 1:
121
+ ns = pk - td
122
+ if use_be_floor and ns < en:
123
+ ns = en
124
+ if ns > p_sl[j]:
125
+ p_sl[j] = ns
126
+ else:
127
+ ns = pk + td
128
+ if use_be_floor and ns > en:
129
+ ns = en
130
+ if p_sl[j] <= 0 or ns < p_sl[j]:
131
+ p_sl[j] = ns
132
+ if TV < tv_exhaust and p_pkp[j] > ATR * 1.5:
133
+ p_ph[j] = 3
134
+
135
+ # Phase 3
136
+ if p_ph[j] == 3:
137
+ sq = ATR * p3_sq * PT
138
+ pk = p_pk[j]
139
+ if si == 1:
140
+ ns = pk - sq
141
+ if use_be_floor and ns < en:
142
+ ns = en
143
+ if ns > p_sl[j]:
144
+ p_sl[j] = ns
145
+ else:
146
+ ns = pk + sq
147
+ if use_be_floor and ns > en:
148
+ ns = en
149
+ if p_sl[j] <= 0 or ns < p_sl[j]:
150
+ p_sl[j] = ns
151
+ if TV > tv_recover:
152
+ p_ph[j] = 2
153
+
154
+ # Trail hit
155
+ if p_ph[j] >= 2 and p_sl[j] > 0:
156
+ hit = False
157
+ if si == 1 and BL <= p_sl[j]:
158
+ hit = True
159
+ elif si == -1 and AH >= p_sl[j]:
160
+ hit = True
161
+ if hit:
162
+ if si == 1:
163
+ ppts = (p_sl[j] - en) / PT
164
+ else:
165
+ ppts = (en - p_sl[j]) / PT
166
+ p_op[j] = False
167
+ p_pnl[j] = ppts * PV / 100.0
168
+
169
+ # Entry
170
+ if i - last_e >= entry_interval and SP < 40 and pc + 2 <= MX:
171
+ if tc[i] >= tick_thresh:
172
+ last_e = i
173
+ for si2_idx in range(2):
174
+ si2 = 1 if si2_idx == 0 else -1
175
+ ep = ao[i] if si2 == 1 else o[i]
176
+ p_s[pc] = si2
177
+ p_e[pc] = ep
178
+ sl_d = ATR * sl_atr * PT
179
+ if si2 == 1:
180
+ p_sl[pc] = ep - sl_d
181
+ else:
182
+ p_sl[pc] = ep + sl_d
183
+ p_ph[pc] = 0
184
+ p_pk[pc] = ep
185
+ p_pkp[pc] = 0.0
186
+ p_op[pc] = True
187
+ p_pnl[pc] = 0.0
188
+ p_atr_e[pc] = ATR
189
+ pc += 1
190
+ else:
191
+ last_e = i
192
+
193
+ # Close remaining
194
+ for j in range(pc):
195
+ if p_op[j]:
196
+ si = p_s[j]
197
+ if si == 1:
198
+ ppts = (c[N-1] - p_e[j]) / PT
199
+ else:
200
+ ppts = (p_e[j] - ac[N-1]) / PT
201
+ p_pnl[j] = ppts * PV / 100.0
202
+ p_op[j] = False
203
+
204
+ return p_pnl[:pc]
205
+
206
+ # Warmup JIT
207
+ print("Warming up Numba JIT...")
208
+ t0 = time_mod.time()
209
+ _ = sim_core(G_c, G_h, G_l, G_ac, G_ao, G_o, G_sp, G_tv, G_atr, G_adx, G_tc, G_N,
210
+ 2.0, 1.0, 2.0, 1.5, 0.8, 0.5, 5, 259.0, True, 1.5, 5.0)
211
+ print(f" JIT warmup: {time_mod.time()-t0:.1f}s")
212
+
213
+ # Speed test
214
+ t0 = time_mod.time()
215
+ pnls = sim_core(G_c, G_h, G_l, G_ac, G_ao, G_o, G_sp, G_tv, G_atr, G_adx, G_tc, G_N,
216
+ 2.0, 1.0, 2.0, 1.5, 0.8, 0.5, 5, 259.0, True, 1.5, 5.0)
217
+ speed = time_mod.time()-t0
218
+ print(f" Speed test: {speed:.2f}s per trial ({len(pnls)} trades)")
219
+
220
+ def objective(trial):
221
+ sl_atr = trial.suggest_float("sl_atr", 1.0, 4.0, step=0.5)
222
+ trail_start = trial.suggest_float("trail_start", 0.5, 3.0, step=0.25)
223
+ p2_trend = trial.suggest_float("p2_trend", 1.0, 3.0, step=0.25)
224
+ p2_norm = trial.suggest_float("p2_norm", 0.75, 2.25, step=0.25)
225
+ p2_side = trial.suggest_float("p2_side", 0.3, 1.5, step=0.1)
226
+ p3_sq = trial.suggest_float("p3_sq", 0.2, 1.0, step=0.1)
227
+ entry_interval = trial.suggest_int("entry_interval", 3, 20)
228
+ tick_pct = trial.suggest_float("tick_pct", 20, 80, step=5)
229
+ use_be_floor = trial.suggest_categorical("use_be_floor", [True, False])
230
+ tv_exhaust = trial.suggest_float("tv_exhaust", 0.5, 3.0, step=0.25)
231
+ tv_recover = trial.suggest_float("tv_recover", 3.0, 10.0, step=0.5)
232
+
233
+ tick_thresh = np.percentile(G_tc, tick_pct)
234
+ be = 1.0 if use_be_floor else 0.0
235
+
236
+ pnls = sim_core(G_c, G_h, G_l, G_ac, G_ao, G_o, G_sp, G_tv, G_atr, G_adx, G_tc, G_N,
237
+ sl_atr, trail_start, p2_trend, p2_norm, p2_side, p3_sq,
238
+ entry_interval, tick_thresh, use_be_floor, tv_exhaust, tv_recover)
239
+
240
+ n = len(pnls)
241
+ if n < 50:
242
+ return 0.0
243
+
244
+ ws = float(np.sum(pnls[pnls > 0]))
245
+ ls = float(np.sum(pnls[pnls <= 0]))
246
+ wins = int(np.sum(pnls > 0))
247
+ pf = abs(ws) / max(0.01, abs(ls))
248
+ exp = float(np.mean(pnls))
249
+ wr = wins / n * 100.0
250
+ total = float(np.sum(pnls))
251
+
252
+ trial.set_user_attr("wr", round(wr, 1))
253
+ trial.set_user_attr("exp", round(exp, 2))
254
+ trial.set_user_attr("pnl", round(total, 0))
255
+ trial.set_user_attr("trades", n)
256
+ trial.set_user_attr("pf", round(pf, 3))
257
+
258
+ if pf < 0.5:
259
+ return 0.0
260
+ return pf * np.sqrt(n) / 100.0
261
+
262
+ if __name__ == "__main__":
263
+ N_TRIALS = 200
264
+ print(f"\n{'='*60}")
265
+ print(f"OPTUNA | {N_TRIALS} trials | ~{speed*N_TRIALS/60:.0f} min estimated")
266
+ print(f"{'='*60}")
267
+
268
+ study = optuna.create_study(direction="maximize",
269
+ sampler=optuna.samplers.TPESampler(seed=42))
270
+ t0 = time_mod.time()
271
+
272
+ def cb(study, trial):
273
+ if trial.number % 10 == 0:
274
+ b = study.best_trial
275
+ el = time_mod.time() - t0
276
+ eta = el / max(1, trial.number+1) * (N_TRIALS - trial.number - 1)
277
+ print(f" T{trial.number:3d}/{N_TRIALS} | "
278
+ f"Best: PF={b.user_attrs.get('pf',0):.2f} WR={b.user_attrs.get('wr',0):.1f}% "
279
+ f"Exp=${b.user_attrs.get('exp',0):.2f} ${b.user_attrs.get('pnl',0):.0f} "
280
+ f"({b.user_attrs.get('trades',0)} tr) | {eta/60:.0f}min left")
281
+
282
+ study.optimize(objective, n_trials=N_TRIALS, callbacks=[cb])
283
+ elapsed = time_mod.time() - t0
284
+ print(f"\nDone! {elapsed/60:.1f} minutes")
285
+
286
+ print(f"\n{'='*60}")
287
+ print(f"TOP 10 RESULTS")
288
+ print(f"{'='*60}")
289
+ trials = sorted(study.trials, key=lambda t: t.value if t.value else 0, reverse=True)
290
+ for i, t in enumerate(trials[:10]):
291
+ a = t.user_attrs
292
+ print(f"#{i+1:2d} PF={a.get('pf',0):.2f} WR={a.get('wr',0):.1f}% "
293
+ f"Exp=${a.get('exp',0):.2f} PnL=${a.get('pnl',0):.0f} ({a.get('trades',0)} tr) | "
294
+ f"SL={t.params.get('sl_atr',0)} TS={t.params.get('trail_start',0)} "
295
+ f"BE={t.params.get('use_be_floor','')} TV_ex={t.params.get('tv_exhaust',0)} "
296
+ f"P2t={t.params.get('p2_trend',0)} P2n={t.params.get('p2_norm',0)} "
297
+ f"P2s={t.params.get('p2_side',0)}")
298
+
299
+ print(f"\n{'='*60}")
300
+ print(f"BEST PARAMETERS")
301
+ print(f"{'='*60}")
302
+ bp = study.best_trial.params
303
+ ba = study.best_trial.user_attrs
304
+ print(f"PF={ba['pf']:.3f} | WR={ba['wr']:.1f}% | Exp=${ba['exp']:.2f} | PnL=${ba['pnl']:.0f} | {ba['trades']} trades")
305
+ for k, v in sorted(bp.items()):
306
+ print(f" {k:20s} = {v}")