//+… · The Chat Archive
Explore //+------------------------------------------------------------------+ // Break of… Save Share Download ▾ Report//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap (full, compile) |
//| Added ADX filter and Losing Streak filter |
//| Added cooldown per candle & minimum time interval cooldown |
//| Improved cooldown after close - scanning recent closed deals |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.6"
#property strict
#include <Trade\Trade.mqh>
input double inpLot = 0.05;
input bool useRiskPercent = false;
input double riskPercent = 1.0; // Position risk % per trade
input int sl_atr_mult = 3;
input double r2r_ratio = 2.0;
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5;
input int atrPeriod = 14;
input int swingLookback = 20;
input ENUM_TIMEFRAMES swingTF = PERIOD_M1;
// Shortest-term MA (existing)
input int maPeriod = 50;
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15;
// Medium-term MA (new)
input int maPeriod2 = 100;
input ENUM_TIMEFRAMES maTimeframe2 = PERIOD_M15;
// Long-term MA (new)
input int maPeriod3 = 200;
input ENUM_TIMEFRAMES maTimeframe3 = PERIOD_M15;
input int tradeStartHour = 7;
input int tradeEndHour = 22;
input int maxPositions = 1;
input uint inpMagicNumber = 123456;
input bool enableTrailingSL = true;
enum ENUM_TrailingStopMode
{
TrailingNone = 0,
TrailingMarketStructure = 1,
TrailingATR = 2,
TrailingHybrid = 3
};
input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid;
input int ms_swingLookback = 20;
input double atr_trail_mult = 2.5;
input uint TrailUpdateIntervalSec = 15;
input double MinSLBufferATRMult = 1.0;
input double TrailingProfitTriggerPerc = 0.5;
input bool enableReverseEntries = false;
input double maxRiskPerTradePercent = 1.0; // Floating loss cap only!
input double maxDailyLossAmount = 500.0;
// --- ADX filter inputs ---
input int adxPeriod = 14; // ADX period
input double adxThreshold = 25.0; // ADX minimum threshold to allow trading
input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX timeframe to use for filtering
// --- Losing streak inputs ---
input int maxLosingStreak = 3; // Max consecutive losing trades allowed
// --- POST-CLOSE COOLDOWN ---
input int postCloseCooldownSeconds = 60; // Cooldown seconds after a position closes before new trades allowed.
CTrade trade;
int ma_handle = INVALID_HANDLE;
int ma_handle2 = INVALID_HANDLE; // Medium-term MA handle
int ma_handle3 = INVALID_HANDLE; // Long-term MA handle
int atr_handle = INVALID_HANDLE;
int adx_handle = INVALID_HANDLE; // ADX handle
Assistant2025-06-22 07:06 UTC Copy response
Assistant2025-06-22 07:06 UTC Copy response
In your EA, trend determination is based on the relative positions of three exponential moving averages (EMAs) calculated on a specific timeframe (maTimeframe, default M15). The three EMAs have different periods for short-, medium-, and long-term trends: 50, 100, and 200 periods respectively.
Assistant2025-06-22 07:07 UTC Copy response
what is now? this ?
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3);
Assistant2025-06-22 07:08 UTC Copy response
Yes, exactly — in your current EA code, the trend determination is done by:
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3);
where:
MA1 = EMA(50)
MA2 = EMA(100)
MA3 = EMA(200)
This logic checks if the short-term EMA is above the medium-term EMA and the medium-term is above the long-term EMA for an uptrend , or the reverse order for a downtrend .
What this means in simple terms:
If EMA(50) > EMA(100) > EMA(200) → the price is showing a consistent upward momentum across multiple timeframes → Uptrend
If EMA(50) < EMA(100) < EMA(200) → the price is showing consistent downward momentum → Downtrend
Otherwise, trend is considered neutral or sideways
To summarize:
This code is your current way of determining the trend.
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3); and price > ma2
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3); and price < ma2
Assistant2025-06-22 07:09 UTC Copy response
Yes, exactly! That’s a good way to combine the EMA stacking trend condition with a price vs a specific MA (e.g., the medium-term EMA, MA2) confirmation.
You can write it like this:
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); // or use Ask or last close price
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
Explanation:
For uptrend , you require:
EMA 50 > EMA 100 > EMA 200 (classic stacked EMA uptrend)
AND current price above EMA 100 (medium term) to confirm price strength inside the trend
For downtrend , you require:
Assistant2025-06-22 07:10 UTC Copy response
Good question! The best place to insert this trend determination update is inside your OnTick() function — right after you successfully fetch the MA values from the indicator buffers.
no, in my code , at what line numer i can find ?
Assistant2025-06-22 07:11 UTC Copy response
Your provided code snippet doesn't include line numbers, so I can't give you an exact numeric line number. However, I can guide you precisely where in your posted code you should insert the trend update logic:
Where to find the place in your code:
Assistant2025-06-22 07:12 UTC Copy response
Yes, exactly! In your code as posted, lines 862 and 863 are these:
bool is_uptrend = (MA1 > MA2) && (MA2 > MA3);
bool is_downtrend = (MA1 < MA2) && (MA2 < MA3);
These are the lines where you currently determine the trend using EMA stacking only .
What you should do:
Before line 862 (or right around there, immediately after you fetch/define the MAs ), insert the price-based trend confirmation, for example:
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
Then replace lines 862-863 with:
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
This way you maintain consistent variable naming in the rest of your code.
Summary
Insert price and emaUptrend/emaDowntrend around or just before line 862.
'close' - undeclared identifier test1.mq5 862 54
close, price... what to use for no error?
Assistant2025-06-22 07:15 UTC Copy response
The error 'close' - undeclared identifier means you're trying to use a variable named close that has never been declared or assigned a value.
In MQL5, close is not a predefined variable; you need to explicitly get the value from the candle data if you want to use the close price.
i used ask , and no error
Assistant2025-06-22 07:16 UTC Copy response
Great! Using Ask (or Bid) like this:
double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
is perfectly fine and will not cause an undeclared identifier error.
Why using Ask or Bid "works":
Ask and Bid are built-in functions/constants in MQL5 that give you the current market prices.
They don't require additional fetching or copying candle data.
Simple and reliable for intrabar price checks.
So your final working code snippet around line 862 can be:
double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); // or SYMBOL_BID
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
This is usually sufficient for trend confirmation unless you specifically want to compare the price at the last closed candle (which is often more stable but slower to react).
Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 10 (20 messages)
Language en
Conversation date Jun 22, 2025
Added to archive Nov 16, 2026
ID 01m7h42w62qnbkh869f6k4dwa1Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: c019702828f467ff3e52047cbdc60b2d
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
struct TrailingUpdateInfo
{
ulong position_ticket;
datetime last_update;
};
TrailingUpdateInfo g_trailingUpdateInfo[];
static double g_initialEquity = 0.0;
static datetime g_lastResetDay = 0;
static int g_currentLosingStreak = 0;
static datetime g_lastLosingStreakResetDay = 0;
static ulong g_lastHistoryTickTime = 0;
// *** Cooldown globals ***
datetime lastTradeCandleTime = 0; // last candle time when trade opened
ENUM_TIMEFRAMES cooldownTimeframe = swingTF; // timeframe for candle cooldown
datetime lastTradeOpenTime = 0; // last trade open timestamp
int tradeIntervalSeconds = 60; // min seconds between trades
//+------------------------------------------------------------------+
void ResetDailyEquityIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm;
TimeToStruct(now, tm);
MqlDateTime todayMidnight = {};
todayMidnight.year = tm.year;
todayMidnight.mon = tm.mon;
todayMidnight.day = tm.day;
todayMidnight.hour = 0;
todayMidnight.min = 0;
todayMidnight.sec = 0;
datetime midnightTime = StructToTime(todayMidnight);
if(g_lastResetDay != midnightTime)
{
g_lastResetDay = midnightTime;
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
PrintFormat("Daily equity reset at %s new initialEquity=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity);
}
}
//+------------------------------------------------------------------+
void ResetLosingStreakIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm;
TimeToStruct(now, tm);
MqlDateTime todayMidnight = {};
todayMidnight.year = tm.year;
todayMidnight.mon = tm.mon;
todayMidnight.day = tm.day;
todayMidnight.hour = 0;
todayMidnight.min = 0;
todayMidnight.sec = 0;
datetime midnightTime = StructToTime(todayMidnight);
if(g_lastLosingStreakResetDay != midnightTime)
{
g_lastLosingStreakResetDay = midnightTime;
g_currentLosingStreak = 0;
PrintFormat("Losing streak reset at new day %s", TimeToString(now, TIME_DATE|TIME_SECONDS));
}
}
//+------------------------------------------------------------------+
void UpdateLosingStreak()
{
datetime now = TimeCurrent();
if(!HistorySelect(now - 86400, now))
{
Print("HistorySelect failed");
return;
}
ulong maxClosedTime = 0;
int total = HistoryDealsTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = HistoryDealGetTicket(i);
datetime closeTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(closeTime <= g_lastHistoryTickTime)
continue;
maxClosedTime = MathMax(maxClosedTime, (ulong)closeTime);
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
if(symbol != _Symbol || magic != inpMagicNumber)
continue;
long entryType = HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(entryType != DEAL_ENTRY_OUT)
continue;
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
{
g_currentLosingStreak++;
PrintFormat("Losing trade detected (ticket %I64d, profit %.2f). Current losing streak: %d", ticket, profit, g_currentLosingStreak);
}
else
{
if(g_currentLosingStreak > 0)
PrintFormat("Winning trade detected (ticket %I64d, profit %.2f). Resetting losing streak.", ticket, profit);
g_currentLosingStreak = 0;
}
}
if(maxClosedTime > 0)
g_lastHistoryTickTime = maxClosedTime;
}
//+------------------------------------------------------------------+
double CalculateLotSize(double sl_distance_price)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0 || sl_distance_price <= 0)
return inpLot;
if(!useRiskPercent)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lot = inpLot;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
lot = MathFloor(lot / lot_step) * lot_step;
return lot;
}
else
{
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
return inpLot;
double point_value = tick_value / tick_size;
double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
if(calculatedLot <= 0)
return inpLot;
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lot = MathFloor(calculatedLot / lot_step) * lot_step;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
return lot;
}
}
//+------------------------------------------------------------------+
bool IsPositionOpen(ENUM_POSITION_TYPE type)
{
int total = PositionsTotal();
for(int i = 0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == type)
return true;
}
}
}
return false;
}
//+------------------------------------------------------------------+
bool CanUpdateTrailing(ulong ticket)
{
datetime now = TimeCurrent();
int count = ArraySize(g_trailingUpdateInfo);
for(int i=0; i<count; i++)
{
if(g_trailingUpdateInfo[i].position_ticket == ticket)
{
if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec)
return false;
g_trailingUpdateInfo[i].last_update = now;
return true;
}
}
ArrayResize(g_trailingUpdateInfo, count + 1);
g_trailingUpdateInfo[count].position_ticket = ticket;
g_trailingUpdateInfo[count].last_update = now;
return true;
}
//+------------------------------------------------------------------+
void UpdateTrailingStopByMarketStructure(ulong position_ticket)
{
if(!PositionSelectByTicket(position_ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double current_sl = PositionGetDouble(POSITION_SL);
double current_tp = PositionGetDouble(POSITION_TP);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
if(current_tp <= 0)
return;
if(!CanUpdateTrailing(position_ticket))
return;
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
if(bid <= 0 || ask <= 0)
return;
if(pos_type == POSITION_TYPE_BUY)
{
double half_tp_level = entry_price + 0.5 * (current_tp - entry_price);
if(bid < half_tp_level)
return;
int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
if(lowestBar < 0)
return;
double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
double buffer = 2 * point;
double new_sl = NormalizeDouble(swing_low - buffer, digits);
if(new_sl > current_sl && new_sl < entry_price)
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = new_sl;
req.tp = current_tp;
req.deviation = 10;
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
}
}
else if(pos_type == POSITION_TYPE_SELL)
{
double half_tp_level = entry_price - 0.5 * (entry_price - current_tp);
if(ask > half_tp_level)
return;
int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
if(highestBar < 0)
return;
double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
double buffer = 2 * point;
double new_sl = NormalizeDouble(swing_high + buffer, digits);
if(new_sl < current_sl && new_sl > entry_price)
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = new_sl;
req.tp = current_tp;
req.deviation = 10;
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
}
}
}
//+------------------------------------------------------------------+
void UpdateTrailingStopByATR(ulong position_ticket)
{
if(!PositionSelectByTicket(position_ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double current_sl = PositionGetDouble(POSITION_SL);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
if(!CanUpdateTrailing(position_ticket))
return;
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double atr_buf[];
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
return;
double atr = atr_buf[0];
if(atr <= 0)
return;
double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID)
: SymbolInfoDouble(symbol, SYMBOL_ASK);
if(current_price <= 0) return;
double new_sl = 0;
if(pos_type == POSITION_TYPE_BUY)
{
new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
double min_sl_dist = atr * MinSLBufferATRMult;
if(new_sl < (current_price - min_sl_dist))
new_sl = current_price - min_sl_dist;
if(new_sl > current_sl && new_sl < current_price)
{
MqlTradeRequest req={};
MqlTradeResult res={};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = new_sl;
req.tp = PositionGetDouble(POSITION_TP);
req.deviation = 10;
if(!OrderSend(req, res))
PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
else
PrintFormat("ATR trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
}
}
else if(pos_type == POSITION_TYPE_SELL)
{
new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
double min_sl_dist = atr * MinSLBufferATRMult;
if(new_sl > (current_price + min_sl_dist))
new_sl = current_price + min_sl_dist;
if(new_sl < current_sl && new_sl > current_price)
{
MqlTradeRequest req={};
MqlTradeResult res={};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = new_sl;
req.tp = PositionGetDouble(POSITION_TP);
req.deviation = 10;
if(!OrderSend(req, res))
PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
else
PrintFormat("ATR trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
}
}
}
//+------------------------------------------------------------------+
void UpdateTrailingStopHybrid(ulong position_ticket)
{
if(!PositionSelectByTicket(position_ticket))
return;
if(!CanUpdateTrailing(position_ticket))
return;
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double atr_buf[];
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
return;
double atr = atr_buf[0];
if(atr <= 0)
return;
double min_sl_distance = atr * MinSLBufferATRMult;
double initial_sl_dist = MathAbs(entry_price - sl);
if(initial_sl_dist <= 0) initial_sl_dist = atr * sl_atr_mult;
double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID)
: SymbolInfoDouble(symbol, SYMBOL_ASK);
if(current_price <= 0) return;
double move_in_profit = (pos_type == POSITION_TYPE_BUY) ? (current_price - entry_price) : (entry_price - current_price);
if(move_in_profit < TrailingProfitTriggerPerc * initial_sl_dist)
return;
double ms_new_sl = 0;
bool ms_sl_valid = false;
if(pos_type == POSITION_TYPE_BUY)
{
int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
if(lowestBar >= 0)
{
double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
ms_new_sl = NormalizeDouble(swing_low - 2point, digits);
ms_sl_valid = (ms_new_sl > sl) && (ms_new_sl < entry_price);
}
}
else if(pos_type == POSITION_TYPE_SELL)
{
int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
if(highestBar >= 0)
{
double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
ms_new_sl = NormalizeDouble(swing_high + 2 point, digits);
ms_sl_valid = (ms_new_sl < sl) && (ms_new_sl > entry_price);
}
}
double atr_new_sl = 0;
if(pos_type == POSITION_TYPE_BUY)
{
atr_new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
atr_new_sl = MathMax(atr_new_sl, current_price - min_sl_distance);
atr_new_sl = (atr_new_sl > sl && atr_new_sl < current_price) ? atr_new_sl : 0;
}
else if(pos_type == POSITION_TYPE_SELL)
{
atr_new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
atr_new_sl = MathMin(atr_new_sl, current_price + min_sl_distance);
atr_new_sl = (atr_new_sl < sl && atr_new_sl > current_price) ? atr_new_sl : 0;
}
double new_sl = 0;
if(ms_sl_valid && atr_new_sl > 0)
{
if(pos_type == POSITION_TYPE_BUY)
new_sl = MathMax(ms_new_sl, atr_new_sl);
else
new_sl = MathMin(ms_new_sl, atr_new_sl);
}
else if(ms_sl_valid)
new_sl = ms_new_sl;
else if(atr_new_sl > 0)
new_sl = atr_new_sl;
else
return;
bool update_sl = false;
if(pos_type == POSITION_TYPE_BUY)
update_sl = (new_sl > sl && new_sl < current_price);
else
update_sl = (new_sl < sl && new_sl > current_price);
if(update_sl)
{
MqlTradeRequest req={};
MqlTradeResult res={};
req.action = TRADE_ACTION_SLTP;
req.position = position_ticket;
req.symbol = symbol;
req.sl = new_sl;
req.tp = tp;
req.deviation = 10;
if(!OrderSend(req,res))
PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
}
}
//+------------------------------------------------------------------+
int OnInit()
{
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle == INVALID_HANDLE)
{
Print("Failed to create EMA handle");
return INIT_FAILED;
}
ma_handle2 = iMA(_Symbol, maTimeframe2, maPeriod2, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle2 == INVALID_HANDLE)
{
Print("Failed to create medium-term EMA handle");
IndicatorRelease(ma_handle);
return INIT_FAILED;
}
ma_handle3 = iMA(_Symbol, maTimeframe3, maPeriod3, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle3 == INVALID_HANDLE)
{
Print("Failed to create long-term EMA handle");
IndicatorRelease(ma_handle);
IndicatorRelease(ma_handle2);
return INIT_FAILED;
}
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
IndicatorRelease(ma_handle);
IndicatorRelease(ma_handle2);
IndicatorRelease(ma_handle3);
return INIT_FAILED;
}
adx_handle = iADX(_Symbol, adxTimeframe, adxPeriod);
if(adx_handle == INVALID_HANDLE)
{
Print("Failed to create ADX handle");
IndicatorRelease(ma_handle);
IndicatorRelease(ma_handle2);
IndicatorRelease(ma_handle3);
IndicatorRelease(atr_handle);
return INIT_FAILED;
}
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, TimeCurrent(), 0))
{
Print("Failed to create swing high line");
IndicatorRelease(ma_handle);
IndicatorRelease(ma_handle2);
IndicatorRelease(ma_handle3);
IndicatorRelease(atr_handle);
IndicatorRelease(adx_handle);
return INIT_FAILED;
}
ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen);
ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);
if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, TimeCurrent(), 0))
{
Print("Failed to create swing low line");
ObjectDelete(0, swingHighLineName);
IndicatorRelease(ma_handle);
IndicatorRelease(ma_handle2);
IndicatorRelease(ma_handle3);
IndicatorRelease(atr_handle);
IndicatorRelease(adx_handle);
return INIT_FAILED;
}
ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed);
ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true);
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(0, swingHighLineName);
ObjectDelete(0, swingLowLineName);
if(ma_handle != INVALID_HANDLE)
{
IndicatorRelease(ma_handle);
ma_handle = INVALID_HANDLE;
}
if(ma_handle2 != INVALID_HANDLE)
{
IndicatorRelease(ma_handle2);
ma_handle2 = INVALID_HANDLE;
}
if(ma_handle3 != INVALID_HANDLE)
{
IndicatorRelease(ma_handle3);
ma_handle3 = INVALID_HANDLE;
}
if(atr_handle != INVALID_HANDLE)
{
IndicatorRelease(atr_handle);
atr_handle = INVALID_HANDLE;
}
if(adx_handle != INVALID_HANDLE)
{
IndicatorRelease(adx_handle);
adx_handle = INVALID_HANDLE;
}
}
//+------------------------------------------------------------------+
void OnTick()
{
datetime now = TimeCurrent();
// Block trading if a position closed recently, using cooldown window
if(postCloseCooldownSeconds > 0 && IsRecentPositionClose(postCloseCooldownSeconds))
{
PrintFormat("Post-close cooldown active, skipping trades at %s", TimeToString(now));
return;
}
ResetDailyEquityIfNewDay();
ResetLosingStreakIfNewDay();
UpdateLosingStreak();
if(maxLosingStreak > 0 && g_currentLosingStreak >= maxLosingStreak)
{
PrintFormat("Current losing streak %d >= max allowed %d. No new trades allowed now.", g_currentLosingStreak, maxLosingStreak);
return;
}
if(g_initialEquity == 0.0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return;
}
//--- FLOATING RISK CLOSE LOGIC ---
if(maxRiskPerTradePercent > 0.0)
{
int total = PositionsTotal();
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double maxLossMoney = balance * (maxRiskPerTradePercent / 100.0);
for(int i=total-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
double currentProfit = PositionGetDouble(POSITION_PROFIT);
if(currentProfit < 0 && MathAbs(currentProfit) >= maxLossMoney)
{
PrintFormat("Closing position %I64d as floating loss reached %.2f (cap is %.2f)",
ticket, MathAbs(currentProfit), maxLossMoney);
trade.PositionClose(ticket);
}
}
}
}
}
//--- TRAILING SL ---
if(enableTrailingSL && trailingStopMode != TrailingNone)
{
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(trailingStopMode == TrailingMarketStructure)
UpdateTrailingStopByMarketStructure(ticket);
else if(trailingStopMode == TrailingATR)
UpdateTrailingStopByATR(ticket);
else if(trailingStopMode == TrailingHybrid)
UpdateTrailingStopHybrid(ticket);
}
}
}
}
//--- POSITION LIMIT CHECK ---
int openPosCount = 0, totalPositions = PositionsTotal();
for(int i=0; i<totalPositions; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
openPosCount++;
}
}
}
if(maxPositions > 0 && openPosCount >= maxPositions)
return;
//--- TRADING TIME ---
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
// --- MINIMUM TIME INTERVAL COOLDOWN CHECK ---
if(lastTradeOpenTime != 0 && (now - lastTradeOpenTime) < tradeIntervalSeconds)
return; // interval cooldown active, skip trade
// --- COOLDOWN PER CANDLE CHECK ---
MqlRates candleRates[];
if(CopyRates(_Symbol, cooldownTimeframe, 1, 1, candleRates) != 1)
{
Print("Failed to get last closed candle data for cooldown check");
return;
}
datetime currentCandleTime = candleRates[0].time;
if(currentCandleTime == lastTradeCandleTime)
return; // candle cooldown active, skip trade
//--- INDICATORS ---
double ma_buf1[], ma_buf2[], ma_buf3[];
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
double MA1 = ma_buf1[0];
double MA2 = ma_buf2[0];
double MA3 = ma_buf3[0];
double atr_buf[];
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
return;
double atr = atr_buf[0];
if(atr <= 0)
atr = 10.0 * _Point;
double adx_buf[];
if(adx_handle == INVALID_HANDLE)
{
Print("ADX handle invalid");
return;
}
if(CopyBuffer(adx_handle, 0, 1, 1, adx_buf) <= 0)
{
Print("Failed to copy ADX buffer");
return;
}
double adx_value = adx_buf[0];
if(adx_value < adxThreshold)
{
PrintFormat("ADX=%.2f below threshold %.2f, skipping new entries", adx_value, adxThreshold);
return;
}
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
if(highestBar < 0 || lowestBar < 0)
return;
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(ask <= 0 || bid <= 0)
return;
bool is_uptrend = (MA1 > MA2) && (MA2 > MA3);
bool is_downtrend = (MA1 < MA2) && (MA2 < MA3);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double lot = CalculateLotSize(sl_dist);
if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
return;
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Buy order rejected, retcode %d", result.retcode);
else
{
PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
else if(bid < lastSwingLow && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Sell order rejected, retcode %d", result.retcode);
else
{
PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
else
{
if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
else
{
PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
else
{
PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
}
//+------------------------------------------------------------------+
// IsRecentPositionClose function (scans recent closed position deals)
bool IsRecentPositionClose(uint cooldownSecs)
{
datetime now = TimeCurrent();
if(!HistorySelect(now - cooldownSecs - 10, now))
{
Print("HistorySelect failed");
return false;
}
int totalDeals = HistoryDealsTotal();
for(int i = totalDeals - 1; i >= 0; i--)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket == 0)
continue;
datetime dealTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(dealTime == 0 || (now - dealTime) > cooldownSecs)
continue;
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(symbol == _Symbol && magic == inpMagicNumber && entry == DEAL_ENTRY_OUT)
{
PrintFormat("Recent position close detected at %s, cooldown active.", TimeToString(dealTime));
return true;
}
}
return false;
}
//+------------------------------------------------------------------+
Your EA code looks quite comprehensive, implementing Break of Structure signals with multiple risk and trade filters, ADX and losing streak filters, cooldowns, and trailing stop modes.
Here is a concise summary of its key features and workflow, to confirm understanding or help you with modifications or debugging:
Key Features Summary:
Multiple Timeframe MAs: Uses 3 EMAs (50, 100, 200) on M15 timeframe for trend filtering.
Swing High/Low Detection: Uses iHighest/iLowest on swingTF (M1) to detect recent structure points for entries and trailing SL placement.
ATR-based SL & TP: Uses ATR on M5 for SL distances and TP based on R:R ratio.
ADX Filter: Trades allowed only if ADX (M15, period=14) above threshold (default 25).
Losing Streak Filter: Limits max consecutive losing trades, resets daily.
Equity & Drawdown Limits: Tracks daily equity drawdown, stops trading if exceeding max daily loss.
Floating Trade Risk Cap: Closes position if drawdown exceeds maxRiskPerTradePercent (floating risk cap).
Cooldown Filters:
Cooldown per candle: prevents multiple trades on the same candle (at cooldownTimeframe).
Minimum time interval cooldown (tradeIntervalSeconds).
Post-close cooldown after a position closes (postCloseCooldownSeconds).
Trailing Stops: Supports 4 modes — none, market structure based, ATR based, or hybrid.
Position Limits: Restricts max simultaneous positions by magic/symbol.
Optional Reverse Entries: Allows entry in opposite direction in countertrend if enabled.
Workflow Overview (inside OnTick):
Check post-close cooldown - skip trading if a position was closed recently.
Reset daily equity and losing streak counters if it's a new day.
Update losing streak based on closed trades for this EA and symbol.
Block new trades if losing streak limit or daily loss limit exceeded.
Apply floating risk cap—close any position exceeding max allowed floating loss.
Update trailing stops on open positions according to the selected mode.
Check position limit; skip trading if max reached.
Check trading time window.
Check cooldown filters: minimum seconds between trades and cooldown per candle.
Retrieve MAs, ATR, ADX values; skip if ADX below threshold.
Calculate SL and TP distances.
Detect break of structure based on price crossing the most recent swing high/low.
If conditions aligned, place buy or sell orders with appropriate SL, TP, lot size.
Update cooldown tracking timestamps on successful order.
Functionality or Code Recommendations:
Check OrderSend and PositionClose returns: In some OrderSend and PositionClose calls, results are not checked carefully. Consider handling retrial logic or error conditions better.
Handling Partial Fills: The EA assumes order fills succeed fully; if partial fills or re-quotes occur, some logic might need adaptations.
Trade copying: If you intend to use on multiple symbols, ensure the magic number is managed distinctly.
Indicator Handles Refresh: iMA, iATR, iADX handles are created in OnInit and not refreshed; this is standard but keep in mind for symbol or timeframe changes.
If you want help with something specific:
Explanation of a certain function or logic?
Debugging an issue, unexpected behavior?
Adding new features or modifying filters?
Optimizing parts of the code?
Feel free to ask!
How your EA determines trend: bool is_uptrend = (MA1 > MA2) && (MA2 > MA3);
bool is_downtrend = (MA1 < MA2) && (MA2 < MA3);
MA1 = EMA with period 50
MA2 = EMA with period 100
MA3 = EMA with period 200
Uptrend: The fastest MA (short-term, period 50) is above the medium-term MA (period 100), and the medium-term MA is above the long-term MA (period 200).
This means the price has upward momentum across multiple time scales.
Downtrend: The short-term MA is below the medium-term MA, and the medium-term is below the long-term MA, indicating downward momentum.
If neither condition is true, the trend is considered neutral or sideways, and the EA will usually refrain from opening new trades.
Why this method? Using multiple EMAs with increasing periods and checking their order is a common approach to define an overall market trend:
The short-term EMA reacts quickly to price changes.
The medium and long-term EMAs filter out noise and give the trend's direction over longer periods.
A stacked order (like MA1 > MA2 > MA3) shows alignment of momentum across timeframes, which is stronger trend confirmation.
Example:
If EMA50 = 1.2000, EMA100 = 1.1980, EMA200 = 1.1950 → Uptrend (1.2000 > 1.1980 > 1.1950)
If EMA50 = 1.1900, EMA100 = 1.1930, EMA200 = 1.1950 → Downtrend (1.1900 < 1.1930 < 1.1950)
Alternative/Extended methods: If you want to improve or modify trend determination, consider:
Using other indicators such as ADX (already in your EA, but only as filter for volatility/strength).
Price vs moving averages (e.g., price above all EMAs).
Using higher timeframe MAs.
Candle structure or swing highs/lows.
Combining Moving Average Convergence Divergence (MACD), RSI, etc.
If you'd like, I can help implement other trend filters or explain how to use your existing ADX filter in conjunction with these EMAs to better define trend strength.
Using Price vs. Moving Averages to determine the trend means looking at the current price (bid/ask or close price) and seeing whether it is above or below one or more moving averages. This method can be simpler or used alongside your EMA stacking condition for additional confirmation.
How to implement Price vs. MA trend check:
Define which moving average(s) you want to compare the price against (e.g., EMA50, or a combination).
Get the current price (usually the close of the last completed candle, or simply Bid or Ask price).
Compare price and MA:
If Price > MA: consider it an uptrend
If Price < MA: consider it a downtrend
Example code snippet using your current MAs and current Bid:
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); // or Ask, or last close price from candles
// already loaded MAs from buffers:
double MA1 = ma_buf1[0]; // 50 EMA
double MA2 = ma_buf2[0]; // 100 EMA
double MA3 = ma_buf3[0]; // 200 EMA
bool priceAboveAllMAs = (price > MA1) && (price > MA2) && (price > MA3);
bool priceBelowAllMAs = (price < MA1) && (price < MA2) && (price < MA3);
if(priceAboveAllMAs)
{
Print("Uptrend confirmed by price above all MAs");
// potentially allow buy trades
}
else if(priceBelowAllMAs)
{
Print("Downtrend confirmed by price below all MAs");
// potentially allow sell trades
}
else
{
Print("No clear trend by price vs MAs");
// avoid taking new trades or consider it sideways
}
Combining with your existing EMA stacking:
You can require both EMA order and price confirmation to strengthen your trend filter:
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3);
bool priceUptrend = (price > MA1) && (price > MA2) && (price > MA3);
bool priceDowntrend = (price < MA1) && (price < MA2) && (price < MA3);
bool isUptrend = emaUptrend && priceUptrend;
bool isDowntrend = emaDowntrend && priceDowntrend;
Pros and Cons:
Pros:
Filtering entries to trade only when price confirms trend direction can reduce bad entries.
Easy to implement and intuitive.
Cons:
Price often crosses MAs multiple times during consolidations → might cause no trades or choppy signals.
Depending on timeframe and volatility, this filter might be too strict or too loose.
Alternative — price close of last closed candle:
Instead of Bid/Ask, you can use the close price of the last fully closed candle, which can stabilize signals:
MqlRates rates[];
if(CopyRates(_Symbol, maTimeframe, 1, 1, rates) == 1)
{
double lastClose = rates[0].close;
bool priceUp = lastClose > MA1 && lastClose > MA2 && lastClose > MA3;
bool priceDown = lastClose < MA1 && lastClose < MA2 && lastClose < MA3;
// your logic here
}
If you want, I can help you integrate this price vs MA trend determination in your existing EA code!
It’s a classic EMA stacking method. If you want to add price vs MA checks to make trend identification stricter or different, you’d add an additional condition as discussed earlier.
If you want me to help you add price vs MA confirmation to this existing logic or replace it totally, just say so!
EMA 50 < EMA 100 < EMA 200 (stacked downtrend)
AND current price below EMA 100 to confirm downside momentum
Why use MA2 (the medium-term MA) for price comparison?
MA2 (EMA 100) is a balanced timeframe: not as fast as EMA 50 (which can be noisy), and not as slow as EMA 200 (which lags more).
Using price vs. MA2 helps check if price is holding above or below the “trend zone.”
Optional variant: use the price of the last closed candle MqlRates rates[];
if(CopyRates(_Symbol, maTimeframe, 1, 1, rates) == 1)
{
double lastClose = rates[0].close;
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (lastClose > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (lastClose < MA2);
// Now use emaUptrend and emaDowntrend in your trade logic
}
If you want, I can generate the code snippet integrated inside your EA’s OnTick() for better clarity. Just ask!
In your code snippet, locate this part inside OnTick(): double ma_buf1[], ma_buf2[], ma_buf3[];
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
double MA1 = ma_buf1[0];
double MA2 = ma_buf2[0];
double MA3 = ma_buf3[0];
Immediately after this, insert your updated trend logic: double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); // or SYMBOL_ASK or last candle close price
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
Then, replace your existing is_uptrend and is_downtrend usages with emaUptrend and emaDowntrend in your trading decision code below.
Example in context (pseudo-code snippet): // Fetch MAs
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
double MA1 = ma_buf1[0];
double MA2 = ma_buf2[0];
double MA3 = ma_buf3[0];
// Current price for trend confirmation
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// New trend determination
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
// Use emaUptrend and emaDowntrend in your entry logic:
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && emaUptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
// buy logic
}
else if(bid < lastSwingLow && emaDowntrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
// sell logic
}
}
else
{
// reverse entry logic ...
}
Insert new trend code immediately after MA values are retrieved .
Then replace the original is_uptrend and is_downtrend bools with your new combined emaUptrend and emaDowntrend conditions.
If you want, I can provide a full integrated snippet of OnTick() with these changes applied. Just ask!
Look for this part inside your OnTick() function — it’s roughly about 270 to 330 lines from the top (depending on editor and comments):
double ma_buf1[], ma_buf2[], ma_buf3[];
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf1) <= 0) return;
if(CopyBuffer(ma_handle2, 0, 1, 1, ma_buf2) <= 0) return;
if(CopyBuffer(ma_handle3, 0, 1, 1, ma_buf3) <= 0) return;
double MA1 = ma_buf1[0];
double MA2 = ma_buf2[0];
double MA3 = ma_buf3[0];
Insert your updated trend detection immediately after these lines . double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); // or Ask, or last candle close price
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
Then, further down where your code currently contains: bool is_uptrend = (MA1 > MA2) && (MA2 > MA3);
bool is_downtrend = (MA1 < MA2) && (MA2 < MA3);
You should replace those two lines with:
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
Summary of locations:
First place: Right after the CopyBuffer() calls for ma_handle, ma_handle2, and ma_handle3.
Second place: Replace the existing is_uptrend / is_downtrend assignments with your new combined emaUptrend / emaDowntrend.
If you want approximate line numbers:
If you want, you can open your .mq5 source code in MetaEditor, and:
Scroll to where those CopyBuffer() calls are.
Insert the new condition after that.
Replace the is_uptrend / is_downtrend declarations further down in the same function.
If you want me to prepare the exact modified snippet with these changes marked clearly, just say so!
Replace lines 862 and 863 with is_uptrend = emaUptrend; and is_downtrend = emaDowntrend;.
If you want, I can prepare a direct code snippet with line comments for you to easily paste it in place.
How to get the last closed candle's close price correctly Instead of straight using close, use CopyRates to get the last closed candle, then read the .close member.
Here is how to do it safely to avoid the error:
MqlRates rates[];
// Copy the most recent closed candle from the MA timeframe
if(CopyRates(_Symbol, maTimeframe, 1, 1, rates) == 1)
{
double lastClose = rates[0].close;
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (lastClose > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (lastClose < MA2);
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
}
else
{
// Failed to get candle data, fallback:
double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
}
Explanation:
We use CopyRates() to read 1 candle shifted by 1 to get the last fully closed candle (start_pos=1, count=1).
rates[0].close is the close price of that candle.
If it fails, fallback to current Bid price.
If you want a minimal version that avoids close error and uses Bid price only: double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool emaUptrend = (MA1 > MA2) && (MA2 > MA3) && (price > MA2);
bool emaDowntrend = (MA1 < MA2) && (MA2 < MA3) && (price < MA2);
bool is_uptrend = emaUptrend;
bool is_downtrend = emaDowntrend;
Summary of your fix:
Don’t use close directly.
Use either CopyRates() to get candle close price or use SymbolInfoDouble(_Symbol, SYMBOL_BID) for current price.
Adjust your OnTick() code accordingly.
If you want, I can give you the exact snippet to replace lines 860-870 with correct close price usage. Just ask!
If you want to add candle close price instead, you can use CopyRates as I showed earlier.
Feel free to ask if you want me to help integrate this fully into the code!
Copy first response
Not yet included in a published release.