tickdata / simulate_arrow_v9.py
gionuibk's picture
Upload simulate_arrow_v9.py with huggingface_hub
f07afb1 verified
Raw
History Blame Contribute Delete
7.63 kB
import pandas as pd
import numpy as np
print("🚀 Khởi chạy Bộ Giả Lập Mũi Tên Bí Mật (Diamond V8 + K-Ratio + Fibo)")
print("Load file: native_rates_M5.parquet...")
try:
df = pd.read_parquet('native_rates_M5.parquet')
except Exception as e:
print(f"Lỗi đọc file: {e}")
exit(1)
# Cấu hình rủi ro từ User
SPREAD = 32 # Spread tĩnh 32 mxc
SLIPPAGE = 10 # Trượt giá khi nổ Vol Spike 10 mxc
TOTAL_PENALTY = SPREAD + SLIPPAGE # Tổng thiệt thòi: 42 points
TP_PTS = 150 # Kinetic Trailing Kích hoạt (Win)
SL_PTS = 300 # Ngưỡng Sập Cứng (Lose)
# Tính Point = 0.01 (Mặc định cho MT5 XAUUSD 2 chữ số thập phân)
# Cần check nếu df có 3 chữ số thập phân thì hệ số khác
POINT = 0.01
print(f"🔧 Cấu hình: Thay vì khớp giá chuẩn, mỗi lệnh chịu phạt: {TOTAL_PENALTY} Points")
print(f"🎯 Kích hoạt Win (Kinetic): +{TP_PTS} Points")
print(f"💀 Kích hoạt Dead (Stoploss): -{SL_PTS} Points")
# ==========================================
# Giai Đoạn 1: Cấu trúc Indicator Data
# ==========================================
# 1. Tính ATR(14)
df['prev_close'] = df['close'].shift(1)
df['tr1'] = df['high'] - df['low']
df['tr2'] = (df['high'] - df['prev_close']).abs()
df['tr3'] = (df['low'] - df['prev_close']).abs()
df['TR'] = df[['tr1', 'tr2', 'tr3']].max(axis=1)
df['ATR_14'] = df['TR'].rolling(window=14).mean().shift(1)
# 2. Tính Donchian(14) và Kênh Fibo
df['DonUpper'] = df['high'].rolling(14).max().shift(1)
df['DonLower'] = df['low'].rolling(14).min().shift(1)
df['DonHeight'] = df['DonUpper'] - df['DonLower']
df['Fibo618'] = df['DonLower'] + df['DonHeight'] * 0.618
df['Fibo382'] = df['DonLower'] + df['DonHeight'] * 0.382
# Tính Range của cây nến hiện tại
df['Range'] = df['high'] - df['low']
# ==========================================
# Giai Đoạn 2: Thưởng Phạt Mũi Tên Đột Phá
# ==========================================
# Luật Bí Mật 1: K-Ratio
# Cây nến báo tín hiệu phải có đột phá dòng tiền cực lớn (K-Ratio quá 2.5 lần ATR bình thường)
cond_kratio = df['Range'] > (2.5 * df['ATR_14'])
# Luật Bí Mật 2: Nến Cụt Râu Xuyên Phá (Wickless Penetration)
# Nến Buy bứt phá không được để lại râu dài ở trên đỉnh bẫy ngỗng. Tối đa râu cho phép = 15% tổng độ dài nến.
wick_ratio_buy = (df['high'] - df['close']) / df['Range']
wick_ratio_sell = (df['close'] - df['low']) / df['Range']
cond_wickless_buy = wick_ratio_buy <= 0.15
cond_wickless_sell = wick_ratio_sell <= 0.15
# Luật Bí Mật 3: Nam Châm Fibonacci
# Điểm nổ nến phải đóng cửa cắt qua khu vực kiểm soát của Mập (Thế trận Fibo của Donchian Channel)
cond_fibo_buy = df['close'] > df['Fibo618']
cond_fibo_sell = df['close'] < df['Fibo382']
# Chốt danh sách mũi tên
df_reset = df.reset_index(drop=True)
buy_signals = df_reset.index[cond_kratio.values & cond_wickless_buy.values & cond_fibo_buy.values].tolist()
sell_signals = df_reset.index[cond_kratio.values & cond_wickless_sell.values & cond_fibo_sell.values].tolist()
print(f"🔍 Quét được {len(buy_signals)} Mũi Tên BUY và {len(sell_signals)} Mũi Tên SELL theo Bí Mật.")
# ==========================================
# Giai Đoạn 3: Mô Phỏng Forward Tương Lai
# ==========================================
highs = df['high'].values
lows = df['low'].values
closes = df['close'].values
n = len(df)
tp_usd = TP_PTS * POINT
sl_usd = SL_PTS * POINT
penalty_usd = TOTAL_PENALTY * POINT
# Thống kê
results = {
"BUY": {"win": 0, "lose": 0, "draw": 0},
"SELL": {"win": 0, "lose": 0, "draw": 0},
"BUY_REVERSE_TO_SELL": {"win": 0, "lose": 0, "draw": 0},
"SELL_REVERSE_TO_BUY": {"win": 0, "lose": 0, "draw": 0}
}
# Mô phỏng BUY
for idx in buy_signals:
if idx + 1 >= n: continue
# Giá thực khớp lệnh = Giả đóng cửa + Độ Nhăn của Sàn (Spread + Slippage)
entry_price = closes[idx] + penalty_usd
won = False
lost = False
# Quét tối đa 60 nến tương lai (5 tiếng đồng hồ) để xem
for j in range(1, min(61, n - idx)):
bars_high = highs[idx + j]
bars_low = lows[idx + j]
# Sàn tát cháy tài khoản trước (Âm 300 points)
if bars_low <= entry_price - sl_usd:
lost = True
break
# EA kéo kịp 150 points dời SL hòa vốn thành công (Win)
if bars_high >= entry_price + tp_usd:
won = True
break
if won: results["BUY"]["win"] += 1
elif lost: results["BUY"]["lose"] += 1
else: results["BUY"]["draw"] += 1 # 5 tiếng vẫn lẹt đẹt
# Mô phỏng SELL
for idx in sell_signals:
if idx + 1 >= n: continue
# Giá thực khớp lệnh (Bán khống rẻ đi vì Spread)
entry_price = closes[idx] - penalty_usd
won = False
lost = False
for j in range(1, min(61, n - idx)):
bars_high = highs[idx + j]
bars_low = lows[idx + j]
# Lỗ cứng
if bars_high >= entry_price + sl_usd:
lost = True
break
# Thắng
if bars_low <= entry_price - tp_usd:
won = True
break
if won: results["SELL"]["win"] += 1
elif lost: results["SELL"]["lose"] += 1
else: results["SELL"]["draw"] += 1
# Mô phỏng BUY REVERSE (Khớp tại tín hiệu SELL)
for idx in sell_signals:
if idx + 1 >= n: continue
entry_price = closes[idx] + penalty_usd
won, lost = False, False
for j in range(1, min(61, n - idx)):
bars_high = highs[idx + j]
bars_low = lows[idx + j]
if bars_low <= entry_price - sl_usd: lost = True; break
if bars_high >= entry_price + tp_usd: won = True; break
if won: results["SELL_REVERSE_TO_BUY"]["win"] += 1
elif lost: results["SELL_REVERSE_TO_BUY"]["lose"] += 1
# Mô phỏng SELL REVERSE (Khớp tại tín hiệu BUY)
for idx in buy_signals:
if idx + 1 >= n: continue
entry_price = closes[idx] - penalty_usd
won, lost = False, False
for j in range(1, min(61, n - idx)):
bars_high = highs[idx + j]
bars_low = lows[idx + j]
if bars_high >= entry_price + sl_usd: lost = True; break
if bars_low <= entry_price - tp_usd: won = True; break
if won: results["BUY_REVERSE_TO_SELL"]["win"] += 1
elif lost: results["BUY_REVERSE_TO_SELL"]["lose"] += 1
# ==========================================
# Giai Đoạn 4: Trả Báo Cáo
# ==========================================
print("\n" + "="*50)
print("📊 BÁO CÁO TOÁN HỌC KHẢO SÁT MŨI TÊN BÍ MẬT")
print("="*50)
for d in ["BUY", "SELL", "BUY_REVERSE_TO_SELL", "SELL_REVERSE_TO_BUY"]:
if d not in results: results[d] = {"win":0, "lose":0, "draw":0}
w = results[d].get("win", 0)
l = results[d].get("lose", 0)
dr = results[d].get("draw", 0)
total = w + l + dr
if total > 0:
win_rate = (w / (w + l)) * 100 if (w + l) > 0 else 0
print(f"Phe {d}:")
print(f" => WIN (+150 pts trước): {w}")
print(f" => LOSE (-300 pts trước): {l}")
print(f" => HÒA (Kẹt biên 5h): {dr}")
print(f" => WIN RATE THỰC CHIẾN: {win_rate:.2f} %")
else:
print(f"Phe {d}: Không có tín hiệu chuẩn.")
print("="*50)
print("Lưu ý: Mũi tên Thường của EA có WinRate ~50-51% nhưng đang bị nghẽn đạn Kiến.")
print("Hoàn tất Mô Phỏng!")