nextrade-engine 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nextrade/nextrade/__init__.py +277 -0
- nextrade/nextrade/backtest/__init__.py +0 -0
- nextrade/nextrade/backtest/engine.py +249 -0
- nextrade/nextrade/core/__init__.py +0 -0
- nextrade/nextrade/core/brain.py +278 -0
- nextrade/nextrade/core/regime.py +63 -0
- nextrade/nextrade/data/__init__.py +0 -0
- nextrade/nextrade/data/fetcher.py +173 -0
- nextrade/nextrade/indicators/__init__.py +0 -0
- nextrade/nextrade/indicators/adaptive.py +73 -0
- nextrade/nextrade/indicators/confluence.py +61 -0
- nextrade/nextrade/indicators/pattern.py +76 -0
- nextrade/nextrade/utils/__init__.py +0 -0
- nextrade/nextrade/utils/terminal_ui.py +87 -0
- nextrade/setup.py +10 -0
- nextrade_engine-0.5.0.dist-info/METADATA +97 -0
- nextrade_engine-0.5.0.dist-info/RECORD +20 -0
- nextrade_engine-0.5.0.dist-info/WHEEL +5 -0
- nextrade_engine-0.5.0.dist-info/licenses/LICENSE +21 -0
- nextrade_engine-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NexTrade — AI Trading Engine
|
|
3
|
+
import nextrade → wizard muncul otomatis di terminal
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from nextrade.utils.terminal_ui import (
|
|
7
|
+
print_welcome, print_signal, print_error,
|
|
8
|
+
print_loading, print_success, list_strategies, STRATEGIES
|
|
9
|
+
)
|
|
10
|
+
from nextrade.indicators.confluence import confluence_score
|
|
11
|
+
from nextrade.core.regime import detect_regime
|
|
12
|
+
from nextrade.core.brain import Brain
|
|
13
|
+
from nextrade.data.fetcher import fetch, fetch_multi, list_markets
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
__version__ = "0.3.0"
|
|
17
|
+
__author__ = "NexTrade"
|
|
18
|
+
|
|
19
|
+
# Tampilkan wizard saat pertama kali import
|
|
20
|
+
print_welcome()
|
|
21
|
+
|
|
22
|
+
# Instance brain global
|
|
23
|
+
_brain = Brain.__new__(Brain)
|
|
24
|
+
_brain.state = None
|
|
25
|
+
|
|
26
|
+
def _get_brain():
|
|
27
|
+
global _brain
|
|
28
|
+
if _brain.state is None:
|
|
29
|
+
_brain = Brain()
|
|
30
|
+
return _brain
|
|
31
|
+
|
|
32
|
+
# ─────────────────────────────────────────
|
|
33
|
+
# PUBLIC API
|
|
34
|
+
# ─────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
def start(strategy: str = "adaptive",
|
|
37
|
+
market: str = "BTCUSD",
|
|
38
|
+
timeframe: str = "H1",
|
|
39
|
+
data: dict = None):
|
|
40
|
+
"""
|
|
41
|
+
Jalankan NexTrade — ambil data real lalu keluarkan sinyal.
|
|
42
|
+
|
|
43
|
+
Contoh:
|
|
44
|
+
nextrade.start("momentum", market="BTCUSD")
|
|
45
|
+
nextrade.start("reversal", market="EURUSD", timeframe="M15")
|
|
46
|
+
nextrade.start("adaptive", market="AAPL")
|
|
47
|
+
"""
|
|
48
|
+
strategy = strategy.lower().strip()
|
|
49
|
+
|
|
50
|
+
if strategy not in STRATEGIES:
|
|
51
|
+
print_error(f"Strategi '{strategy}' tidak ditemukan.")
|
|
52
|
+
list_strategies()
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
print_loading(f"Memuat strategi {strategy.upper()}...")
|
|
56
|
+
|
|
57
|
+
# Ambil data real kalau tidak ada data manual
|
|
58
|
+
if data is None:
|
|
59
|
+
data = fetch(market, timeframe, bars=500)
|
|
60
|
+
if data is None:
|
|
61
|
+
print_error("Gagal ambil data market. Cek koneksi internet.")
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
print_loading("Menghitung indikator AI...")
|
|
65
|
+
|
|
66
|
+
# Hitung sinyal pakai confluence score
|
|
67
|
+
result = confluence_score(
|
|
68
|
+
opens = data["open"],
|
|
69
|
+
highs = data["high"],
|
|
70
|
+
lows = data["low"],
|
|
71
|
+
closes = data["close"],
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# Sesuaikan confidence threshold dengan agresivitas brain
|
|
75
|
+
brain = _get_brain()
|
|
76
|
+
threshold = brain.get_confidence_threshold()
|
|
77
|
+
confidence = result["confidence"]
|
|
78
|
+
|
|
79
|
+
# Adjust sinyal berdasarkan threshold agresivitas
|
|
80
|
+
if confidence >= threshold and result["details"]["pattern"]["direction"] != "bear":
|
|
81
|
+
signal = "BUY"
|
|
82
|
+
elif confidence <= (100 - threshold) or result["details"]["pattern"]["direction"] == "bear":
|
|
83
|
+
signal = "SELL"
|
|
84
|
+
else:
|
|
85
|
+
signal = "HOLD"
|
|
86
|
+
|
|
87
|
+
# Tampilkan sinyal
|
|
88
|
+
print_signal(
|
|
89
|
+
signal = signal,
|
|
90
|
+
confidence = confidence,
|
|
91
|
+
strategy = strategy,
|
|
92
|
+
market = market,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Tampilkan detail tambahan
|
|
96
|
+
regime = result["details"]["regime"]["regime"]
|
|
97
|
+
rsi = result["details"]["rsi"]
|
|
98
|
+
mom = result["details"]["momentum"]
|
|
99
|
+
price = data["price_now"]
|
|
100
|
+
|
|
101
|
+
print(f" \033[2mDetail Analisis:\033[0m")
|
|
102
|
+
print(f" \033[36mHarga Sekarang :\033[0m {price:,.5f}")
|
|
103
|
+
print(f" \033[36mKondisi Pasar :\033[0m {regime}")
|
|
104
|
+
print(f" \033[36mRSI Adaptif :\033[0m {rsi:.1f}")
|
|
105
|
+
print(f" \033[36mMomentum Score :\033[0m {mom:.1f}")
|
|
106
|
+
print(f" \033[36mIQ Model :\033[0m {brain.state['iq']} / 100")
|
|
107
|
+
print(f" \033[36mAgresivitas :\033[0m {brain.state['agresivitas']}%")
|
|
108
|
+
print()
|
|
109
|
+
|
|
110
|
+
return {**result, "signal": signal, "market": market,
|
|
111
|
+
"price": price, "strategy": strategy}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def train(mode: str = "hybrid", market: str = "BTCUSD",
|
|
115
|
+
timeframe: str = "D1", bars: int = 1000):
|
|
116
|
+
"""
|
|
117
|
+
Latih brain NexTrade dengan data real market.
|
|
118
|
+
|
|
119
|
+
Contoh:
|
|
120
|
+
nextrade.train("offline", market="BTCUSD", timeframe="D1")
|
|
121
|
+
nextrade.train("hybrid", market="EURUSD", timeframe="H4")
|
|
122
|
+
nextrade.train("online", market="AAPL", timeframe="D1")
|
|
123
|
+
"""
|
|
124
|
+
print(f"\n \033[1m\033[37m Training NexTrade Brain\033[0m")
|
|
125
|
+
print(f" \033[36m{'─' * 40}\033[0m")
|
|
126
|
+
|
|
127
|
+
# Ambil data real untuk training
|
|
128
|
+
data = fetch(market, timeframe, bars=bars)
|
|
129
|
+
if data is None:
|
|
130
|
+
print_error("Gagal ambil data untuk training.")
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
brain = _get_brain()
|
|
134
|
+
brain.train(mode=mode, data=data)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def brain_status():
|
|
138
|
+
"""Tampilkan status otak NexTrade."""
|
|
139
|
+
_get_brain().status()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def set_agresivitas(pct: int):
|
|
143
|
+
"""
|
|
144
|
+
Set seberapa agresif NexTrade dalam mengambil sinyal.
|
|
145
|
+
0 = sangat selektif (sedikit sinyal tapi akurat)
|
|
146
|
+
100 = sangat agresif (banyak sinyal)
|
|
147
|
+
|
|
148
|
+
Contoh:
|
|
149
|
+
nextrade.set_agresivitas(20) # konservatif
|
|
150
|
+
nextrade.set_agresivitas(50) # moderat
|
|
151
|
+
nextrade.set_agresivitas(80) # agresif
|
|
152
|
+
"""
|
|
153
|
+
_get_brain().set_agresivitas(pct)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def scan(markets: list = None, strategy: str = "adaptive",
|
|
157
|
+
timeframe: str = "H1"):
|
|
158
|
+
"""
|
|
159
|
+
Scan banyak market sekaligus — cari peluang trading terbaik.
|
|
160
|
+
|
|
161
|
+
Contoh:
|
|
162
|
+
nextrade.scan(["BTCUSD", "EURUSD", "AAPL"])
|
|
163
|
+
nextrade.scan(["BTCUSD", "ETHUSD", "SOLUSD"], timeframe="H4")
|
|
164
|
+
"""
|
|
165
|
+
if markets is None:
|
|
166
|
+
markets = ["BTCUSD", "EURUSD", "XAUUSD", "AAPL", "TSLA"]
|
|
167
|
+
|
|
168
|
+
print(f"\n \033[1m\033[37m NexTrade Market Scanner\033[0m")
|
|
169
|
+
print(f" \033[36m{'─' * 55}\033[0m")
|
|
170
|
+
print(f" \033[2m{'MARKET':<12} {'HARGA':>14} {'SINYAL':>8} {'CONFIDENCE':>12} {'REGIME'}\033[0m")
|
|
171
|
+
print(f" \033[36m{'─' * 55}\033[0m")
|
|
172
|
+
|
|
173
|
+
results = []
|
|
174
|
+
for market in markets:
|
|
175
|
+
data = fetch(market, timeframe, bars=300, silent=True)
|
|
176
|
+
if data is None:
|
|
177
|
+
continue
|
|
178
|
+
|
|
179
|
+
result = confluence_score(
|
|
180
|
+
opens = data["open"],
|
|
181
|
+
highs = data["high"],
|
|
182
|
+
lows = data["low"],
|
|
183
|
+
closes = data["close"],
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
signal = result["signal"]
|
|
187
|
+
confidence = result["confidence"]
|
|
188
|
+
regime = result["details"]["regime"]["regime"]
|
|
189
|
+
price = data["price_now"]
|
|
190
|
+
|
|
191
|
+
# Warna sinyal
|
|
192
|
+
if signal == "BUY":
|
|
193
|
+
sc = "\033[32m"
|
|
194
|
+
elif signal == "SELL":
|
|
195
|
+
sc = "\033[31m"
|
|
196
|
+
else:
|
|
197
|
+
sc = "\033[33m"
|
|
198
|
+
|
|
199
|
+
print(f" {market:<12} {price:>14,.5f} {sc}{signal:>8}\033[0m "
|
|
200
|
+
f"{confidence:>10.1f}% \033[2m{regime}\033[0m")
|
|
201
|
+
|
|
202
|
+
results.append({**result, "market": market, "price": price})
|
|
203
|
+
|
|
204
|
+
print(f" \033[36m{'─' * 55}\033[0m\n")
|
|
205
|
+
|
|
206
|
+
# Highlight sinyal terkuat
|
|
207
|
+
buys = [r for r in results if r["signal"] == "BUY"]
|
|
208
|
+
sells = [r for r in results if r["signal"] == "SELL"]
|
|
209
|
+
|
|
210
|
+
if buys:
|
|
211
|
+
best = max(buys, key=lambda x: x["confidence"])
|
|
212
|
+
print(f" \033[32m★ Peluang BUY terkuat : {best['market']} "
|
|
213
|
+
f"({best['confidence']:.1f}%)\033[0m")
|
|
214
|
+
if sells:
|
|
215
|
+
best = max(sells, key=lambda x: x["confidence"])
|
|
216
|
+
print(f" \033[31m★ Peluang SELL terkuat : {best['market']} "
|
|
217
|
+
f"({best['confidence']:.1f}%)\033[0m")
|
|
218
|
+
print()
|
|
219
|
+
return results
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def backtest(strategy: str = "adaptive", market: str = "BTCUSD",
|
|
223
|
+
timeframe: str = "D1"):
|
|
224
|
+
"""Jalankan backtest strategi (coming soon v0.4.0)."""
|
|
225
|
+
print_loading("Menyiapkan backtest engine...")
|
|
226
|
+
print_success("Backtest engine hadir di v0.4.0!")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def info():
|
|
230
|
+
"""Tampilkan semua strategi dan market yang tersedia."""
|
|
231
|
+
list_strategies()
|
|
232
|
+
list_markets()
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def regime(market: str = "BTCUSD", timeframe: str = "H1") -> dict:
|
|
236
|
+
"""
|
|
237
|
+
Deteksi kondisi pasar saat ini.
|
|
238
|
+
|
|
239
|
+
Contoh:
|
|
240
|
+
r = nextrade.regime("EURUSD")
|
|
241
|
+
print(r["regime"]) # TRENDING / RANGING / VOLATILE
|
|
242
|
+
"""
|
|
243
|
+
data = fetch(market, timeframe, bars=100, silent=True)
|
|
244
|
+
if data is None:
|
|
245
|
+
return {}
|
|
246
|
+
return detect_regime(data["close"])
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def backtest(strategy: str = "adaptive",
|
|
250
|
+
market: str = "BTCUSD",
|
|
251
|
+
timeframe: str = "D1",
|
|
252
|
+
bars: int = 500,
|
|
253
|
+
agresivitas: int = 30,
|
|
254
|
+
sl_pct: float = 2.0,
|
|
255
|
+
tp_pct: float = 4.0):
|
|
256
|
+
"""
|
|
257
|
+
Backtest strategi NexTrade dengan data real historis.
|
|
258
|
+
|
|
259
|
+
Contoh:
|
|
260
|
+
nextrade.backtest("momentum", market="BTCUSD", timeframe="D1")
|
|
261
|
+
nextrade.backtest("adaptive", market="EURUSD", agresivitas=50)
|
|
262
|
+
nextrade.backtest("reversal", market="AAPL", sl_pct=1.5, tp_pct=3.0)
|
|
263
|
+
"""
|
|
264
|
+
from nextrade.backtest.engine import run as _run
|
|
265
|
+
|
|
266
|
+
data = fetch(market, timeframe, bars=bars)
|
|
267
|
+
if data is None:
|
|
268
|
+
print_error("Gagal ambil data untuk backtest.")
|
|
269
|
+
return
|
|
270
|
+
|
|
271
|
+
return _run(
|
|
272
|
+
data = data,
|
|
273
|
+
strategy = strategy,
|
|
274
|
+
agresivitas = agresivitas,
|
|
275
|
+
sl_pct = sl_pct,
|
|
276
|
+
tp_pct = tp_pct,
|
|
277
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NexTrade — Backtest Engine
|
|
3
|
+
Vectorized backtest engine — cepat, ringan, bisa jutaan bar di HP.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from nextrade.indicators.confluence import confluence_score
|
|
8
|
+
from nextrade.core.regime import detect_regime_series
|
|
9
|
+
|
|
10
|
+
def run(data: dict,
|
|
11
|
+
strategy: str = "adaptive",
|
|
12
|
+
agresivitas: int = 30,
|
|
13
|
+
sl_pct: float = 2.0,
|
|
14
|
+
tp_pct: float = 4.0,
|
|
15
|
+
silent: bool = False) -> dict:
|
|
16
|
+
"""
|
|
17
|
+
Jalankan backtest pada data historis.
|
|
18
|
+
|
|
19
|
+
data : dict { open, high, low, close, volume }
|
|
20
|
+
strategy : nama strategi
|
|
21
|
+
agresivitas : 0-100, makin tinggi makin banyak sinyal
|
|
22
|
+
sl_pct : stop loss dalam % (default 2%)
|
|
23
|
+
tp_pct : take profit dalam % (default 4%)
|
|
24
|
+
|
|
25
|
+
Returns dict lengkap hasil backtest.
|
|
26
|
+
"""
|
|
27
|
+
opens = np.array(data["open"], dtype=float)
|
|
28
|
+
highs = np.array(data["high"], dtype=float)
|
|
29
|
+
lows = np.array(data["low"], dtype=float)
|
|
30
|
+
closes = np.array(data["close"], dtype=float)
|
|
31
|
+
n = len(closes)
|
|
32
|
+
|
|
33
|
+
if not silent:
|
|
34
|
+
_print_start(n, strategy, agresivitas, sl_pct, tp_pct)
|
|
35
|
+
|
|
36
|
+
# Threshold berdasarkan agresivitas
|
|
37
|
+
threshold = 75 - (agresivitas * 0.30)
|
|
38
|
+
|
|
39
|
+
# ── GENERATE SINYAL UNTUK SETIAP BAR ──────────────────
|
|
40
|
+
signals = np.full(n, "HOLD", dtype=object)
|
|
41
|
+
confidences = np.zeros(n, dtype=float)
|
|
42
|
+
window = 50 # minimum window untuk kalkulasi
|
|
43
|
+
|
|
44
|
+
for i in range(window, n):
|
|
45
|
+
result = confluence_score(
|
|
46
|
+
opens = opens[max(0, i-window):i+1],
|
|
47
|
+
highs = highs[max(0, i-window):i+1],
|
|
48
|
+
lows = lows[max(0, i-window):i+1],
|
|
49
|
+
closes = closes[max(0, i-window):i+1],
|
|
50
|
+
)
|
|
51
|
+
conf = result["confidence"]
|
|
52
|
+
confidences[i] = conf
|
|
53
|
+
pat_dir = result["details"]["pattern"]["direction"]
|
|
54
|
+
|
|
55
|
+
if conf >= threshold and pat_dir != "bear":
|
|
56
|
+
signals[i] = "BUY"
|
|
57
|
+
elif conf <= (100 - threshold) or pat_dir == "bear":
|
|
58
|
+
signals[i] = "SELL"
|
|
59
|
+
else:
|
|
60
|
+
signals[i] = "HOLD"
|
|
61
|
+
|
|
62
|
+
if not silent and i % 100 == 0:
|
|
63
|
+
pct = (i / n) * 100
|
|
64
|
+
bar = "█" * int(pct / 5) + "░" * (20 - int(pct / 5))
|
|
65
|
+
print(f"\r \033[36m⠿\033[0m Menghitung sinyal... "
|
|
66
|
+
f"\033[33m{bar}\033[0m {pct:.0f}%", end="", flush=True)
|
|
67
|
+
|
|
68
|
+
if not silent:
|
|
69
|
+
print(f"\r \033[32m✓\033[0m Sinyal selesai dihitung! ")
|
|
70
|
+
|
|
71
|
+
# ── SIMULASI TRADE ─────────────────────────────────────
|
|
72
|
+
trades = []
|
|
73
|
+
in_trade = False
|
|
74
|
+
entry_price = 0.0
|
|
75
|
+
entry_idx = 0
|
|
76
|
+
trade_dir = ""
|
|
77
|
+
balance = 10000.0 # modal awal $10,000
|
|
78
|
+
peak_balance = balance
|
|
79
|
+
max_drawdown = 0.0
|
|
80
|
+
|
|
81
|
+
for i in range(window, n):
|
|
82
|
+
price = closes[i]
|
|
83
|
+
|
|
84
|
+
if not in_trade:
|
|
85
|
+
if signals[i] == "BUY":
|
|
86
|
+
in_trade = True
|
|
87
|
+
entry_price = price
|
|
88
|
+
entry_idx = i
|
|
89
|
+
trade_dir = "BUY"
|
|
90
|
+
elif signals[i] == "SELL":
|
|
91
|
+
in_trade = True
|
|
92
|
+
entry_price = price
|
|
93
|
+
entry_idx = i
|
|
94
|
+
trade_dir = "SELL"
|
|
95
|
+
else:
|
|
96
|
+
# Hitung pergerakan harga
|
|
97
|
+
if trade_dir == "BUY":
|
|
98
|
+
pnl_pct = (price - entry_price) / entry_price * 100
|
|
99
|
+
else:
|
|
100
|
+
pnl_pct = (entry_price - price) / entry_price * 100
|
|
101
|
+
|
|
102
|
+
# Cek SL / TP / exit signal
|
|
103
|
+
hit_sl = pnl_pct <= -sl_pct
|
|
104
|
+
hit_tp = pnl_pct >= tp_pct
|
|
105
|
+
exit_signal = (trade_dir == "BUY" and signals[i] == "SELL") or \
|
|
106
|
+
(trade_dir == "SELL" and signals[i] == "BUY")
|
|
107
|
+
|
|
108
|
+
if hit_sl or hit_tp or exit_signal:
|
|
109
|
+
pnl_dollar = balance * (pnl_pct / 100)
|
|
110
|
+
balance += pnl_dollar
|
|
111
|
+
if balance > peak_balance:
|
|
112
|
+
peak_balance = balance
|
|
113
|
+
dd = (peak_balance - balance) / peak_balance * 100
|
|
114
|
+
if dd > max_drawdown:
|
|
115
|
+
max_drawdown = dd
|
|
116
|
+
|
|
117
|
+
trades.append({
|
|
118
|
+
"entry_idx" : entry_idx,
|
|
119
|
+
"exit_idx" : i,
|
|
120
|
+
"direction" : trade_dir,
|
|
121
|
+
"entry_price": round(entry_price, 5),
|
|
122
|
+
"exit_price" : round(price, 5),
|
|
123
|
+
"pnl_pct" : round(pnl_pct, 4),
|
|
124
|
+
"pnl_dollar" : round(pnl_dollar, 2),
|
|
125
|
+
"result" : "WIN" if pnl_pct > 0 else "LOSS",
|
|
126
|
+
"exit_reason": "TP" if hit_tp else "SL" if hit_sl else "SIGNAL",
|
|
127
|
+
"balance" : round(balance, 2),
|
|
128
|
+
})
|
|
129
|
+
in_trade = False
|
|
130
|
+
|
|
131
|
+
# ── HITUNG STATISTIK ───────────────────────────────────
|
|
132
|
+
total_trades = len(trades)
|
|
133
|
+
if total_trades == 0:
|
|
134
|
+
if not silent:
|
|
135
|
+
print(" \033[33m⚠\033[0m Tidak ada trade yang terjadi. "
|
|
136
|
+
"Coba turunkan agresivitas.\n")
|
|
137
|
+
return {"trades": [], "stats": {}}
|
|
138
|
+
|
|
139
|
+
wins = [t for t in trades if t["result"] == "WIN"]
|
|
140
|
+
losses = [t for t in trades if t["result"] == "LOSS"]
|
|
141
|
+
winrate = len(wins) / total_trades * 100
|
|
142
|
+
|
|
143
|
+
total_pnl = sum(t["pnl_dollar"] for t in trades)
|
|
144
|
+
avg_win = np.mean([t["pnl_pct"] for t in wins]) if wins else 0
|
|
145
|
+
avg_loss = np.mean([t["pnl_pct"] for t in losses]) if losses else 0
|
|
146
|
+
profit_factor = (sum(t["pnl_dollar"] for t in wins) /
|
|
147
|
+
abs(sum(t["pnl_dollar"] for t in losses)) + 1e-9) if losses else 999
|
|
148
|
+
|
|
149
|
+
rr_ratio = abs(avg_win / avg_loss) if avg_loss != 0 else 999
|
|
150
|
+
final_balance = balance
|
|
151
|
+
total_return = (final_balance - 10000) / 10000 * 100
|
|
152
|
+
|
|
153
|
+
stats = {
|
|
154
|
+
"total_trades" : total_trades,
|
|
155
|
+
"wins" : len(wins),
|
|
156
|
+
"losses" : len(losses),
|
|
157
|
+
"winrate" : round(winrate, 2),
|
|
158
|
+
"total_return" : round(total_return, 2),
|
|
159
|
+
"final_balance" : round(final_balance, 2),
|
|
160
|
+
"profit_factor" : round(profit_factor, 2),
|
|
161
|
+
"max_drawdown" : round(max_drawdown, 2),
|
|
162
|
+
"avg_win_pct" : round(avg_win, 4),
|
|
163
|
+
"avg_loss_pct" : round(avg_loss, 4),
|
|
164
|
+
"rr_ratio" : round(rr_ratio, 2),
|
|
165
|
+
"strategy" : strategy,
|
|
166
|
+
"bars_tested" : n,
|
|
167
|
+
"sl_pct" : sl_pct,
|
|
168
|
+
"tp_pct" : tp_pct,
|
|
169
|
+
"agresivitas" : agresivitas,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if not silent:
|
|
173
|
+
_print_report(stats, trades[-5:])
|
|
174
|
+
|
|
175
|
+
return {"trades": trades, "stats": stats}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ── DISPLAY HELPERS ────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
def _print_start(n, strategy, agresivitas, sl_pct, tp_pct):
|
|
181
|
+
print(f"\n \033[1m\033[37m NexTrade Backtest Engine\033[0m")
|
|
182
|
+
print(f" \033[36m{'─' * 48}\033[0m")
|
|
183
|
+
print(f" \033[1mStrategi :\033[0m {strategy}")
|
|
184
|
+
print(f" \033[1mTotal Bar :\033[0m {n:,} candle")
|
|
185
|
+
print(f" \033[1mModal Awal :\033[0m $10,000")
|
|
186
|
+
print(f" \033[1mStop Loss :\033[0m {sl_pct}%")
|
|
187
|
+
print(f" \033[1mTake Profit :\033[0m {tp_pct}%")
|
|
188
|
+
print(f" \033[1mAgresivitas :\033[0m {agresivitas}%")
|
|
189
|
+
print(f" \033[36m{'─' * 48}\033[0m\n")
|
|
190
|
+
|
|
191
|
+
def _print_report(stats: dict, last_trades: list):
|
|
192
|
+
wr = stats["winrate"]
|
|
193
|
+
ret = stats["total_return"]
|
|
194
|
+
bal = stats["final_balance"]
|
|
195
|
+
pf = stats["profit_factor"]
|
|
196
|
+
dd = stats["max_drawdown"]
|
|
197
|
+
rr = stats["rr_ratio"]
|
|
198
|
+
|
|
199
|
+
ret_color = "\033[32m" if ret >= 0 else "\033[31m"
|
|
200
|
+
wr_color = "\033[32m" if wr >= 50 else "\033[31m"
|
|
201
|
+
|
|
202
|
+
print(f"\n \033[1m\033[37m Hasil Backtest\033[0m")
|
|
203
|
+
print(f" \033[36m{'─' * 48}\033[0m")
|
|
204
|
+
print(f" \033[1mTotal Trade :\033[0m {stats['total_trades']}")
|
|
205
|
+
print(f" \033[1mWin / Loss :\033[0m {stats['wins']} / {stats['losses']}")
|
|
206
|
+
print(f" \033[1mWinrate :\033[0m {wr_color}{wr:.1f}%\033[0m")
|
|
207
|
+
print(f" \033[1mTotal Return :\033[0m {ret_color}{ret:+.2f}%\033[0m "
|
|
208
|
+
f"(${bal:,.2f})")
|
|
209
|
+
print(f" \033[1mProfit Factor :\033[0m {pf:.2f} \033[2m(>1.5 = bagus)\033[0m")
|
|
210
|
+
print(f" \033[1mMax Drawdown :\033[0m \033[31m{dd:.2f}%\033[0m")
|
|
211
|
+
print(f" \033[1mRisk:Reward :\033[0m 1 : {rr:.2f}")
|
|
212
|
+
print(f" \033[36m{'─' * 48}\033[0m")
|
|
213
|
+
|
|
214
|
+
# Grade otomatis
|
|
215
|
+
grade, color = _grade(wr, ret, dd, pf)
|
|
216
|
+
print(f"\n \033[1mGrade Model :\033[0m {color}{grade}\033[0m\n")
|
|
217
|
+
|
|
218
|
+
# 5 trade terakhir
|
|
219
|
+
if last_trades:
|
|
220
|
+
print(f" \033[2m5 Trade Terakhir:\033[0m")
|
|
221
|
+
for t in last_trades:
|
|
222
|
+
c = "\033[32m" if t["result"] == "WIN" else "\033[31m"
|
|
223
|
+
print(f" {c}{t['result']:<5}\033[0m {t['direction']:<5} "
|
|
224
|
+
f"{t['pnl_pct']:+.2f}% ${t['pnl_dollar']:+.2f} "
|
|
225
|
+
f"\033[2m({t['exit_reason']})\033[0m")
|
|
226
|
+
print()
|
|
227
|
+
|
|
228
|
+
def _grade(winrate, total_return, max_dd, profit_factor):
|
|
229
|
+
score = 0
|
|
230
|
+
if winrate >= 60: score += 3
|
|
231
|
+
elif winrate >= 50: score += 2
|
|
232
|
+
elif winrate >= 40: score += 1
|
|
233
|
+
|
|
234
|
+
if total_return >= 30: score += 3
|
|
235
|
+
elif total_return >= 10: score += 2
|
|
236
|
+
elif total_return >= 0: score += 1
|
|
237
|
+
|
|
238
|
+
if max_dd <= 10: score += 3
|
|
239
|
+
elif max_dd <= 20: score += 2
|
|
240
|
+
elif max_dd <= 30: score += 1
|
|
241
|
+
|
|
242
|
+
if profit_factor >= 2: score += 2
|
|
243
|
+
elif profit_factor >= 1.5: score += 1
|
|
244
|
+
|
|
245
|
+
if score >= 10: return "S — Luar Biasa! 🏆", "\033[33m"
|
|
246
|
+
elif score >= 8: return "A — Sangat Bagus ⭐", "\033[32m"
|
|
247
|
+
elif score >= 6: return "B — Bagus, bisa dipakai", "\033[32m"
|
|
248
|
+
elif score >= 4: return "C — Perlu optimasi", "\033[33m"
|
|
249
|
+
else: return "D — Perlu banyak perbaikan", "\033[31m"
|
|
File without changes
|