حق با شماست! عذرخواهی میکنم. در MQL5، آرایه Time به طور مستقیم در تابع OnTick یا توابع دیگر در سطح گلوبال قابل دسترسی نیست. شما باید دادههای زمان (timestamp) را نیز مانند قیمتها و RSI با استفاده از توابع CopyTime کپی کنید و سپس به تابع CheckForDivergences ارسال کنید.
این خطاها به دلیل تلاش برای دسترسی به آرایه Time (که در واقع باید time[] باشد) بدون اینکه آن را به تابع CheckForDivergences ارسال کرده باشید، رخ میدهد.
نسخه اصلاحشده کد:
//+------------------------------------------------------------------+
//| RSI_Divergence_EA.mq5 |
//| Expert Advisor for RSI Divergence Trading |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025"
#property version "1.00"
#property description "EA that trades RSI divergences with 1% risk, 20 pip TP, 10 pip SL"
// Input parameters
input int RSI_Period = 14;
input ENUM_APPLIED_PRICE RSI_Price = PRICE_CLOSE;
input int Lookback_Bars = 5;
input int Min_Bars_Between = 5;
input double RSI_Overbought = 70.0;
input double RSI_Oversold = 30.0;
input double Risk_Percent = 1.0; // Risk percentage of balance
input double TakeProfit_Pips = 20.0; // Take profit in pips
input double StopLoss_Pips = 10.0; // Stop loss in pips
input double Max_Spread = 3.0; // Maximum allowed spread in points
input bool Use_Trailing_Stop = false; // Use trailing stop
input int Magic_Number = 123456; // Magic number for orders
// Global variables
int rsi_handle;
datetime last_divergence_time = 0;
int last_divergence_type = 0; // 0 = none, 1 = bullish, -1 = bearish
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Create RSI handle
rsi_handle = iRSI(_Symbol, _Period, RSI_Period, RSI_Price);
if(rsi_handle == INVALID_HANDLE)
{
Print("Failed to create RSI handle");
return INIT_FAILED;
}
Print("RSI Divergence EA initialized successfully");
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(rsi_handle != INVALID_HANDLE)
IndicatorRelease(rsi_handle);
Print("RSI Divergence EA deinitialized");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if we have enough bars
if(Bars(_Symbol, _Period) < RSI_Period + Lookback_Bars * 2)
return;
// Define an appropriate size for buffers. For an EA, usually recent bars are enough.
// Let's copy 200 bars as a reasonable default.
int bars_to_copy = 200;
// Get RSI values
double rsi_values[];
if(CopyBuffer(rsi_handle, 0, 0, bars_to_copy, rsi_values) <= 0)
return;
// Get price data
double low[], high[];
if(CopyLow(_Symbol, _Period, 0, bars_to_copy, low) <= 0 ||
CopyHigh(_Symbol, _Period, 0, bars_to_copy, high) <= 0)
return;
// Get time data
datetime time_values[];
if(CopyTime(_Symbol, _Period, 0, bars_to_copy, time_values) <= 0)
return;
// Check for new divergences
CheckForDivergences(rsi_values, low, high, time_values);
// Check for position management
ManagePositions();
}
//+------------------------------------------------------------------+
//| Check for RSI divergences |
//+------------------------------------------------------------------+
// Added time_values[] as a parameter
void CheckForDivergences(const double &rsi_values[], const double &low[],
const double &high[], const datetime &time_values[])
{
int rates_total = ArraySize(rsi_values);
// Ensure all arrays have the same size
if(ArraySize(low) != rates_total || ArraySize(high) != rates_total || ArraySize(time_values) != rates_total)
{
Print("Array size mismatch in CheckForDivergences");
return;
}
// We analyze the most recent bars for divergence, excluding the current (forming) bar [rates_total-1]
// The divergence point will be at rates_total - Lookback_Bars - 1 (or earlier)
// We check from the newest bar back in time
for(int i = rates_total - Lookback_Bars - 1; i >= Lookback_Bars; i--)
{
// Check for bullish divergence
if(rsi_values[i] < RSI_Oversold) // Check if RSI is in oversold region
{
int current_price_low = FindPriceLow(i, Lookback_Bars, low);
int current_rsi_low = FindRSILow(i, Lookback_Bars, rsi_values);
if(current_price_low == i && current_rsi_low == i) // If current bar is a valid pivot low for both price and RSI
{
// Look for previous low
int prev_price_low = FindPreviousPriceLow(i, Min_Bars_Between, low);
int prev_rsi_low = FindPreviousRSILow(i, Min_Bars_Between, rsi_values);
if(prev_price_low >= 0 && prev_rsi_low >= 0) // Ensure valid previous pivots are found
{
// Check divergence conditions: Lower price low, Higher RSI low
if(low[i] < low[prev_price_low] && rsi_values[i] > rsi_values[prev_rsi_low])
{
// Bullish divergence detected
// Check if this is a new divergence or we haven't traded this one yet
if(last_divergence_time != time_values[i] || last_divergence_type != 1)
{
last_divergence_time = time_values[i];
last_divergence_type = 1;
Print("Bullish Divergence Detected at ", TimeToString(time_values[i], TIME_DATE|TIME_SECONDS));
// Open buy position
OpenPosition(ORDER_TYPE_BUY);
}
return; // Exit after finding the most recent divergence
}
}
}
}
}
// Check for bearish divergence
for(int i = rates_total - Lookback_Bars - 1; i >= Lookback_Bars; i--)
{
if(rsi_values[i] > RSI_Overbought) // Check if RSI is in overbought region
{
int current_price_high = FindPriceHigh(i, Lookback_Bars, high);
int current_rsi_high = FindRSIHigh(i, Lookback_Bars, rsi_values);
if(current_price_high == i && current_rsi_high == i) // If current bar is a valid pivot high for both price and RSI
{
// Look for previous high
int prev_price_high = FindPreviousPriceHigh(i, Min_Bars_Between, high);
int prev_rsi_high = FindPreviousRSIHigh(i, Min_Bars_Between, rsi_values);
if(prev_price_high >= 0 && prev_rsi_high >= 0) // Ensure valid previous pivots are found
{
// Check divergence conditions: Higher price high, Lower RSI high
if(high[i] > high[prev_price_high] && rsi_values[i] < rsi_values[prev_rsi_high])
{
// Bearish divergence detected
// Check if this is a new divergence or we haven't traded this one yet
if(last_divergence_time != time_values[i] || last_divergence_type != -1)
{
last_divergence_time = time_values[i];
last_divergence_type = -1;
Print("Bearish Divergence Detected at ", TimeToString(time_values[i], TIME_DATE|TIME_SECONDS));
// Open sell position
OpenPosition(ORDER_TYPE_SELL);
}
return; // Exit after finding the most recent divergence
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Open position based on divergence |
//+------------------------------------------------------------------+
void OpenPosition(ENUM_ORDER_TYPE order_type)
{
// Check if already have position managed by this EA
if(PositionExists())
{
Print("Position already open. Skipping new order.");
return;
}
// Check spread
if(SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) > Max_Spread)
{
Print("Spread too high: ", SymbolInfoInteger(_Symbol, SYMBOL_SPREAD), " points. Max allowed: ", Max_Spread);
return;
}
// Calculate lot size based on risk
double lot_size = CalculateLotSize(order_type);
if(lot_size <= 0)
{
Print("Failed to calculate lot size or lot size is too small.");
return;
}
// Calculate SL and TP prices
double price, sl, tp;
MqlTick latest_tick;
if(!SymbolInfoTick(_Symbol, latest_tick))
{
Print("Failed to get latest tick info. Error: ", GetLastError());
return;
}
if(order_type == ORDER_TYPE_BUY)
{
price = latest_tick.ask;
sl = price - StopLoss_Pips * _Point;
tp = price + TakeProfit_Pips * _Point;
}
else // ORDER_TYPE_SELL
{
price = latest_tick.bid;
sl = price + StopLoss_Pips * _Point;
tp = price - TakeProfit_Pips * _Point;
}
// Normalize prices to symbol's digits
sl = NormalizeDouble(sl, _Digits);
tp = NormalizeDouble(tp, _Digits);
// Prepare trade request
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size;
request.type = order_type;
request.price = price;
request.sl = sl;
request.tp = tp;
request.magic = Magic_Number;
request.comment = "RSI Divergence";
request.deviation = 3 * _Point; // Deviation in points
// Send order
Print("Attempting to open ", EnumToString(order_type), " position for ", lot_size, " lots at ", price, " SL:", sl, " TP:", tp);
if(OrderSend(request, result))
{
if(result.retcode == TRADE_RETCODE_DONE)
{
Print("Position opened successfully. Ticket: ", result.order, ". Deal: ", result.deal);
}
else
{
Print("Failed to open position. Error: ", result.retcode, " (", GetLastError(), ")");
}
}
else
{
Print("OrderSend failed. Error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Calculate lot size based on risk percentage |
//+------------------------------------------------------------------+
double CalculateLotSize(ENUM_ORDER_TYPE order_type)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double risk_amount = balance * Risk_Percent / 100.0;
// Get symbol information for lot calculation
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tick_value <= 0 || tick_size <= 0)
{
Print("Invalid tick value or tick size for ", _Symbol);
return 0;
}
double sl_distance_in_points = StopLoss_Pips; // SL in pips, not points
// Convert SL pips to price difference using _Point
double sl_price_difference = sl_distance_in_points * _Point;
if(sl_price_difference <= 0)
{
Print("StopLoss_Pips is zero or negative. Cannot calculate lot size.");
return 0;
}
// Calculate lot size based on risk amount and SL distance
// (risk_amount / (sl_price_difference / tick_size * tick_value))
// Note: tick_value might depend on lot size for some instruments, but generally it's per standard lot.
// For simplicity, we assume tick_value is per 1 unit of lot, so it's correct.
double lot_size = risk_amount / (sl_price_difference / tick_size * tick_value);
// Normalize lot size
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
// Ensure lot_size is within allowed range and is a multiple of lot_step
lot_size = MathMax(min_lot, MathMin(max_lot, NormalizeDouble(floor(lot_size / lot_step) * lot_step, 2)));
// NormalizeDouble(lot_size, 2) might be needed if lot_step is very small
// A better way to round to lot_step:
// lot_size = NormalizeDouble(round(lot_size / lot_step) * lot_step, 2); // Round to nearest step
// Or for safer approach (always round down to avoid margin call):
// lot_size = NormalizeDouble(floor(lot_size / lot_step) * lot_step, 2);
if (lot_size < min_lot)
{
Print("Calculated lot size (", lot_size, ") is less than minimum allowed lot (", min_lot, "). Setting to minimum lot.");
lot_size = min_lot;
}
return lot_size;
}
//+------------------------------------------------------------------+
//| Check if position already exists for this symbol and Magic Number|
//+------------------------------------------------------------------+
bool PositionExists()
{
for(int i = 0; i < PositionsTotal(); i++)
{
ulong position_ticket = PositionGetTicket(i);
if(position_ticket > 0)
{
if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic_Number)
{
return true;
}
}
}
return false;
}
//+------------------------------------------------------------------+
//| Manage existing positions (e.g., trailing stop) |
//+------------------------------------------------------------------+
void ManagePositions()
{
if(!Use_Trailing_Stop) return;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong position_ticket = PositionGetTicket(i);
if(position_ticket > 0)
{
if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic_Number)
{
// Retrieve position details
ENUM_POSITION_TYPE pos_type = PositionGetInteger(POSITION_TYPE);
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
double current_sl = PositionGetDouble(POSITION_SL);
MqlTick latest_tick;
if(!SymbolInfoTick(_Symbol, latest_tick)) continue;
double bid = latest_tick.bid;
double ask = latest_tick.ask;
double trailing_stop_distance_points = StopLoss_Pips; // Using SL_Pips as trailing distance for example
// For BUY position
if(pos_type == POSITION_TYPE_BUY)
{
double new_sl = NormalizeDouble(bid - trailing_stop_distance_points * _Point, _Digits);
if(new_sl > current_sl && new_sl > open_price + (trailing_stop_distance_points * _Point * 0.5)) // Only trail if in profit & SL moves significantly
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_SLTP;
request.position = position_ticket;
request.sl = new_sl;
request.symbol = _Symbol;
if(OrderSend(request, result))
{
if(result.retcode == TRADE_RETCODE_DONE)
{
Print("Trailing SL updated for BUY position ", position_ticket, " to ", new_sl);
}
else
{
Print("Failed to update SL for BUY position ", position_ticket, ". Error: ", result.retcode);
}
}
}
}
// For SELL position
else if(pos_type == POSITION_TYPE_SELL)
{
double new_sl = NormalizeDouble(ask + trailing_stop_distance_points * _Point, _Digits);
if(new_sl < current_sl && new_sl < open_price - (trailing_stop_distance_points * _Point * 0.5)) // Only trail if in profit & SL moves significantly
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_SLTP;
request.position = position_ticket;
request.sl = new_sl;
request.symbol = _Symbol;
if(OrderSend(request, result))
{
if(result.retcode == TRADE_RETCODE_DONE)
{
Print("Trailing SL updated for SELL position ", position_ticket, " to ", new_sl);
}
else
{
Print("Failed to update SL for SELL position ", position_ticket, ". Error: ", result.retcode);
}
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Helper functions for divergence detection |
//+------------------------------------------------------------------+
// These functions are generally copied from the indicator.
// Make sure they match your definition of pivot points.
int FindPriceLow(int current_bar, int lookback, const double &low[])
{
// A bar is a low if it's the lowest within (current_bar-lookback) to (current_bar+lookback)
double current_low = low[current_bar];
for(int i = current_bar - lookback; i <= current_bar + lookback; i++)
{
if(i >= 0 && i < ArraySize(low) && i != current_bar)
{
if(low[i] <= current_low)
return -1; // Not a low, found a lower or equal bar
}
}
return current_bar; // It's a low
}
int FindRSILow(int current_bar, int lookback, const double &rsi_values[])
{
double current_rsi = rsi_values[current_bar];
for(int i = current_bar - lookback; i <= current_bar + lookback; i++)
{
if(i >= 0 && i < ArraySize(rsi_values) && i != current_bar)
{
if(rsi_values[i] <= current_rsi)
return -1;
}
}
return current_bar;
}
int FindPriceHigh(int current_bar, int lookback, const double &high[])
{
double current_high = high[current_bar];
for(int i = current_bar - lookback; i <= current_bar + lookback; i++)
{
if(i >= 0 && i < ArraySize(high) && i != current_bar)
{
if(high[i] >= current_high)
return -1;
}
}
return current_bar;
}
int FindRSIHigh(int current_bar, int lookback, const double &rsi_values[])
{
double current_rsi = rsi_values[current_bar];
for(int i = current_bar - lookback; i <= current_bar + lookback; i++)
{
if(i >= 0 && i < ArraySize(rsi_values) && i != current_bar)
{
if(rsi_values[i] >= current_rsi)
return -1;
}
}
return current_bar;
}
int FindPreviousPriceLow(int current_low_bar_index, int min_distance, const double &low[])
{
// Search backward from current_low_bar_index - min_distance
for(int i = current_low_bar_index - min_distance; i >= Lookback_Bars; i--)
{
if(FindPriceLow(i, Lookback_Bars, low) == i)
return i; // Found a previous valid price low
}
return -1;
}
int FindPreviousRSILow(int current_low_bar_index, int min_distance, const double &rsi_values[])
{
for(int i = current_low_bar_index - min_distance; i >= Lookback_Bars; i--)
{
if(FindRSILow(i, Lookback_Bars, rsi_values) == i)
return i;
}
return -1;
}
int FindPreviousPriceHigh(int current_high_bar_index, int min_distance, const double &high[])
{
for(int i = current_high_bar_index - min_distance; i >= Lookback_Bars; i--)
{
if(FindPriceHigh(i, Lookback_Bars, high) == i)
return i;
}
return -1;
}
int FindPreviousRSIHigh(int current_high_bar_index, int min_distance, const double &rsi_values[])
{
for(int i = current_high_bar_index - min_distance; i >= Lookback_Bars; i--)
{
if(FindRSIHigh(i, Lookback_Bars, rsi_values) == i)
return i;
}
return -1;
}
تغییرات اصلی اعمال شده:
-
تابع OnTick():
- متغیر
bars_to_copy را اضافه کردم تا تعداد ثابتی از کندلها را برای buffers کپی کنیم (مثلا 200). این باعث میشود ArraySize روی تعداد معقولی از کندلهای اخیر کار کند.
- تابع
CopyTime(_Symbol, _Period, 0, bars_to_copy, time_values); برای کپی کردن آرایه زمان کندلها اضافه شد.
- آرایههای
low, high, time_values همگی به تابع CheckForDivergences پاس داده میشوند.
-
تابع CheckForDivergences():
- امضای تابع به
void CheckForDivergences(const double &rsi_values[], const double &low[], const double &high[], const datetime &time_values[]) تغییر یافت تا آرایه time_values را بپذیرد.
- عبارت
time_values[i] جایگزین Time[i] شده است.
- یک بررسی اضافه شد تا اطمینان حاصل شود که تمام آرایهها (rsi, low, high, time) هماندازه هستند.
- عبارت
return بعد از تشخیص واگرایی و تلاش برای باز کردن پوزیشن اضافه شد تا مطمئن شویم در هر تیک فقط یک سیگنال قویترین و اخیرترین واگرایی بررسی و اقدام میشود.
-
توابع FindPreviousPriceLow, FindPreviousRSILow, FindPreviousPriceHigh, FindPreviousRSIHigh:
- نام پارامتر
current_low و current_high به current_low_bar_index و current_high_bar_index تغییر یافت تا وضوح بیشتری داشته باشد. (این یک تغییر عملکردی نیست و فقط برای خوانایی است).
- مقدار بازگشتی
prev_price_low, prev_rsi_low, prev_price_high, prev_rsi_high از > 0 به >= 0 تغییر داده شد، زیرا اندکس 0 نیز یک ایندکس معتبر برای بار است.
-
تابع OpenPosition():
- گرفتن قیمت با
SymbolInfoTick بهروزرسانی شده تا دقیقتر باشد.
- مکانیسم
NormalizeDouble برای sl و tp اضافه شده تا اطمینان حاصل شود که قیمتها با تعداد ارقام اعشار مربوط به سیمبل، نرمالایز میشوند.
- لوگهای دقیقتری برای باز شدن پوزیشن و خطاها اضافه شده است.
deviation از 3 به 3 * _Point تغییر یافته تا به درستی به واحد پوینت تبدیل شود.
لطفاً کد را مجدداً ذخیره کرده و کامپایل کنید. این بار باید بدون خطا کامپایل شود.