سلام دوست عزیز
در ادامه کدی آماده کردم که شامل دو بخش اصلی برای مدلهای پیشرفته یادگیری ماشین است:
- XGBoost برای پیشبینی حرکت قیمت با ویژگیهای فنی (ایچی موکو و سایر اطلاعات قیمتی)
- LSTM برای مدلسازی سریهای زمانی و پیشبینی حرکت قیمت بعدی
کد به گونهای نوشته شده که میتوانید بین دو مدل سوئیچ کنید و در نهایت ربات تصمیم میگیرد بر اساس پیشبینی مدل و سیگنال تکنیکال که قبلا گفتیم وارد معامله شود.
پیشنیاز نصب کتابخانهها
pip install MetaTrader5 pandas numpy matplotlib scikit-learn xgboost tensorflow
کد کامل با XGBoost و LSTM
import MetaTrader5 as mt5
import pandas as pd
import numpy as np
import datetime
import time
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import xgboost as xgb
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
# تنظیمات کلی
SYMBOL = "XAUUSD"
LOT = 0.01
TIMEFRAME = mt5.TIMEFRAME_M1
PIP = 0.01
STOP_LOSS_PIPS = 15
TAKE_PROFIT_PIPS = 30
# اتصال به متاتریدر
if not mt5.initialize():
print("MT5 initialize failed")
mt5.shutdown()
exit()
if not mt5.symbol_select(SYMBOL, True):
print(f"Symbol {SYMBOL} select failed")
mt5.shutdown()
exit()
# گرفتن دیتای OHLC
def get_ohlc(symbol, timeframe, n):
utc_to = datetime.datetime.now()
rates = mt5.copy_rates_from(symbol, timeframe, utc_to, n)
if rates is None or len(rates) == 0:
print(f"Failed to get rates for {symbol}")
return None
df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s')
return df
# محاسبه Ichimoku
def ichimoku(df):
high_9 = df['high'].rolling(window=9).max()
low_9 = df['low'].rolling(window=9).min()
df['tenkan_sen'] = (high_9 + low_9) / 2
high_26 = df['high'].rolling(window=26).max()
low_26 = df['low'].rolling(window=26).min()
df['kijun_sen'] = (high_26 + low_26) / 2
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
high_52 = df['high'].rolling(window=52).max()
low_52 = df['low'].rolling(window=52).min()
df['senkou_span_b'] = ((high_52 + low_52) / 2).shift(26)
df['chikou_span'] = df['close'].shift(-26)
df.dropna(inplace=True)
return df
# پرایس اکشن (Engulfing)
def is_bullish_engulfing(df):
if len(df) < 2:
return False
current = df.iloc[-1]
previous = df.iloc[-2]
return (current['open'] < current['close'] and
previous['open'] > previous['close'] and
current['open'] < previous['close'] and
current['close'] > previous['open'])
def is_bearish_engulfing(df):
if len(df) < 2:
return False
current = df.iloc[-1]
previous = df.iloc[-2]
return (current['open'] > current['close'] and
previous['open'] < previous['close'] and
current['open'] > previous['close'] and
current['close'] < previous['open'])
# حمایت و مقاومت پایه (میتوانید توسعه دهید)
def find_support_resistance(df, window=20):
highs = df['high']
lows = df['low']
supports = []
resistances = []
for i in range(window, len(df) - window):
high_slice = highs[i - window:i + window + 1]
low_slice = lows[i - window:i + window + 1]
current_high = highs[i]
current_low = lows[i]
if current_high == max(high_slice):
resistances.append(current_high)
if current_low == min(low_slice):
supports.append(current_low)
return supports, resistances
# سیگنال تکنیکال ترکیبی ساده
def signal_generator(df):
last_row = df.iloc[-1]
last_close = last_row['close']
price_above_cloud = (last_close > last_row['senkou_span_a']) and (last_close > last_row['senkou_span_b'])
price_below_cloud = (last_close < last_row['senkou_span_a']) and (last_close < last_row['senkou_span_b'])
tenkan_above_kijun = last_row['tenkan_sen'] > last_row['kijun_sen']
tenkan_below_kijun = last_row['tenkan_sen'] < last_row['kijun_sen']
bullish_engulfing = is_bullish_engulfing(df)
bearish_engulfing = is_bearish_engulfing(df)
supports, resistances = find_support_resistance(df)
near_support = any(abs(last_close - sup) < 10 * PIP for sup in supports)
near_resistance = any(abs(last_close - res) < 10 * PIP for res in resistances)
if price_above_cloud and tenkan_above_kijun and bullish_engulfing and near_support:
return "buy"
if price_below_cloud and tenkan_below_kijun and bearish_engulfing and near_resistance:
return "sell"
return "hold"
# آمادهسازی داده برای XGBoost و RandomForest (شامل همین کد)
def prepare_ml_dataset(df):
df = ichimoku(df)
df['return'] = df['close'].pct_change()
df['diff_tk_kj'] = df['tenkan_sen'] - df['kijun_sen']
df['diff_spans'] = df['senkou_span_a'] - df['senkou_span_b']
df.dropna(inplace=True)
features = ['tenkan_sen','kijun_sen','senkou_span_a','senkou_span_b','chikou_span','close','return','diff_tk_kj','diff_spans']
X = df[features]
y = (df['close'].shift(-1) > df['close']).astype(int)
X = X[:-1]
y = y[:-1]
return X, y
# آموزش مدل XGBoost
def train_xgboost(X, y):
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=42)
model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss', verbosity=0)
model.fit(X_train, y_train)
preds = model.predict(X_test)
print("XGBoost Classification Report:\n",classification_report(y_test,preds))
return model
# آماده سازی داده برای LSTM
def prepare_lstm_data(df, lookback=20):
df = ichimoku(df)
df['return'] = df['close'].pct_change()
df['diff_tk_kj'] = df['tenkan_sen'] - df['kijun_sen']
df['diff_spans'] = df['senkou_span_a'] - df['senkou_span_b']
df.dropna(inplace=True)
features = ['tenkan_sen','kijun_sen','senkou_span_a','senkou_span_b','chikou_span','close','return','diff_tk_kj','diff_spans']
data = df[features].values
X = []
y = []
for i in range(lookback, len(data)-1):
X.append(data[i-lookback:i])
label = 1 if df['close'].iloc[i+1] > df['close'].iloc[i] else 0
y.append(label)
return np.array(X), np.array(y)
# ساخت مدل ساده LSTM
def build_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(64, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(32))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# آموزش مدل LSTM
def train_lstm(X, y, epochs=20, batch_size=32):
model = build_lstm_model((X.shape[1], X.shape[2]))
es = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
history = model.fit(X, y, epochs=epochs, batch_size=batch_size, validation_split=0.2, callbacks=[es], verbose=2)
return model, history
# ارسال سفارش با SL و TP
def place_order(symbol, lot, order_type):
tick = mt5.symbol_info_tick(symbol)
price = tick.ask if order_type == "buy" else tick.bid
deviation = 10
if order_type == "buy":
sl = price - STOP_LOSS_PIPS * PIP
tp = price + TAKE_PROFIT_PIPS * PIP
order_type_mt5 = mt5.ORDER_TYPE_BUY
else:
sl = price + STOP_LOSS_PIPS * PIP
tp = price - TAKE_PROFIT_PIPS * PIP
order_type_mt5 = mt5.ORDER_TYPE_SELL
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot,
"type": order_type_mt5,
"price": price,
"sl": sl,
"tp": tp,
"deviation": deviation,
"magic": 234000,
"comment": "Auto trade with ML",
"type_filling": mt5.ORDER_FILLING_RETURN,
}
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print(f"Order failed, retcode={result.retcode}")
return False
else:
print(f"Order placed: {order_type} {lot} at price {price}, SL: {sl}, TP: {tp}")
return True
# اجرای ربات با XGBoost یا LSTM
def main(algorithm="xgboost"):
print("دادهها را برای آموزش مدل میگیریم ...")
df = get_ohlc(SYMBOL, TIMEFRAME, 1000)
if df is None or len(df) < 500:
print("داده کافی برای آموزش موجود نیست.")
return
if algorithm == "xgboost":
X, y = prepare_ml_dataset(df)
model = train_xgboost(X, y)
elif algorithm == "lstm":
X, y = prepare_lstm_data(df, lookback=20)
model, _ = train_lstm(X, y)
else:
print("الگوریتم نامعتبر است")
return
print(f"مدل {algorithm} آموزش داده شد.")
while True:
df_new = get_ohlc(SYMBOL, TIMEFRAME, 60)
if df_new is None or len(df_new) < 60:
print("دریافت داده ناموفق، تاخیر 60 ثانیه...")
time.sleep(60)
continue
df_new = ichimoku(df_new)
signal_tech = signal_generator(df_new)
print(f"سیگنال تکنیکال: {signal_tech}")
if algorithm == "xgboost":
features = ['tenkan_sen','kijun_sen','senkou_span_a','senkou_span_b','chikou_span','close']
last_row = df_new.iloc[[-1]][features].copy()
last_row['return'] = df_new['close'].pct_change().iloc[-1]
last_row['diff_tk_kj'] = last_row['tenkan_sen'].values[0] - last_row['kijun_sen'].values[0]
last_row['diff_spans'] = last_row['senkou_span_a'].values[0] - last_row['senkou_span_b'].values[0]
last_row = last_row.fillna(0)
pred = model.predict(last_row)[0]
else: # LSTM
features = ['tenkan_sen','kijun_sen','senkou_span_a','senkou_span_b','chikou_span','close','return','diff_tk_kj','diff_spans']
data = df_new[features].values
lookback = 20
if data.shape[0] < lookback:
print("دیتای کافی برای LSTM نیست.")
time.sleep(60)
continue
last_seq = data[-lookback:]
last_seq = np.expand_dims(last_seq, axis=0)
pred_prob = model.predict(last_seq)[0][0]
pred = 1 if pred_prob >= 0.5 else 0
print(f"احتمال حرکت صعودی توسط LSTM: {pred_prob:.2f}")
print(f"پیش بینی حرکت قیمت توسط مدل: {'صعودی' if pred==1 else 'نزولی'}")
if signal_tech == "buy" and pred == 1:
place_order(SYMBOL, LOT, "buy")
elif signal_tech == "sell" and pred == 0:
place_order(SYMBOL, LOT, "sell")
else:
print("سیگنال مطمئن برای معامله وجود ندارد.")
time.sleep(60)
if __name__ == "__main__":
# اجرای ربات، الگوریتم را انتخاب کنید:
# main("xgboost")
# main("lstm")
mt5.shutdown()
توضیحات:
- در تابع اصلی
main() با مقدار "xgboost" مدل XGBoost آموزش داده و استفاده میشود.
- با مقدار
"lstm" مدل LSTM آموزش داده و استفاده میشود.
- آموزش مدل روی دیتای 1000 کندل قبلی است.
- هر دقیقه داده جدید گرفته، اندیکاتور محاسبه شده، سیگنال تکنیکال تولید میشود، سپس مدل ML پیشبینی حرکت میکند.
- اگر سیگنال تکنیکال و پیشبینی مدل همجهت بودند، سفارش ارسال میشود.
- LSTM از داده 20 کندل قبلی استفاده میکند (دقت کنید که قبل از اجرا دیتا کافی به لست بدهید).
- مدیریت ریسک (حد ضرر و حد سود) در ارسال سفارش لحاظ شده.
اگر نیاز داشتی میتونم کدهای تحلیل پیشرفتهتر یا بکتست دقیقتر و همچنین زمانبندیهای بهینهتر هم برات آماده کنم.
موفق باشید!