Hello, I have learned to implement my code...
I must finish inserting the average into the RSI, and then change the entry conditions to the market.
// Expert Advisor (EA) in MQL4 based on the provided parameters, now with Parabolic SAR filter, ADX filter, MACD filter, ATR volatility filter, Multi-Timeframe Trend filter, Heiken Ashi filter, Volume filter, and Debug Print Statements for Diagnostics
//--- Inputs based on provided image
input bool Monday = true;
input bool Tuesday = true;
input bool Wednesday = true;
input bool Thursday = true;
input bool Friday = true;
input bool Saturday = false;
input bool Sunday = false;
input bool TradeMonthEnd = false;
input int MonthEndOffset = 1;
input bool TradeFirstDayOffset = false;
input double DayOffset = 0.0;
input double GMTOffset = 0.0;
input bool TradeNFP = false;
input bool TradeMondayAfterNFP = false;
input bool TradeADP = false;
input bool Trading24h = false;
input int HoursFrom = 8;
input int HoursTo = 19; // Optimized trading hours to focus on active market times
input bool Session_Filter = false;
input bool Session_Filter1 = false;
input double SF1Hour_On = 5.0;
input double SF1MinuteOn = 0.0;
input double SF1Hour_Off = 9.0;
input double SF1MinuteOff = 0.0;
input bool AvoidNews = true;
input bool High_Impact = true;
input int MinsUntilNextHighNews = 90;
input int MinsSincePrevHighNews = 90;
input bool Medium_Impact = true;
input int MinsUntilNextMediumNews = 60;
input int MinsSincePrevMediumNews = 60;
input bool Low_Impact = false;
input int MinsUntilNextLowNews = 30;
input int MinsSincePrevLowNews = 30;
input bool USD = true;
input bool EUR = true;
input bool GBP = true;
input bool JPY = false;
input bool AUD = false;
input bool CAD = false;
input bool CHF = false;
input bool NZD = false;
input int MA_RSI_Period = 14; // Periodo della Media Mobile sulla RSI
input ENUM_MA_METHOD MA_RSI_Method = MODE_SMA; // Metodo della Media Mobile (SMA, EMA, etc.)
input int RSI_Period = 14; // Periodo RSI
input int Applied_Price = PRICE_CLOSE; // Prezzo applicato per RSI
input double MA_RSI_Level = 50.0; // Livello della Media Mobile sulla RSI per Buy/Sell
input bool UseMARSI = true; // On/Off filtro Media Mobile su RSI
// Main order settings
input double Lots = 0.1;
input double MicroLot = 0.01;
input double LotExponent = 1.5;
input int lotdecimal = 2;
input double PipStep = 50.0; // Adjusted PipStep for H1 timeframe
input double MaxLots = 10.0;
input bool ReverseOrder = false;
input double SlipPage = 3.0;
input double RiskInPercent = 2.0;
input bool AutoLotSize = true;
input bool UseTimeStop = false;
input bool StopHours = true;
input bool StopMinutes = true;
input double TakeProfit = 100.0; // Adjusted TakeProfit for H1 timeframe
input double StopLossMultiplier = 2.0; // Adjusted input for controlling stop loss based on ATR or another value
input bool UseEquityStop = true;
input double TotalEquityRisk = 5.0; // Reduced risk percentage for H1 timeframe
input bool UseTrailingStop = true;
input double TrailStart = 50.0; // Adjusted trailing start for H1 timeframe
input double TrailStop = 25.0; // Adjusted trailing stop for H1 timeframe
input double slip = 3.0;
// Fibo-settings
input int Max_Trades_Hilo = 10;
input int MagicNumber_Hilo = 10278;
// RSI-settings
input int g_magic_176_15 = 22324;
input int MaxTrades_15 = 10;
input double RSI_BuyLowerLevel = 60.0; // Adjusted RSI Buy Lower Level for H1
input double RSI_BuyUpperLevel = 70.0; // Adjusted RSI Buy Upper Level for H1
input double RSI_SellLowerLevel = 30.0; // Adjusted RSI Sell Lower Level for H1
input double RSI_SellUpperLevel = 40.0; // Adjusted RSI Sell Upper Level for H1
input bool UseRSI = true; // On/Off RSI filter
// Dayrange-settings
input int g_magic_176_16 = 23794;
input int MaxTrades_16 = 10;
input double DayRangeThreshold = 50.0; // Range giornaliero in pips oltre il quale si verifica un segnale
input int DayRangePeriod = 14; // Periodo per calcolare il range giornaliero medio
// News filter
input bool UseNewsFilter = true;
// Moving Average settings
input int MA_Period = 50; // Adjusted MA period for H1 timeframe
input int MA_Shift = 0;
input ENUM_MA_METHOD MA_Type = MODE_SMA; // Added option for different MA types: Simple, Exponential, Smoothed, Linear Weighted
input int MA_Price = PRICE_CLOSE;
input bool UseMA = true; // On/Off MA filter
// Second Moving Average settings
input int MA2_Period = 100; // Adjusted MA2 period for H1 timeframe
input int MA2_Shift = 0;
input ENUM_MA_METHOD MA2_Type = MODE_SMA; // Added option for different MA types: Simple, Exponential, Smoothed, Linear Weighted
input int MA2_Price = PRICE_CLOSE;
input bool UseMA2 = true; // On/Off Second MA filter
// Bollinger Bands settings
input int BB_Period = 20;
input double BB_Deviation = 2.0;
input bool UseBB = true; // On/Off Bollinger Bands filter
// ATR settings
input int ATR_Period = 14; // Adjusted ATR period for H1 timeframe
input double ATR_VolatilityThreshold = 0.01; // Adjusted ATR volatility threshold for H1 timeframe
input bool UseATRVolatilityFilter = true; // On/Off ATR Volatility filter
// Ichimoku settings
input int Ichimoku_Tenkan = 9;
input int Ichimoku_Kijun = 26;
input int Ichimoku_Senkou = 52;
input bool UseIchimoku = true; // On/Off Ichimoku filter
// Parabolic SAR settings
input double PSAR_Step = 0.02;
input double PSAR_Maximum = 0.2;
input bool UseParabolicSAR = true; // On/Off Parabolic SAR filter
// ADX settings
input int ADX_Period = 14; // Adjusted ADX period for H1 timeframe
input double ADX_Level = 25.0; // Adjusted ADX level for stronger trend detection on H1
input double ADX_DPlusThreshold = 20.0; // Lowered threshold for more sensitivity in trend detection
input double ADX_DMinusThreshold = 20.0; // Lowered threshold for more sensitivity in trend detection
input bool UseADX = true; // On/Off ADX filter
// MACD settings
input int MACD_Fast = 9;
input int MACD_Slow = 21;
input int MACD_Signal = 9;
input bool UseMACD = false; // On/Off MACD filter
// Heiken Ashi settings
input bool UseHeikenAshi = true; // On/Off Heiken Ashi filter
// Multi-Timeframe Trend settings
input int HigherTimeframe = PERIOD_H4; // Timeframe for higher trend confirmation
input bool UseMultiTimeframeTrend = true; // On/Off Multi-Timeframe Trend filter
// Volume settings
input bool UseVolumeFilter = true; // On/Off Volume filter
input double MinVolume = 100.0; // Adjusted minimum volume for H1 timeframe
// Maximum number of allowed open trades
input int MaxOpenTrades = 1;
// Minimum distance between new orders (in points)
input double MinOrderDistance = 100;
// Break Even and Dynamic Take Profit settings
input bool UseBreakEven = true;
input double BreakEvenLevel = 10.0; // Move stop to break-even after this many pips in profit
input bool UseDynamicTP = true;
input double DynamicTPMultiplier = 1.5; // Multiplier to calculate dynamic take profit based on ATR
// EA Logic Placeholder
void OnTick() {
// Add trading logic based on these inputs
// For example, check trading time, open orders, apply filters, etc.
//--- Example: Check the trading time based on HoursFrom and HoursTo
if (!IsTradingDay() || !IsTradingHour()) {
return; // Exit if today is not a trading day or it's outside trading hours
}
// Check if we should avoid trading due to news
if (AvoidNews && !CheckNews()) {
Print("Avoiding trade due to unfavorable news conditions");
return; // Exit if news conditions are not favorable
}
// Check if the number of open trades exceeds the maximum allowed
if (CountOpenTrades() >= MaxOpenTrades) {
Print("Maximum number of open trades reached");
return; // Exit if the maximum number of open trades is reached
}
// Calculate lot size based on risk settings
double lotSize = Lots;
if (AutoLotSize) {
double accountBalance = AccountBalance();
lotSize = NormalizeDouble((accountBalance * RiskInPercent / 100) / 1000, lotdecimal);
if (lotSize > MaxLots) lotSize = MaxLots;
}
// Check distance from the last order
if (!IsEnoughDistanceFromLastOrder()) {
Print("Minimum distance condition not met for new order");
return; // Exit if the minimum distance condition is not met
}
// Placeholder for trade entry logic
if (MarketCondition() && CheckDayRange()) {
Print("Market conditions met for a new trade");
// Open a new order
double tp = TakeProfit * Point;
double sl = CalculateStopLoss(); // Calculate StopLoss based on ATR or other strategies
if (UseDynamicTP) {
tp = CalculateDynamicTP(); // Calculate dynamic TP based on ATR
}
int ticket = -1;
if (ShouldBuy()) {
ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, SlipPage, Ask - sl, Ask + tp, "Buy Order", MagicNumber_Hilo, 0, Blue);
} else if (ShouldSell()) {
ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, SlipPage, Bid + sl, Bid - tp, "Sell Order", MagicNumber_Hilo, 0, Red);
}
if (ticket < 0) {
Print("OrderSend failed with error #", GetLastError());
} else {
Print("Order sent successfully, ticket #", ticket);
}
}
// Manage break-even stop if applicable
if (UseBreakEven) {
ManageBreakEven();
}
// Manage trailing stop if applicable
if (UseTrailingStop) {
ManageTrailingStop();
}
}
// Function to determine if the market conditions are favorable for trading
bool MarketCondition() {
Print("Checking market conditions");
return (ShouldBuy() || ShouldSell());
}
// Determine if a Buy condition is met
bool ShouldBuy() {
// Check for candle direction to be bullish
if (Close[1] <= Open[1]) {
Print("Previous candle is not bullish");
return false; // Only trade if previous candle is bullish
}
double rsiValue = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);
double maValue = iMA(Symbol(), 0, MA_Period, MA_Shift, MA_Type, MA_Price, 0);
double ma2Value = iMA(Symbol(), 0, MA2_Period, MA2_Shift, MA2_Type, MA2_Price, 0);
double bbMiddle = iBands(Symbol(), 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_MAIN, 0);
double kijunSen = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 1, 0); // Usato indice 1 per la Kijun Sen
double senkouSpanA = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 2, 0); // Senkou Span A
double psarValue = iSAR(Symbol(), 0, PSAR_Step, PSAR_Maximum, 0);
double adxValue = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MAIN, 0);
double diPlus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_PLUSDI, 0);
double diMinus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MINUSDI, 0);
double macdMain = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_MAIN, 0);
double macdSignal = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_SIGNAL, 0);
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double haClose = iCustom(Symbol(), 0, "Heiken Ashi", 3, 0); // Heiken Ashi close value
double volume = iVolume(Symbol(), 0, 0);
double maHigherTimeframe = iMA(Symbol(), HigherTimeframe, MA_Period, MA_Shift, MA_Type, MA_Price, 0); // Higher timeframe MA
if (UseRSI && !(rsiValue > RSI_BuyLowerLevel && rsiValue < RSI_BuyUpperLevel)) {
Print("RSI condition not met, RSI value:", rsiValue);
return false;
}
if (UseMA && !(Close[1] > maValue)) {
Print("MA condition not met, Close:", Close[1], " MA:", maValue);
return false;
}
if (UseMA2 && !(Close[1] > ma2Value)) {
Print("Second MA condition not met, Close:", Close[1], " MA2:", ma2Value);
return false;
}
if (UseBB && !(Close[1] > bbMiddle)) {
Print("Bollinger Bands condition not met, Close:", Close[1], " BB Middle:", bbMiddle);
return false;
}
if (UseIchimoku && !(Close[1] > kijunSen && Close[1] > senkouSpanA)) {
Print("Ichimoku condition not met, Close:", Close[1], " Kijun Sen:", kijunSen, " Senkou Span A:", senkouSpanA);
return false;
}
if (UseParabolicSAR && !(psarValue < Close[1])) {
Print("Parabolic SAR condition not met, SAR:", psarValue, " Close:", Close[1]);
return false;
}
if (UseADX && (adxValue < ADX_Level || diPlus < ADX_DPlusThreshold)) {
Print("ADX or Directional Index condition not met, ADX value:", adxValue, " +DI:", diPlus, " Threshold:", ADX_DPlusThreshold);
return false; // Only trade if ADX indicates a strong trend and +DI is greater than the threshold
}
if (UseMACD && !(macdMain > macdSignal)) {
Print("MACD condition not met, MACD Main:", macdMain, " MACD Signal:", macdSignal);
return false; // Only trade if MACD Main line is above the Signal line
}
if (UseATRVolatilityFilter && atrValue < ATR_VolatilityThreshold) {
Print("ATR Volatility condition not met, ATR value:", atrValue);
return false; // Avoid trading during low volatility
}
if (UseHeikenAshi && haClose <= Close[1]) {
Print("Heiken Ashi condition not met, HA Close:", haClose, " Close:", Close[1]);
return false; // Only trade if Heiken Ashi close indicates bullish trend
}
if (UseVolumeFilter && volume < MinVolume) {
Print("Volume condition not met, Volume:", volume);
return false; // Avoid trading if market volume is low
}
if (UseMultiTimeframeTrend && !(Close[1] > maHigherTimeframe)) {
Print("Multi-Timeframe Trend condition not met, Close:", Close[1], " Higher Timeframe MA:", maHigherTimeframe);
return false; // Only trade if the trend is confirmed on a higher timeframe
}
return true;
}
// Determine if a Sell condition is met
bool ShouldSell() {
// Check for candle direction to be bearish
if (Close[1] >= Open[1]) {
Print("Previous candle is not bearish");
return false; // Only trade if previous candle is bearish
}
double rsiValue = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);
double maValue = iMA(Symbol(), 0, MA_Period, MA_Shift, MA_Type, MA_Price, 0);
double ma2Value = iMA(Symbol(), 0, MA2_Period, MA2_Shift, MA2_Type, MA2_Price, 0);
double bbMiddle = iBands(Symbol(), 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_MAIN, 0);
double kijunSen = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 1, 0); // Usato indice 1 per la Kijun Sen
double senkouSpanA = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 2, 0); // Senkou Span A
double psarValue = iSAR(Symbol(), 0, PSAR_Step, PSAR_Maximum, 0);
double adxValue = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MAIN, 0);
double diPlus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_PLUSDI, 0);
double diMinus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MINUSDI, 0);
double macdMain = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_MAIN, 0);
double macdSignal = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_SIGNAL, 0);
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double haClose = iCustom(Symbol(), 0, "Heiken Ashi", 3, 0); // Heiken Ashi close value
double volume = iVolume(Symbol(), 0, 0);
double maHigherTimeframe = iMA(Symbol(), HigherTimeframe, MA_Period, MA_Shift, MA_Type, MA_Price, 0); // Higher timeframe MA
if (UseRSI && !(rsiValue < RSI_SellUpperLevel && rsiValue > RSI_SellLowerLevel)) {
Print("RSI condition not met, RSI value:", rsiValue);
return false;
}
if (UseMA && !(Close[1] < maValue)) {
Print("MA condition not met, Close:", Close[1], " MA:", maValue);
return false;
}
if (UseMA2 && !(Close[1] < ma2Value)) {
Print("Second MA condition not met, Close:", Close[1], " MA2:", ma2Value);
return false;
}
if (UseBB && !(Close[1] < bbMiddle)) {
Print("Bollinger Bands condition not met, Close:", Close[1], " BB Middle:", bbMiddle);
return false;
}
if (UseIchimoku && !(Close[1] < kijunSen && Close[1] < senkouSpanA)) {
Print("Ichimoku condition not met, Close:", Close[1], " Kijun Sen:", kijunSen, " Senkou Span A:", senkouSpanA);
return false;
}
if (UseParabolicSAR && !(psarValue > Close[1])) {
Print("Parabolic SAR condition not met, SAR:", psarValue, " Close:", Close[1]);
return false;
}
if (UseADX && (adxValue < ADX_Level || diMinus < ADX_DMinusThreshold)) {
Print("ADX or Directional Index condition not met, ADX value:", adxValue, " -DI:", diMinus, " Threshold:", ADX_DMinusThreshold);
return false; // Only trade if ADX indicates a strong trend and -DI is greater than the threshold
}
if (UseMACD && !(macdMain < macdSignal)) {
Print("MACD condition not met, MACD Main:", macdMain, " MACD Signal:", macdSignal);
return false; // Only trade if MACD Main line is below the Signal line
}
if (UseATRVolatilityFilter && atrValue < ATR_VolatilityThreshold) {
Print("ATR Volatility condition not met, ATR value:", atrValue);
return false; // Avoid trading during low volatility
}
if (UseHeikenAshi && haClose >= Close[1]) {
Print("Heiken Ashi condition not met, HA Close:", haClose, " Close:", Close[1]);
return false; // Only trade if Heiken Ashi close indicates bearish trend
}
if (UseVolumeFilter && volume < MinVolume) {
Print("Volume condition not met, Volume:", volume);
return false; // Avoid trading if market volume is low
}
if (UseMultiTimeframeTrend && !(Close[1] < maHigherTimeframe)) {
Print("Multi-Timeframe Trend condition not met, Close:", Close[1], " Higher Timeframe MA:", maHigherTimeframe);
return false; // Only trade if the trend is confirmed on a higher timeframe
}
return true;
}
// Example function to check news impact
bool CheckNews() {
// Implement logic to check for news impact based on provided filters (High, Medium, Low impact)
// Placeholder logic here, always returns true for now
Print("Checking news impact");
return true;
}
// Example function to calculate StopLoss based on ATR
double CalculateStopLoss() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double stopLoss = atrValue * StopLossMultiplier;
// Additional safety checks
if (stopLoss < 10 * Point) {
Print("StopLoss value too low, adjusting to minimum level", 10 * Point);
stopLoss = 10 * Point; // Ensure minimum stop loss value
} else if (stopLoss > 200 * Point) {
Print("StopLoss value too high, adjusting to maximum level", 200 * Point);
stopLoss = 200 * Point; // Ensure maximum stop loss value
}
Print("Calculated StopLoss, ATR value:", atrValue, " StopLoss:", stopLoss);
return NormalizeDouble(stopLoss, Digits);
}
// Example function to calculate Dynamic Take Profit based on ATR
double CalculateDynamicTP() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double dynamicTP = atrValue * DynamicTPMultiplier;
Print("Calculated Dynamic TP, ATR value:", atrValue, " Dynamic TP:", dynamicTP);
return NormalizeDouble(dynamicTP, Digits);
}
// Example function to manage Break Even
void ManageBreakEven() {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only process orders that are in profit and belong to the current symbol and have a specific Magic Number
if (OrderSymbol() == Symbol() && OrderProfit() > 0 && OrderMagicNumber() == MagicNumber_Hilo) {
double breakEvenLevel = (OrderType() == OP_BUY)
? OrderOpenPrice() + BreakEvenLevel * Point
: OrderOpenPrice() - BreakEvenLevel * Point;
if ((OrderType() == OP_BUY && Bid > breakEvenLevel && OrderStopLoss() < OrderOpenPrice()) ||
(OrderType() == OP_SELL && Ask < breakEvenLevel && OrderStopLoss() > OrderOpenPrice())) {
if (!OrderModify(OrderTicket(), OrderOpenPrice(), breakEvenLevel, OrderTakeProfit(), 0)) {
Print("OrderModify failed with error #", GetLastError());
} else {
Print("BreakEven set for order #", OrderTicket(), " at level:", breakEvenLevel);
}
}
}
}
}
}
// Example function to manage trailing stop
void ManageTrailingStop() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0); // ATR value for dynamic adjustment
double dynamicTrailStart = TrailStart * (atrValue / 0.01); // Dynamically adjust TrailStart based on ATR
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only process orders that belong to the current symbol and have a specific Magic Number
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber_Hilo) {
double newStopLevel = (OrderType() == OP_BUY)
? Bid - dynamicTrailStart * Point
: Ask + dynamicTrailStart * Point;
if (((OrderType() == OP_BUY && newStopLevel > OrderStopLoss()) ||
(OrderType() == OP_SELL && newStopLevel < OrderStopLoss())) && OrderStopLoss() != 0) {
if (!OrderModify(OrderTicket(), OrderOpenPrice(), newStopLevel, OrderTakeProfit(), 0)) {
Print("OrderModify failed with error #", GetLastError());
} else {
Print("Trailing stop adjusted for order #", OrderTicket(), " to level:", newStopLevel);
}
}
}
}
}
}
// Example function to check if the trading day is valid
bool IsTradingDay() {
int dayOfWeek = TimeDayOfWeek(TimeCurrent());
if ((dayOfWeek == 0 && !Sunday) ||
(dayOfWeek == 1 && !Monday) ||
(dayOfWeek == 2 && !Tuesday) ||
(dayOfWeek == 3 && !Wednesday) ||
(dayOfWeek == 4 && !Thursday) ||
(dayOfWeek == 5 && !Friday) ||
(dayOfWeek == 6 && !Saturday)) {
Print("Today is not a trading day");
return false;
}
return true;
}
// Example function to check if current time is within trading hours
bool IsTradingHour() {
int currentHour = TimeHour(TimeCurrent());
if (currentHour >= HoursFrom && currentHour <= HoursTo) {
return true;
}
Print("Current time is outside trading hours");
return false;
}
// Example function to check distance from the last order
bool IsEnoughDistanceFromLastOrder() {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only check orders with the specific Magic Number
if (OrderMagicNumber() == MagicNumber_Hilo) {
double distance = MathAbs(OrderOpenPrice() - Bid) / Point;
if (distance < MinOrderDistance) {
Print("Minimum distance not satisfied, distance:", distance);
return false; // Minimum distance not satisfied
}
}
}
}
return true;
}
// Function to count the number of open trades for the current symbol
int CountOpenTrades() {
int count = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol() == Symbol() && (OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderMagicNumber() == MagicNumber_Hilo) {
count++;
}
}
}
Print("Number of open trades for symbol:", Symbol(), " is ", count);
return count;
}
// Example function to check if the current market condition is suitable based on Day Range
bool CheckDayRange() {
double dayHigh = iHigh(Symbol(), PERIOD_D1, 0);
double dayLow = iLow(Symbol(), PERIOD_D1, 0);
double range = dayHigh - dayLow;
double averageRange = iATR(Symbol(), PERIOD_D1, DayRangePeriod, 0);
if (range > DayRangeThreshold * Point && range > averageRange) {
return true; // Trade allowed if the daily range is greater than the threshold and average range
}
Print("Day range condition not met, Range:", range, " Average Range:", averageRange);
return false;
}
// Example OnInit function
int OnInit() {
// Initialization tasks if needed
Print("Expert Advisor Initialized");
return INIT_SUCCEEDED;
}
// Example OnDeinit function
void OnDeinit(const int reason) {
// Cleanup tasks if needed
Print("Expert Advisor Deinitialized, Reason: ", reason);
}
I must finish inserting the average into the RSI, and then change the entry conditions to the market.
// Expert Advisor (EA) in MQL4 based on the provided parameters, now with Parabolic SAR filter, ADX filter, MACD filter, ATR volatility filter, Multi-Timeframe Trend filter, Heiken Ashi filter, Volume filter, and Debug Print Statements for Diagnostics
//--- Inputs based on provided image
input bool Monday = true;
input bool Tuesday = true;
input bool Wednesday = true;
input bool Thursday = true;
input bool Friday = true;
input bool Saturday = false;
input bool Sunday = false;
input bool TradeMonthEnd = false;
input int MonthEndOffset = 1;
input bool TradeFirstDayOffset = false;
input double DayOffset = 0.0;
input double GMTOffset = 0.0;
input bool TradeNFP = false;
input bool TradeMondayAfterNFP = false;
input bool TradeADP = false;
input bool Trading24h = false;
input int HoursFrom = 8;
input int HoursTo = 19; // Optimized trading hours to focus on active market times
input bool Session_Filter = false;
input bool Session_Filter1 = false;
input double SF1Hour_On = 5.0;
input double SF1MinuteOn = 0.0;
input double SF1Hour_Off = 9.0;
input double SF1MinuteOff = 0.0;
input bool AvoidNews = true;
input bool High_Impact = true;
input int MinsUntilNextHighNews = 90;
input int MinsSincePrevHighNews = 90;
input bool Medium_Impact = true;
input int MinsUntilNextMediumNews = 60;
input int MinsSincePrevMediumNews = 60;
input bool Low_Impact = false;
input int MinsUntilNextLowNews = 30;
input int MinsSincePrevLowNews = 30;
input bool USD = true;
input bool EUR = true;
input bool GBP = true;
input bool JPY = false;
input bool AUD = false;
input bool CAD = false;
input bool CHF = false;
input bool NZD = false;
input int MA_RSI_Period = 14; // Periodo della Media Mobile sulla RSI
input ENUM_MA_METHOD MA_RSI_Method = MODE_SMA; // Metodo della Media Mobile (SMA, EMA, etc.)
input int RSI_Period = 14; // Periodo RSI
input int Applied_Price = PRICE_CLOSE; // Prezzo applicato per RSI
input double MA_RSI_Level = 50.0; // Livello della Media Mobile sulla RSI per Buy/Sell
input bool UseMARSI = true; // On/Off filtro Media Mobile su RSI
// Main order settings
input double Lots = 0.1;
input double MicroLot = 0.01;
input double LotExponent = 1.5;
input int lotdecimal = 2;
input double PipStep = 50.0; // Adjusted PipStep for H1 timeframe
input double MaxLots = 10.0;
input bool ReverseOrder = false;
input double SlipPage = 3.0;
input double RiskInPercent = 2.0;
input bool AutoLotSize = true;
input bool UseTimeStop = false;
input bool StopHours = true;
input bool StopMinutes = true;
input double TakeProfit = 100.0; // Adjusted TakeProfit for H1 timeframe
input double StopLossMultiplier = 2.0; // Adjusted input for controlling stop loss based on ATR or another value
input bool UseEquityStop = true;
input double TotalEquityRisk = 5.0; // Reduced risk percentage for H1 timeframe
input bool UseTrailingStop = true;
input double TrailStart = 50.0; // Adjusted trailing start for H1 timeframe
input double TrailStop = 25.0; // Adjusted trailing stop for H1 timeframe
input double slip = 3.0;
// Fibo-settings
input int Max_Trades_Hilo = 10;
input int MagicNumber_Hilo = 10278;
// RSI-settings
input int g_magic_176_15 = 22324;
input int MaxTrades_15 = 10;
input double RSI_BuyLowerLevel = 60.0; // Adjusted RSI Buy Lower Level for H1
input double RSI_BuyUpperLevel = 70.0; // Adjusted RSI Buy Upper Level for H1
input double RSI_SellLowerLevel = 30.0; // Adjusted RSI Sell Lower Level for H1
input double RSI_SellUpperLevel = 40.0; // Adjusted RSI Sell Upper Level for H1
input bool UseRSI = true; // On/Off RSI filter
// Dayrange-settings
input int g_magic_176_16 = 23794;
input int MaxTrades_16 = 10;
input double DayRangeThreshold = 50.0; // Range giornaliero in pips oltre il quale si verifica un segnale
input int DayRangePeriod = 14; // Periodo per calcolare il range giornaliero medio
// News filter
input bool UseNewsFilter = true;
// Moving Average settings
input int MA_Period = 50; // Adjusted MA period for H1 timeframe
input int MA_Shift = 0;
input ENUM_MA_METHOD MA_Type = MODE_SMA; // Added option for different MA types: Simple, Exponential, Smoothed, Linear Weighted
input int MA_Price = PRICE_CLOSE;
input bool UseMA = true; // On/Off MA filter
// Second Moving Average settings
input int MA2_Period = 100; // Adjusted MA2 period for H1 timeframe
input int MA2_Shift = 0;
input ENUM_MA_METHOD MA2_Type = MODE_SMA; // Added option for different MA types: Simple, Exponential, Smoothed, Linear Weighted
input int MA2_Price = PRICE_CLOSE;
input bool UseMA2 = true; // On/Off Second MA filter
// Bollinger Bands settings
input int BB_Period = 20;
input double BB_Deviation = 2.0;
input bool UseBB = true; // On/Off Bollinger Bands filter
// ATR settings
input int ATR_Period = 14; // Adjusted ATR period for H1 timeframe
input double ATR_VolatilityThreshold = 0.01; // Adjusted ATR volatility threshold for H1 timeframe
input bool UseATRVolatilityFilter = true; // On/Off ATR Volatility filter
// Ichimoku settings
input int Ichimoku_Tenkan = 9;
input int Ichimoku_Kijun = 26;
input int Ichimoku_Senkou = 52;
input bool UseIchimoku = true; // On/Off Ichimoku filter
// Parabolic SAR settings
input double PSAR_Step = 0.02;
input double PSAR_Maximum = 0.2;
input bool UseParabolicSAR = true; // On/Off Parabolic SAR filter
// ADX settings
input int ADX_Period = 14; // Adjusted ADX period for H1 timeframe
input double ADX_Level = 25.0; // Adjusted ADX level for stronger trend detection on H1
input double ADX_DPlusThreshold = 20.0; // Lowered threshold for more sensitivity in trend detection
input double ADX_DMinusThreshold = 20.0; // Lowered threshold for more sensitivity in trend detection
input bool UseADX = true; // On/Off ADX filter
// MACD settings
input int MACD_Fast = 9;
input int MACD_Slow = 21;
input int MACD_Signal = 9;
input bool UseMACD = false; // On/Off MACD filter
// Heiken Ashi settings
input bool UseHeikenAshi = true; // On/Off Heiken Ashi filter
// Multi-Timeframe Trend settings
input int HigherTimeframe = PERIOD_H4; // Timeframe for higher trend confirmation
input bool UseMultiTimeframeTrend = true; // On/Off Multi-Timeframe Trend filter
// Volume settings
input bool UseVolumeFilter = true; // On/Off Volume filter
input double MinVolume = 100.0; // Adjusted minimum volume for H1 timeframe
// Maximum number of allowed open trades
input int MaxOpenTrades = 1;
// Minimum distance between new orders (in points)
input double MinOrderDistance = 100;
// Break Even and Dynamic Take Profit settings
input bool UseBreakEven = true;
input double BreakEvenLevel = 10.0; // Move stop to break-even after this many pips in profit
input bool UseDynamicTP = true;
input double DynamicTPMultiplier = 1.5; // Multiplier to calculate dynamic take profit based on ATR
// EA Logic Placeholder
void OnTick() {
// Add trading logic based on these inputs
// For example, check trading time, open orders, apply filters, etc.
//--- Example: Check the trading time based on HoursFrom and HoursTo
if (!IsTradingDay() || !IsTradingHour()) {
return; // Exit if today is not a trading day or it's outside trading hours
}
// Check if we should avoid trading due to news
if (AvoidNews && !CheckNews()) {
Print("Avoiding trade due to unfavorable news conditions");
return; // Exit if news conditions are not favorable
}
// Check if the number of open trades exceeds the maximum allowed
if (CountOpenTrades() >= MaxOpenTrades) {
Print("Maximum number of open trades reached");
return; // Exit if the maximum number of open trades is reached
}
// Calculate lot size based on risk settings
double lotSize = Lots;
if (AutoLotSize) {
double accountBalance = AccountBalance();
lotSize = NormalizeDouble((accountBalance * RiskInPercent / 100) / 1000, lotdecimal);
if (lotSize > MaxLots) lotSize = MaxLots;
}
// Check distance from the last order
if (!IsEnoughDistanceFromLastOrder()) {
Print("Minimum distance condition not met for new order");
return; // Exit if the minimum distance condition is not met
}
// Placeholder for trade entry logic
if (MarketCondition() && CheckDayRange()) {
Print("Market conditions met for a new trade");
// Open a new order
double tp = TakeProfit * Point;
double sl = CalculateStopLoss(); // Calculate StopLoss based on ATR or other strategies
if (UseDynamicTP) {
tp = CalculateDynamicTP(); // Calculate dynamic TP based on ATR
}
int ticket = -1;
if (ShouldBuy()) {
ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, SlipPage, Ask - sl, Ask + tp, "Buy Order", MagicNumber_Hilo, 0, Blue);
} else if (ShouldSell()) {
ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, SlipPage, Bid + sl, Bid - tp, "Sell Order", MagicNumber_Hilo, 0, Red);
}
if (ticket < 0) {
Print("OrderSend failed with error #", GetLastError());
} else {
Print("Order sent successfully, ticket #", ticket);
}
}
// Manage break-even stop if applicable
if (UseBreakEven) {
ManageBreakEven();
}
// Manage trailing stop if applicable
if (UseTrailingStop) {
ManageTrailingStop();
}
}
// Function to determine if the market conditions are favorable for trading
bool MarketCondition() {
Print("Checking market conditions");
return (ShouldBuy() || ShouldSell());
}
// Determine if a Buy condition is met
bool ShouldBuy() {
// Check for candle direction to be bullish
if (Close[1] <= Open[1]) {
Print("Previous candle is not bullish");
return false; // Only trade if previous candle is bullish
}
double rsiValue = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);
double maValue = iMA(Symbol(), 0, MA_Period, MA_Shift, MA_Type, MA_Price, 0);
double ma2Value = iMA(Symbol(), 0, MA2_Period, MA2_Shift, MA2_Type, MA2_Price, 0);
double bbMiddle = iBands(Symbol(), 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_MAIN, 0);
double kijunSen = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 1, 0); // Usato indice 1 per la Kijun Sen
double senkouSpanA = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 2, 0); // Senkou Span A
double psarValue = iSAR(Symbol(), 0, PSAR_Step, PSAR_Maximum, 0);
double adxValue = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MAIN, 0);
double diPlus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_PLUSDI, 0);
double diMinus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MINUSDI, 0);
double macdMain = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_MAIN, 0);
double macdSignal = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_SIGNAL, 0);
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double haClose = iCustom(Symbol(), 0, "Heiken Ashi", 3, 0); // Heiken Ashi close value
double volume = iVolume(Symbol(), 0, 0);
double maHigherTimeframe = iMA(Symbol(), HigherTimeframe, MA_Period, MA_Shift, MA_Type, MA_Price, 0); // Higher timeframe MA
if (UseRSI && !(rsiValue > RSI_BuyLowerLevel && rsiValue < RSI_BuyUpperLevel)) {
Print("RSI condition not met, RSI value:", rsiValue);
return false;
}
if (UseMA && !(Close[1] > maValue)) {
Print("MA condition not met, Close:", Close[1], " MA:", maValue);
return false;
}
if (UseMA2 && !(Close[1] > ma2Value)) {
Print("Second MA condition not met, Close:", Close[1], " MA2:", ma2Value);
return false;
}
if (UseBB && !(Close[1] > bbMiddle)) {
Print("Bollinger Bands condition not met, Close:", Close[1], " BB Middle:", bbMiddle);
return false;
}
if (UseIchimoku && !(Close[1] > kijunSen && Close[1] > senkouSpanA)) {
Print("Ichimoku condition not met, Close:", Close[1], " Kijun Sen:", kijunSen, " Senkou Span A:", senkouSpanA);
return false;
}
if (UseParabolicSAR && !(psarValue < Close[1])) {
Print("Parabolic SAR condition not met, SAR:", psarValue, " Close:", Close[1]);
return false;
}
if (UseADX && (adxValue < ADX_Level || diPlus < ADX_DPlusThreshold)) {
Print("ADX or Directional Index condition not met, ADX value:", adxValue, " +DI:", diPlus, " Threshold:", ADX_DPlusThreshold);
return false; // Only trade if ADX indicates a strong trend and +DI is greater than the threshold
}
if (UseMACD && !(macdMain > macdSignal)) {
Print("MACD condition not met, MACD Main:", macdMain, " MACD Signal:", macdSignal);
return false; // Only trade if MACD Main line is above the Signal line
}
if (UseATRVolatilityFilter && atrValue < ATR_VolatilityThreshold) {
Print("ATR Volatility condition not met, ATR value:", atrValue);
return false; // Avoid trading during low volatility
}
if (UseHeikenAshi && haClose <= Close[1]) {
Print("Heiken Ashi condition not met, HA Close:", haClose, " Close:", Close[1]);
return false; // Only trade if Heiken Ashi close indicates bullish trend
}
if (UseVolumeFilter && volume < MinVolume) {
Print("Volume condition not met, Volume:", volume);
return false; // Avoid trading if market volume is low
}
if (UseMultiTimeframeTrend && !(Close[1] > maHigherTimeframe)) {
Print("Multi-Timeframe Trend condition not met, Close:", Close[1], " Higher Timeframe MA:", maHigherTimeframe);
return false; // Only trade if the trend is confirmed on a higher timeframe
}
return true;
}
// Determine if a Sell condition is met
bool ShouldSell() {
// Check for candle direction to be bearish
if (Close[1] >= Open[1]) {
Print("Previous candle is not bearish");
return false; // Only trade if previous candle is bearish
}
double rsiValue = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);
double maValue = iMA(Symbol(), 0, MA_Period, MA_Shift, MA_Type, MA_Price, 0);
double ma2Value = iMA(Symbol(), 0, MA2_Period, MA2_Shift, MA2_Type, MA2_Price, 0);
double bbMiddle = iBands(Symbol(), 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_MAIN, 0);
double kijunSen = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 1, 0); // Usato indice 1 per la Kijun Sen
double senkouSpanA = iIchimoku(Symbol(), 0, Ichimoku_Tenkan, Ichimoku_Kijun, Ichimoku_Senkou, 2, 0); // Senkou Span A
double psarValue = iSAR(Symbol(), 0, PSAR_Step, PSAR_Maximum, 0);
double adxValue = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MAIN, 0);
double diPlus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_PLUSDI, 0);
double diMinus = iADX(Symbol(), 0, ADX_Period, PRICE_CLOSE, MODE_MINUSDI, 0);
double macdMain = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_MAIN, 0);
double macdSignal = iMACD(Symbol(), 0, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE, MODE_SIGNAL, 0);
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double haClose = iCustom(Symbol(), 0, "Heiken Ashi", 3, 0); // Heiken Ashi close value
double volume = iVolume(Symbol(), 0, 0);
double maHigherTimeframe = iMA(Symbol(), HigherTimeframe, MA_Period, MA_Shift, MA_Type, MA_Price, 0); // Higher timeframe MA
if (UseRSI && !(rsiValue < RSI_SellUpperLevel && rsiValue > RSI_SellLowerLevel)) {
Print("RSI condition not met, RSI value:", rsiValue);
return false;
}
if (UseMA && !(Close[1] < maValue)) {
Print("MA condition not met, Close:", Close[1], " MA:", maValue);
return false;
}
if (UseMA2 && !(Close[1] < ma2Value)) {
Print("Second MA condition not met, Close:", Close[1], " MA2:", ma2Value);
return false;
}
if (UseBB && !(Close[1] < bbMiddle)) {
Print("Bollinger Bands condition not met, Close:", Close[1], " BB Middle:", bbMiddle);
return false;
}
if (UseIchimoku && !(Close[1] < kijunSen && Close[1] < senkouSpanA)) {
Print("Ichimoku condition not met, Close:", Close[1], " Kijun Sen:", kijunSen, " Senkou Span A:", senkouSpanA);
return false;
}
if (UseParabolicSAR && !(psarValue > Close[1])) {
Print("Parabolic SAR condition not met, SAR:", psarValue, " Close:", Close[1]);
return false;
}
if (UseADX && (adxValue < ADX_Level || diMinus < ADX_DMinusThreshold)) {
Print("ADX or Directional Index condition not met, ADX value:", adxValue, " -DI:", diMinus, " Threshold:", ADX_DMinusThreshold);
return false; // Only trade if ADX indicates a strong trend and -DI is greater than the threshold
}
if (UseMACD && !(macdMain < macdSignal)) {
Print("MACD condition not met, MACD Main:", macdMain, " MACD Signal:", macdSignal);
return false; // Only trade if MACD Main line is below the Signal line
}
if (UseATRVolatilityFilter && atrValue < ATR_VolatilityThreshold) {
Print("ATR Volatility condition not met, ATR value:", atrValue);
return false; // Avoid trading during low volatility
}
if (UseHeikenAshi && haClose >= Close[1]) {
Print("Heiken Ashi condition not met, HA Close:", haClose, " Close:", Close[1]);
return false; // Only trade if Heiken Ashi close indicates bearish trend
}
if (UseVolumeFilter && volume < MinVolume) {
Print("Volume condition not met, Volume:", volume);
return false; // Avoid trading if market volume is low
}
if (UseMultiTimeframeTrend && !(Close[1] < maHigherTimeframe)) {
Print("Multi-Timeframe Trend condition not met, Close:", Close[1], " Higher Timeframe MA:", maHigherTimeframe);
return false; // Only trade if the trend is confirmed on a higher timeframe
}
return true;
}
// Example function to check news impact
bool CheckNews() {
// Implement logic to check for news impact based on provided filters (High, Medium, Low impact)
// Placeholder logic here, always returns true for now
Print("Checking news impact");
return true;
}
// Example function to calculate StopLoss based on ATR
double CalculateStopLoss() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double stopLoss = atrValue * StopLossMultiplier;
// Additional safety checks
if (stopLoss < 10 * Point) {
Print("StopLoss value too low, adjusting to minimum level", 10 * Point);
stopLoss = 10 * Point; // Ensure minimum stop loss value
} else if (stopLoss > 200 * Point) {
Print("StopLoss value too high, adjusting to maximum level", 200 * Point);
stopLoss = 200 * Point; // Ensure maximum stop loss value
}
Print("Calculated StopLoss, ATR value:", atrValue, " StopLoss:", stopLoss);
return NormalizeDouble(stopLoss, Digits);
}
// Example function to calculate Dynamic Take Profit based on ATR
double CalculateDynamicTP() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0);
double dynamicTP = atrValue * DynamicTPMultiplier;
Print("Calculated Dynamic TP, ATR value:", atrValue, " Dynamic TP:", dynamicTP);
return NormalizeDouble(dynamicTP, Digits);
}
// Example function to manage Break Even
void ManageBreakEven() {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only process orders that are in profit and belong to the current symbol and have a specific Magic Number
if (OrderSymbol() == Symbol() && OrderProfit() > 0 && OrderMagicNumber() == MagicNumber_Hilo) {
double breakEvenLevel = (OrderType() == OP_BUY)
? OrderOpenPrice() + BreakEvenLevel * Point
: OrderOpenPrice() - BreakEvenLevel * Point;
if ((OrderType() == OP_BUY && Bid > breakEvenLevel && OrderStopLoss() < OrderOpenPrice()) ||
(OrderType() == OP_SELL && Ask < breakEvenLevel && OrderStopLoss() > OrderOpenPrice())) {
if (!OrderModify(OrderTicket(), OrderOpenPrice(), breakEvenLevel, OrderTakeProfit(), 0)) {
Print("OrderModify failed with error #", GetLastError());
} else {
Print("BreakEven set for order #", OrderTicket(), " at level:", breakEvenLevel);
}
}
}
}
}
}
// Example function to manage trailing stop
void ManageTrailingStop() {
double atrValue = iATR(Symbol(), 0, ATR_Period, 0); // ATR value for dynamic adjustment
double dynamicTrailStart = TrailStart * (atrValue / 0.01); // Dynamically adjust TrailStart based on ATR
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only process orders that belong to the current symbol and have a specific Magic Number
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber_Hilo) {
double newStopLevel = (OrderType() == OP_BUY)
? Bid - dynamicTrailStart * Point
: Ask + dynamicTrailStart * Point;
if (((OrderType() == OP_BUY && newStopLevel > OrderStopLoss()) ||
(OrderType() == OP_SELL && newStopLevel < OrderStopLoss())) && OrderStopLoss() != 0) {
if (!OrderModify(OrderTicket(), OrderOpenPrice(), newStopLevel, OrderTakeProfit(), 0)) {
Print("OrderModify failed with error #", GetLastError());
} else {
Print("Trailing stop adjusted for order #", OrderTicket(), " to level:", newStopLevel);
}
}
}
}
}
}
// Example function to check if the trading day is valid
bool IsTradingDay() {
int dayOfWeek = TimeDayOfWeek(TimeCurrent());
if ((dayOfWeek == 0 && !Sunday) ||
(dayOfWeek == 1 && !Monday) ||
(dayOfWeek == 2 && !Tuesday) ||
(dayOfWeek == 3 && !Wednesday) ||
(dayOfWeek == 4 && !Thursday) ||
(dayOfWeek == 5 && !Friday) ||
(dayOfWeek == 6 && !Saturday)) {
Print("Today is not a trading day");
return false;
}
return true;
}
// Example function to check if current time is within trading hours
bool IsTradingHour() {
int currentHour = TimeHour(TimeCurrent());
if (currentHour >= HoursFrom && currentHour <= HoursTo) {
return true;
}
Print("Current time is outside trading hours");
return false;
}
// Example function to check distance from the last order
bool IsEnoughDistanceFromLastOrder() {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
// Only check orders with the specific Magic Number
if (OrderMagicNumber() == MagicNumber_Hilo) {
double distance = MathAbs(OrderOpenPrice() - Bid) / Point;
if (distance < MinOrderDistance) {
Print("Minimum distance not satisfied, distance:", distance);
return false; // Minimum distance not satisfied
}
}
}
}
return true;
}
// Function to count the number of open trades for the current symbol
int CountOpenTrades() {
int count = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol() == Symbol() && (OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderMagicNumber() == MagicNumber_Hilo) {
count++;
}
}
}
Print("Number of open trades for symbol:", Symbol(), " is ", count);
return count;
}
// Example function to check if the current market condition is suitable based on Day Range
bool CheckDayRange() {
double dayHigh = iHigh(Symbol(), PERIOD_D1, 0);
double dayLow = iLow(Symbol(), PERIOD_D1, 0);
double range = dayHigh - dayLow;
double averageRange = iATR(Symbol(), PERIOD_D1, DayRangePeriod, 0);
if (range > DayRangeThreshold * Point && range > averageRange) {
return true; // Trade allowed if the daily range is greater than the threshold and average range
}
Print("Day range condition not met, Range:", range, " Average Range:", averageRange);
return false;
}
// Example OnInit function
int OnInit() {
// Initialization tasks if needed
Print("Expert Advisor Initialized");
return INIT_SUCCEEDED;
}
// Example OnDeinit function
void OnDeinit(const int reason) {
// Cleanup tasks if needed
Print("Expert Advisor Deinitialized, Reason: ", reason);
}