i send you two codes to analize and tel me diferences
Assistant
Sure! Please go ahead and send me the two codes you'd like me to analyze and compare.
User
Assistant
Thanks for sharing the first code (AutoTradingMultiLookback.mq5). Please share the second code now, and then I will analyze both and provide you with the detailed differences between them.
//--- inputs
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_H1; // Timeframe to look back on
input int BaseLookbackCandles = 10; // Base number of candles (will adjust dynamically)
input double InpMultiplier = 7.0; // Max multiplier (integer part used, >=1)
input bool IncludeCurrentCandle = false; // Include current forming candle in calculations
input double MinimalDistancePoints = 20; // Minimal distance between lines, in points
// Trading inputs
input double RiskPercent = 2.0; // Risk percentage of balance per trade
// Default SL/TP pips used if ATR based SL is unavailable
input int DefaultStopLossPips = 50; // Default Stop Loss in pips (0 = no SL)
input int DefaultTakeProfitPips = 100; // Default Take Profit in pips (0 = no TP)
input int MaxOpenTrades = 3; // Maximum open trades at once
input bool EnableBuyTrades = true; // Enable buy trades
input bool EnableSellTrades = true; // Enable sell trades
// Trade hours (server time)
input int TradeStartHour = 7; // Trading session start hour (inclusive)
input int TradeEndHour = 20; // Trading session end hour (exclusive)
// Optional color inputs
input color ColorHighLines = clrRed;
input color ColorLowLines = clrBlue;
int DynamicLookbackCandles = 10;
int TradeOnlyMultiplier = 3;
int atr_handle = INVALID_HANDLE;
int sma_handle_short = INVALID_HANDLE;
int sma_handle_long = INVALID_HANDLE;
// Arrays to store line levels and their states
struct LineData
{
double price;
int multiplier;
bool crossedAbove; // For high lines: price crossed above
bool crossedBelow; // For low lines: price crossed below
};
LineData highLines[];
LineData lowLines[];
//+------------------------------------------------------------------+
//| Expert initialization |
//+------------------------------------------------------------------+
int OnInit()
{
if(BaseLookbackCandles < 1)
{
Print("Error: BaseLookbackCandles must be >= 1");
return(INIT_FAILED);
}
//+------------------------------------------------------------------+
//| Get SMA value from handle |
//+------------------------------------------------------------------+
double GetSMA(int handle)
{
if(handle == INVALID_HANDLE) return 0.0;
double filteredHighsPrices[];
int filteredHighsMultipliers[];
double filteredLowsPrices[];
int filteredLowsMultipliers[];
for(int m = 1; m <= maxMult; m++)
{
int barsToLookBack = DynamicLookbackCandles * m;
code
MqlRates rates[];
int copied = CopyRates(_Symbol, InpTimeframe, startPos, barsToLookBack, rates);
if(copied <= 0)
{
PrintFormat("CopyRates failed for %d bars on timeframe %s", barsToLookBack, EnumToString(InpTimeframe));
continue;
}
double highest = -DBL_MAX;
double lowest = DBL_MAX;
for(int i = 0; i < copied; i++)
{
if(rates[i].high > highest) highest = rates[i].high;
if(rates[i].low < lowest) lowest = rates[i].low;
}
ProcessHighLine(highest, m, filteredHighsPrices, filteredHighsMultipliers);
ProcessLowLine(lowest, m, filteredLowsPrices, filteredLowsMultipliers);
}
}
//+------------------------------------------------------------------+
//| Process high line |
//+------------------------------------------------------------------+
void ProcessHighLine(double highest, int mult, double &filteredHighsPrices[], int &filteredHighsMultipliers[])
{
bool foundClose = false;
int indexClose = -1;
//+------------------------------------------------------------------+
//| Process low line |
//+------------------------------------------------------------------+
void ProcessLowLine(double lowest, int mult, double &filteredLowsPrices[], int &filteredLowsMultipliers[])
{
bool foundClose = false;
int indexClose = -1;
//+------------------------------------------------------------------+
//| Get count of open trades |
//+------------------------------------------------------------------+
int GetOpenTradesCount()
{
int count = 0;
int totalPositions = PositionsTotal();
for(int i = 0; i < totalPositions; i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
//--- inputs
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_H1; // Timeframe to look back on
input int InpLookbackCandles = 10; // Base number of candles (>=1)
input double InpMultiplier = 7.0; // Max multiplier (integer part used, >=1)
input bool IncludeCurrentCandle = false; // Include current forming candle in calculations
input double MinimalDistancePoints = 20; // Minimal distance between lines, in points
// Trading inputs
input double RiskPercent = 2.0; // Risk percentage of balance per trade
input int StopLossPips = 50; // Stop Loss in pips (0 = no SL)
input int TakeProfitPips = 100; // Take Profit in pips (0 = no TP)
input int MaxOpenTrades = 3; // Maximum open trades at once
input bool EnableBuyTrades = true; // Enable buy trades (price cross low and close above)
input bool EnableSellTrades = true; // Enable sell trades (price cross high and close below)
input int MinMultiplier = 1; // Minimum multiplier to trade
input int MaxMultiplier = 7; // Maximum multiplier to trade
// Optional color inputs
input color ColorHighLines = clrRed;
input color ColorLowLines = clrBlue;
// Arrays to store line levels and their states
struct LineData
{
double price;
int multiplier;
bool crossedAbove; // For high lines: price crossed above
bool crossedBelow; // For low lines: price crossed below
};
LineData highLines[];
LineData lowLines[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
if(InpLookbackCandles < 1)
{
Print("Error: InpLookbackCandles must be >= 1");
return(INIT_FAILED);
}
Print("AutoTradingMultiLookback EA initialized");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ClearLines();
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Get time of the latest completed bar on the input timeframe
datetime currentBarTime = iTime(_Symbol, InpTimeframe, 0);
if(currentBarTime != lastBarTime)
{
lastBarTime = currentBarTime;
UpdateLines();
}
// Check for trading signals on every tick
CheckTradingSignals();
}
//+------------------------------------------------------------------+
//| Core function to draw or update all lines |
//+------------------------------------------------------------------+
void UpdateLines()
{
int maxMult = (int)MathFloor(multiplier);
if(maxMult < 1) maxMult = 1;
// Temporary arrays for filtering
double filteredHighsPrices[];
int filteredHighsMultipliers[];
double filteredLowsPrices[];
int filteredLowsMultipliers[];
for(int m = 1; m <= maxMult; m++)
{
int barsToLookBack = InpLookbackCandles * m;
code
MqlRates rates[];
int copied = CopyRates(_Symbol, InpTimeframe, startPos, barsToLookBack, rates);
if(copied <= 0)
{
PrintFormat("CopyRates failed for %d bars on timeframe %s", barsToLookBack, EnumToString(InpTimeframe));
continue;
}
double highest = -DBL_MAX;
double lowest = DBL_MAX;
for(int i = 0; i < copied; i++)
{
if(rates[i].high > highest) highest = rates[i].high;
if(rates[i].low < lowest) lowest = rates[i].low;
}
// Filter and add high lines
ProcessHighLine(highest, m, filteredHighsPrices, filteredHighsMultipliers);
// Filter and add low lines
ProcessLowLine(lowest, m, filteredLowsPrices, filteredLowsMultipliers);
}
}
//+------------------------------------------------------------------+
//| Process high line with filtering |
//+------------------------------------------------------------------+
void ProcessHighLine(double highest, int mult, double &filteredHighsPrices[], int &filteredHighsMultipliers[])
{
bool highCloseFound = false;
int highCloseIndex = -1;
}
else if(highest > filteredHighsPrices[highCloseIndex])
{
// Replace with higher value
filteredHighsPrices[highCloseIndex] = highest;
int replacedMultiplier = filteredHighsMultipliers[highCloseIndex];
string replacedLineName = PREFIX_HIGH + IntegerToString(replacedMultiplier);
code
// Update in trading array
for(int k = 0; k < ArraySize(highLines); k++)
{
if(highLines[k].multiplier == replacedMultiplier)
{
highLines[k].price = highest;
highLines[k].crossedAbove = false;
break;
}
}
DrawOrUpdateLine(replacedLineName, highest, ColorHighLines);
}
}
//+------------------------------------------------------------------+
//| Process low line with filtering |
//+------------------------------------------------------------------+
void ProcessLowLine(double lowest, int mult, double &filteredLowsPrices[], int &filteredLowsMultipliers[])
{
bool lowCloseFound = false;
int lowCloseIndex = -1;
//+------------------------------------------------------------------+
//| Get count of open trades |
//+------------------------------------------------------------------+
int GetOpenTradesCount()
{
int count = 0;
int totalPositions = PositionsTotal();
for(int i = 0; i < totalPositions; i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue; // safety
//+------------------------------------------------------------------+
//| Clear lines with defined prefixes |
//+------------------------------------------------------------------+
void ClearLines()
{
int total = ObjectsTotal(0);
for(int i = total - 1; i >= 0; i--)
{
string name = ObjectName(0, i);
if(StringFind(name, PREFIX_HIGH) == 0 || StringFind(name, PREFIX_LOW) == 0)
ObjectDelete(0, name);
}
}
//+------------------------------------------------------------------+
Thanks for providing both codes! Both are MQL5 Expert Advisors named AutoTradingMultiLookback.mq5, but different versions, with version 3.03 (first) and 2.01 (second). Below is a detailed analysis of the key differences between them:
1. Version and Metadata
Aspect
Version 3.03 (First)
Version 2.01 (Second)
#property version
"3.03"
"2.01"
Copyright comment
"Enhanced Trading System"
"Enhanced Trading System"
Some comments/styles
More descriptive in v3
More minimalistic
2. Inputs and Parameters
Parameter
Version 3.03
Version 2.01
Lookback candles input
BaseLookbackCandles, int, dynamic adjustment via ATR
InpLookbackCandles, int, static
Multiplier
InpMultiplier, double, dynamic between 1 and max integer
InpMultiplier, double, static
Minimal distance points
MinimalDistancePoints
Same
RiskPercent
Same (2.0 default)
Same
StopLoss/TakeProfit
Adaptive SL & TP based on ATR (functions GetAdaptiveStopLossPips() and GetAdaptiveTakeProfitPips())
Static SL/TP by user input (StopLossPips, TakeProfitPips)
Max open trades
Same (3 default)
Same
Enable Buy/Sell trades
Same
Same
Trade Session Hours
Added: TradeStartHour, TradeEndHour to restrict trading to certain hours
Not present
Multiplier min/max for trade
TradeOnlyMultiplier dynamic, adjusted in AdjustParametersByVolatility()
Manual MinMultiplier and MaxMultiplier to filter lines for trades
Colors for lines
Same: ColorHighLines, ColorLowLines
Same
Summary:
Version 3.03 adds volatility-based dynamic adjustments of lookback candles and multipliers, adaptive SL/TP based on ATR, and trading session time control. The older v2.01 uses fixed lookback and SL/TP values and multiplier range filter.
3. Volatility & Indicator Usage
Aspect
v3.03
v2.01
ATR indicator
Creates ATR handle (atr_handle = iATR(...)), used for adaptive SL/TP and volatility-based parameter adjustment
No ATR usage
SMA indicators (short and long)
Created (sma_handle_short, sma_handle_long) and used for trend filtering functions IsTrendingUp(), IsTrendingDown()
No SMA usage or trend filtering
Dynamic Adjustments
Adjusts lookback candles and multiplier dynamically based on ATR thresholds
Parameters fixed
Summary:
v3.03 incorporates volatility and trend filtering via technical indicators that the v2.01 version lacks.
4. Trade Session Time Filter
v3.03: Uses TradeStartHour and TradeEndHour inputs and checks in OnTick() if current time is within trade hours before proceeding.
v2.01: No time filtering; trades can open any time.
5. Line Management and Multipliers
Aspect
v3.03
v2.01
Line arrays (highLines[], lowLines[])
Same, store price, multiplier, crossing state
Same
Multipliers for lines
Based on multiplier, integer part of InpMultiplier, dynamically adjusted in AdjustParametersByVolatility()
Multiplier limited by user input MinMultiplier and MaxMultiplier
Filtering of lines close in price
Checks minimal distance (MinimalDistancePoints) to avoid close lines
Same filtering logic
Line naming
Uses PREFIX_HIGH and PREFIX_LOW with multiplier suffix
Same
Summary:
Both versions manage lines similarly but v3.03 controls which multiplier lines are traded via a dynamic TradeOnlyMultiplier, while v2.01 uses user inputs MinMultiplier and MaxMultiplier for filtering.
6. Trading Logic and Conditions
Aspect
v3.03
v2.01
Trend Filtering
Trades only if IsTrendingUp() or IsTrendingDown() (SMA cross)
No trend filter; trades occur regardless of SMA
Crossing flags
Same mechanism — sets flags on crossing line and triggers trades upon crossing back or candle close confirmation
Same mechanism
Trade volumes (lots)
Calculated dynamically based on adaptive SL pips and ATR
Calculated based on fixed SL pips
Trade open conditions
Uses current bid/ask and previous candle close to detect confirmations
Same concept
Max open trades limit
Same
Same
7. Stop Loss and Take Profit Management
v3.03:
GetAdaptiveStopLossPips() returns SL based on ATR (4 x ATR), capped between 10 and 150 pips.
GetAdaptiveTakeProfitPips() defines TP as 2.5x SL, capped between 20 and 400 pips.
This allows SL/TP to adjust with volatility.
v2.01: Uses constant input StopLossPips and TakeProfitPips, no dynamic adjustment.
8. Lot Size Calculation
Aspect
v3.03
v2.01
Uses SL pips for risk calc
Uses adaptive SL pips in calculating lot size
Uses fixed SL pips for lot sizing
If no SL pips
Fallback fixed risk (50 pips equivalent)
Same fallback but with fixed SL inputs
9. Additional Functional Differences
v3.03:
Includes functions to create and release indicator handles properly (OnInit(), OnDeinit()).
Prints more detailed logs related to volatility adjustments.
Uses TimeCurrent() and MqlDateTime for session time checks.
v2.01:
Simpler initialization, no indicators created or released.
No time filtering.
10. Summary of Major Differences
Feature
Version 3.03 (Newer)
Version 2.01 (Older)
Lookback candles
Dynamically adjusted by ATR volatility
Static, user defined
SL/TP
Adaptive (4x ATR) and (2.5x SL)
Fixed (user inputs)
Trend Filter (SMA)
Yes (10 and 50 SMA)
No
Trading Hours Filter
Yes, restrict trades to specified hours
No
Multiplier filtering
Dynamic multiplier (TradeOnlyMultiplier)
Fixed min/max multiplier filters
Indicator Handles
ATR and SMA handles created/released
None
Trading logic enhanced
Uses volatility and trend filters
Basic price crossing logic
More logging and error checks
Yes
Basic
In short:
The v3.03 is an enhanced and more sophisticated EA that adapts its strategy based on market volatility (ATR), filters trades by trend (SMA cross), adjusts SL/TP dynamically, and restricts trading to specific hours. The v2.01 is a simpler, static version with fixed parameters and no indicator-based filtering.
If you want automated risk/volatility adjustments and trend filtering, v3.03 is better. If you prefer a simpler baseline EA with fixed parameters, v2.01 suffices.
If you'd like, I can also help summarize specific code parts or provide suggestions on how to merge features between them. Let me know!
Certainly! Here is a detailed explanation of how AutoTradingMultiLookback.mq5 version 3.03 works, covering its main components and overall trading logic:
Overview of AutoTradingMultiLookback v3.03
This Expert Advisor (EA) is designed to place buy and sell trades based on dynamic support/resistance levels calculated from multiple lookback intervals. It adapts key parameters dynamically according to market volatility (measured by ATR), incorporates trend filtering using moving averages (SMA), and restricts trading to defined hours. It also manages trade risk by calculating position sizes based on account balance and adaptive stop loss.
Every time a new bar forms (OnTick() detects new bar), the EA calculates the current ATR value.
Using ATR, it classifies volatility into three ranges:
Volatility Level
ATR Threshold
Lookback Candles Adjustment
Multiplier Adjustment
Low Volatility
ATR < 0.0005
Reduce lookback candles to half (minimum 3)
Multiplier forced to 1
High Volatility
ATR > 0.0012
Double the lookback candles
Multiplier capped at 5 or less
Normal Volatility
Between thresholds
Use base lookback & multiplier adjusted to max 3
These adjustments make the EA more sensitive in low volatility (smaller lookbacks) and more conservative in high volatility (larger lookbacks).
3. Drawing Support and Resistance Lines (UpdateLines())
For each multiplier from 1 up to the integer part of the maximum multiplier:
It calculates the lookback period as DynamicLookbackCandles * multiplier.
Copies price data (CopyRates) for that lookback range.
Finds the highest high and lowest low within those bars.
It avoids drawing lines that are too close together (distance less than MinimalDistancePoints points).
High price levels become resistance lines with prefix "AutoTrade_High_" + multiplier.
Low price levels become support lines with prefix "AutoTrade_Low_" + multiplier.
These lines are plotted as dotted horizontal lines on the chart.
4. Trend Direction Filtering (IsTrendingUp(), IsTrendingDown())
Calculates the short-term (10-period) and long-term (50-period) SMA values using indicator buffers.
Defines trend:
Uptrend: Short SMA > Long SMA
Downtrend: Short SMA < Long SMA
EA only considers buy trades during uptrends and sell trades during downtrends.
5. Trading Time Filter
EA checks current server time.
Only trades if current hour is within the defined trading session (e.g., 7:00 to 20:00).
Skips trading outside those hours.
6. Entry Signal Logic (CheckTradingSignals())
On every tick, EA performs the following:
For Buy Trades:
EA loops through lowLines arrays (support lines) with multiplier equal to the dynamic trade multiplier set by volatility.
It tracks whether price has crossed below the support line (crossedBelow flag).
Signal Steps:
Detects if current ask price crosses below a support line → sets crossedBelow = true.
When price crosses back above that line or the previous candle's close is above the line and crossedBelow == true, it opens a Buy trade (if max trades not exceeded).
Resets crossedBelow flag after entering trade.
For Sell Trades:
Similarly, loops through highLines arrays (resistance lines) with the dynamic multiplier.
Tracks if price has crossed above the resistance line (crossedAbove flag).
Signal Steps:
Detects if current bid price crosses above a resistance line → sets crossedAbove = true.
When price crosses back below that line or previous candle close is below the line and crossedAbove == true, it opens a Sell trade (if max trades not exceeded).
Adaptive stop loss pips derived from ATR (typically 4 x ATR converted to pips)
Price and tick values of the symbol
Stop Loss (SL) and Take Profit (TP) levels are set adaptively:
SL = Entry price ± adaptive SL pips
TP = Entry price ± adaptive SL * 2.5 (take profit is 2.5 times larger than SL)
EA opens market orders with the calculated parameters and adds a comment like "BUY M3 at 1.12345" indicating the multiplier and price.
8. Stop Loss and Take Profit Calculation
GetAdaptiveStopLossPips():
Uses the ATR value and converts it into pips.
Multiplies by 4 for safe SL distance.
Ensures a minimum of 10 pips and a max of 150 pips.
GetAdaptiveTakeProfitPips():
Takes SL pips value and multiplies by 2.5 to define TP pips.
Clamps TP between 20 and 400 pips.
These adaptive stop and target levels dynamically follow market volatility.
9. Utility Functions
CalculateLotSize():
Determines lot size so that the risk defined by stop loss level matches the configured risk percentage of the account balance.
Uses symbol tick size and value for precise position sizing.
Normalizes lot size to allowed steps and limits.
ClearLines():
Deletes all previously drawn lines on chart before updating.
DrawOrUpdateLine():
Creates or updates horizontal lines with given color, width, and style.
GetOpenTradesCount():
Counts currently open trades for current symbol and EA magic number to respect max allowed open trades limit.
Summary: What Makes v3.03 Distinct?
Dynamic adaptation: The key feature is that the EA adapts its lookback periods, line multipliers, stop loss, and take profit sizes automatically based on market volatility (ATR).
Trend filtering: It only trades in the direction of the trend defined by SMA crossover to avoid counter-trend trades.
Session window: Trades only during user-defined trading hours, avoiding unwanted trading during less favorable times.
Multi-lookback approach: It considers multiple lookback periods by multiplying the base number of candles by multipliers, creating several support or resistance lines on chart.
Price crossing behavior: Uses crossing flags that trigger trades only after price crosses a line and then returns back, filtering noise and false signals.
Risk management: Dynamically calculates lot sizes and stop losses to control risk according to current volatility and account balance.
If you'd like, I can help you with examples of each step or how to modify specific components!