From 7ab804654344825b998f3ab9f9778e71f1b6b471 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 15 Sep 2024 14:14:44 +0330 Subject: [PATCH] combine xch and xchche strategy in one ea and name it x121 ... --- Experts/x-saherelm.x121.ea.mq5 | 956 +++++++++++++++++++++++++++++++++ 1 file changed, 956 insertions(+) create mode 100644 Experts/x-saherelm.x121.ea.mq5 diff --git a/Experts/x-saherelm.x121.ea.mq5 b/Experts/x-saherelm.x121.ea.mq5 new file mode 100644 index 00000000..8520f0d4 --- /dev/null +++ b/Experts/x-saherelm.x121.ea.mq5 @@ -0,0 +1,956 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: X121EA +// Description: an Exper Advisor which used to +// XCH and XCHCHE Strategy to Analyse Market ... +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +//////////////////////////////////////////////////////x +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm X121EA" +#property strict + +// +#define ShortName "X121EA" + +// +// Imports ... +#include "../Helpers/x-saherelm.xct.helper.mq5" +#include "../Helpers/x-saherelm.xcc.helper.mq5" + +// +#include "../Parsers/x-saherelm.xch.parser.mq5" +#include "../Strategies/x-saherelm.xch.strategy.mq5" + +// +#include "../Parsers/x-saherelm.xch.che.parser.mq5" +#include "../Strategies/x-saherelm.xch.che.strategy.mq5" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Symbols ... +input group "Symbols"; +input bool eaMultiSymbol = false; // Use Multi Symbol +input bool eaUseMaxAllowedTradesPerSymbol = true; // Use Max Allowed Trades Per Symbol +input string eaSymbols = "EURUSDb,GBPUSDb,EURGBPb,USDJPYb,EURJPYb,USDCHFb,EURCHFb,AUDUSDb,EURAUDb,NZDUSDb,EURNZDb,USDCADb,EURCADb,XAUUSDb,XAGUSDb,BRENT,DowJones30"; // Trading Symbols + +// +// Risk Management ... +input group "Risk Management"; + +// +// Risk Management > Risk / Reward Calculation ... +input group "Risk/Reward"; +input bool eaIgnoreTP = false; // Ignore TP +input bool eaIgnoreSL = false; // Ignore SL +input double eaTPPoint = 200; // Static TP Point +input double eaSLPoint = 200; // Static SL Point + +// +// Risk Management > Volume Calculation ... +input group "Volume"; +input bool eaUseDynamicVolume = false; // Use Dynamic Volume +input double eaDynamicVolumeStep = 0.01; // Increase Volume Step +input double eaDynamicVolumeBalanceFactor = 200; // Balance Factor for Generate Dynamic Volume +input double eaVolume = 0.02; // Static Volume + +// +// Risk Management > Trade Management ... +input group "Trade Management"; +input bool eaAllowLong = true; // Allow Long Positions +input bool eaAllowShort = true; // Allow Short Positions +input int eaMaxAllowedLongs = 2; // Max Allowed Long Positions +input int eaMaxAllowedShorts = 2; // Max Allowed Short Positions +input double eaMaxDrawdownPercentForOpenTrades = 3; // Max Drawdown Percent for Open Trades + +// +// Alert ... +input group "Alert"; +input bool eAEnableAlerts = true; // Enable Alerts +input bool eALogAlerts = true; // Log Alerts +input bool eAMailAlerts = false; // Mail Alerts +input bool eAPushAlerts = false; // Push Alerts +input bool eATerminalAlerts = false; // Terminal Alerts + +// +// Time Report ... +input group "Reports"; +input bool eaAlertNewMonths = false; // Alert New Month +input bool eaAlertNewWeeks = false; // Alert New Weeks +input bool eaAlertNewDays = true; // Alert New Days +input bool eaAlertNewHours = false; // Alert New Hours +input bool eaAlertRawSignals = false; // Alert Raw Signals +input bool eaAlertStrongSignals = false; // Alert Strong Signals + +// +// Variables ... + +// +// Bar Style nad Time Instances ... +XSCXCTHelper *mCTHelper; +XSCXCCHelper *mCCHelper; + +// +// Registred Strategies ... +XSCBaseStrategy *strategies[]; + +// +// Trader Instance Class ... +XSCTrade *eaTrader; + +// +// Alert Class ... +XSCAlert *eaAlert; + +// +// Time Tracker ... +XTimeTracker eaTimeTracker; + +// +// Trade Handler Instance Class ... +XSCXTradeHandler *eaTradeHandler; + +// +string mTag = ""; + +// +double eaR2R = 1.5; +bool eaUseFixedTPSLPoints = true; + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + if (!InitialEA()) + { + return INIT_FAILED; + } + + // + mTag = + !IsValid(eaLogSuffix) + ? ShortName + : ShortName + "_" + eaLogSuffix; + + // + drawPrefix = mTag; + + // + // EventSetTimer(1); + // EventSetMillisecondTimer(100); + + // + // Alert Initialization ... + string msg = "Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + // Alert De Initialization Succeeded ... + string msg = "De Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // De Initialize XSampleEA Providers ... + delete mCTHelper; + delete mCCHelper; + + // + delete eaAlert; + delete eaTrader; + delete eaTradeHandler; + + // + Clean(strategies); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + HandleTradeState(); + HandleTimeReport(); + HandleStrategiesOnTick(); +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaTrader.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + // + // HandleTradeState(); + // HandleTimeReport(); + // HandleStrategiesOnTick(); +} + +// +// Custom Functions ... + +// +// Validate Inputs ... +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + bool isSymbolsValid = ( + // + eaMultiSymbol + ? IsValid(eaSymbols) + : true + // + ); + if (!isSymbolsValid) + { + // + errMessage += "symbols configurations error;" + "\n"; + } + + // + bool isRiskRewardValid = ( + // + (eaUseFixedTPSLPoints + ? eaTPPoint > 0 || + eaSLPoint > 0 + : eaR2R > 0) && + !(eaIgnoreTP && + eaIgnoreSL) + // + ); + if (!isRiskRewardValid) + { + // + errMessage += "risk/reward configurations error;" + "\n"; + } + + // + bool isVolumeValid = ( + // + eaUseDynamicVolume + ? eaDynamicVolumeStep >= 0.01 && + eaDynamicVolumeBalanceFactor > 0 + : eaVolume >= 0.01 + // + ); + if (!isVolumeValid) + { + // + errMessage += "volume configurations error;" + "\n"; + } + + // + bool isTradeManagementValid = ( + // + !(!eaAllowLong && !eaAllowShort) && + eaMaxAllowedLongs >= 0 && + eaMaxAllowedShorts >= 0 + // + ); + if (!isTradeManagementValid) + { + // + errMessage += "trade management configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Symbols ... + isSymbolsValid && + // + // Risk/Reward ... + isRiskRewardValid && + // + // Volume ... + isVolumeValid && + // + // Trade Management ... + isTradeManagementValid + // + ; + + // + if (!result) + { + Print("Errors: \n", errMessage); + } + + // + return result; +} + +// +// Initialize all Requirements ... +bool InitialEA() +{ + // + bool result = false; + + // + // Bar Timer ... + XCTInputs ctInputs; + ctInputs.Default(); + mCTHelper = new XSCXCTHelper(); + result = mCTHelper.Init( + _Symbol, + _Period, + ctInputs // + ); + if (!result) + { + return result; + } + + // + // Bar Styles ... + XCCInputs ccInputs; + ccInputs.Default(); + mCCHelper = new XSCXCCHelper(); + result = mCCHelper.Init( + _Symbol, + _Period, + ccInputs // + ); + if (!result) + { + return result; + } + + // + // Create Instance of Alert Class ... + eaAlert = new XSCAlert(); + eaAlert.SetPrefix(mTag); + eaAlert.SetLogAlerts(eALogAlerts); + eaAlert.SetMailAlerts(eAMailAlerts); + eaAlert.SetPushAlerts(eAPushAlerts); + eaAlert.SetEnableAlerts(eAEnableAlerts); + eaAlert.SetTerminalAlerts(eATerminalAlerts); + + // + // Create Trader Instance ... + eaTrader = new XSCTrade( + eaSlippage, + eaMagicNumber // + ); + eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered); + eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + + // + // Initialize Trade Handler ... + eaTradeHandler = new XSCXTradeHandler(eaTrader); + eaTradeHandler.SaveTrades(true); + eaTradeHandler.SaveSignals(true); + eaTradeHandler.SaveConditions(true); + + // + // Configure Alerts ... + eaTradeHandler.SetAlertPrefix(mTag); + eaTradeHandler.SetAlertEnableAlerts(eAEnableAlerts); + eaTradeHandler.SetAlertLogAlerts(eALogAlerts); + eaTradeHandler.SetAlertMailAlerts(eAMailAlerts); + eaTradeHandler.SetAlertPushAlerts(eAPushAlerts); + eaTradeHandler.SetAlertTerminalAlerts(eATerminalAlerts); + + // + // Configure Trade Management ... + eaTradeHandler.AllowLong(eaAllowLong); + eaTradeHandler.AllowShort(eaAllowShort); + eaTradeHandler.MaxAllowedLongs(eaMaxAllowedLongs); + eaTradeHandler.MaxAllowedShorts(eaMaxAllowedShorts); + eaTradeHandler.UseMaxAllowedTradesPerSymbol(eaUseMaxAllowedTradesPerSymbol); + eaTradeHandler.MaxDrawdownPercentForOpenTrades(eaMaxDrawdownPercentForOpenTrades); + + // + // Single Symbol ... + if (!eaMultiSymbol) + { + // + // Register XCH Strategy ... + + // + // Create Class Instance ... + XSCXCHStrategy *xchStrategy; + xchStrategy = new XSCXCHStrategy( + _Symbol, + _Period, + PERIOD_H1, // Analyzing Period + eaVolume, + eaR2R, // R2R ... + eaSlippage, + eaMagicNumber, + true, // Ignore Signal Execution + eaUseFixedTPSLPoints, // Use TP SL Point + false, // Use Max + eaTPPoint, // TP + eaSLPoint, // SL + eaIgnoreTP, + eaIgnoreSL, + eaAllowLong, + eaAllowShort, + eaMaxAllowedLongs, // Max Longs + eaMaxAllowedShorts // Max Shorts + ); + + // + // Configuere Strategy ... + xchStrategy.EnableXCHM(true); + xchStrategy.EnableXCHHK(true); + xchStrategy.EnableXCHSTR(true); + xchStrategy.EnableXCHCHE(true); + xchStrategy.DrawImportantAreas(false); + xchStrategy.AddXCHSignalEventHandler(OnSignalRecieved); + + // + // Configure Alerts ... + xchStrategy.SetAlertPrefix(mTag); + xchStrategy.SetAlertEnableAlerts(eAEnableAlerts); + xchStrategy.SetAlertLogAlerts(eALogAlerts); + xchStrategy.SetAlertMailAlerts(eAMailAlerts); + xchStrategy.SetAlertPushAlerts(eAPushAlerts); + xchStrategy.SetAlertTerminalAlerts(eATerminalAlerts); + + // + // Register Strategy ... + RegisterStrategy(xchStrategy); + + // + // Register XCHCHE Strategy ... + + // + // Create Class Instance ... + XSCXCHCHEStrategy *xchcheStrategy; + xchcheStrategy = new XSCXCHCHEStrategy( + _Symbol, + _Period, + PERIOD_H1, // Analyzing Period + eaVolume, + eaR2R, // R2R ... + eaSlippage, + eaMagicNumber, + true, // Ignore Signal Execution + eaUseFixedTPSLPoints, // Use TP SL Point + false, // Use Max + eaTPPoint, // TP + eaSLPoint, // SL + eaIgnoreTP, + eaIgnoreSL, + eaAllowLong, + eaAllowShort, + eaMaxAllowedLongs, // Max Longs + eaMaxAllowedShorts // Max Shorts + ); + + // + // Configuere Strategy ... + xchcheStrategy.DrawImportantAreas(false); + xchcheStrategy.AddXCHSignalEventHandler(OnSignalRecieved); + + // + // Configure Alerts ... + xchcheStrategy.SetAlertPrefix(mTag); + xchcheStrategy.SetAlertEnableAlerts(eAEnableAlerts); + xchcheStrategy.SetAlertLogAlerts(eALogAlerts); + xchcheStrategy.SetAlertMailAlerts(eAMailAlerts); + xchcheStrategy.SetAlertPushAlerts(eAPushAlerts); + xchcheStrategy.SetAlertTerminalAlerts(eATerminalAlerts); + + // + // Register Strategy ... + RegisterStrategy(xchcheStrategy); + } + // + // Multi Symbol ... + else + { + // + // Parse Symbols ... + string symbols[]; + int symbolsCount = SplitContent( + symbols, + eaSymbols // + ); + result = IsValidSize(symbolsCount); + if (!result) + { + return result; + } + + // + for (int i = 0; i < symbolsCount; i++) + { + // + // Select Symbol ... + string iSymbol = symbols[i]; + + // + // Register XCH Strategy ... + + // + // Create Class Instance ... + XSCXCHStrategy *iXCHStrategy; + iXCHStrategy = new XSCXCHStrategy( + iSymbol, + _Period, + PERIOD_H1, // Analyzing Period + eaVolume, + eaR2R, // R2R ... + eaSlippage, + eaMagicNumber, + true, // Ignore Signal Execution + eaUseFixedTPSLPoints, // Use TP SL Point + false, // Use Max + eaTPPoint, // TP + eaSLPoint, // SL + eaIgnoreTP, + eaIgnoreSL, + eaAllowLong, + eaAllowShort, + eaMaxAllowedLongs, // Max Longs + eaMaxAllowedShorts // Max Shorts + ); + + // + // Configuere Strategy ... + iXCHStrategy.EnableXCHM(true); + iXCHStrategy.EnableXCHHK(true); + iXCHStrategy.EnableXCHSTR(true); + iXCHStrategy.EnableXCHCHE(true); + iXCHStrategy.DrawImportantAreas(false); + iXCHStrategy.AddXCHSignalEventHandler(OnSignalRecieved); + + // + // Configure Alerts ... + iXCHStrategy.SetAlertPrefix(mTag); + iXCHStrategy.SetAlertEnableAlerts(eAEnableAlerts); + iXCHStrategy.SetAlertLogAlerts(eALogAlerts); + iXCHStrategy.SetAlertMailAlerts(eAMailAlerts); + iXCHStrategy.SetAlertPushAlerts(eAPushAlerts); + iXCHStrategy.SetAlertTerminalAlerts(eATerminalAlerts); + + // + // Register Strategy ... + RegisterStrategy(iXCHStrategy); + + // + // Register XCHCHE Strategy ... + + // + // Create Class Instance ... + XSCXCHCHEStrategy *iXCHCHEStrategy; + iXCHCHEStrategy = new XSCXCHCHEStrategy( + iSymbol, + _Period, + PERIOD_H1, // Analyzing Period + eaVolume, + eaR2R, // R2R ... + eaSlippage, + eaMagicNumber, + true, // Ignore Signal Execution + eaUseFixedTPSLPoints, // Use TP SL Point + false, // Use Max + eaTPPoint, // TP + eaSLPoint, // SL + eaIgnoreTP, + eaIgnoreSL, + eaAllowLong, + eaAllowShort, + eaMaxAllowedLongs, // Max Longs + eaMaxAllowedShorts // Max Shorts + ); + + // + // Configuere Strategy ... + iXCHCHEStrategy.DrawImportantAreas(false); + iXCHCHEStrategy.AddXCHSignalEventHandler(OnSignalRecieved); + + // + // Configure Alerts ... + iXCHCHEStrategy.SetAlertPrefix(mTag); + iXCHCHEStrategy.SetAlertEnableAlerts(eAEnableAlerts); + iXCHCHEStrategy.SetAlertLogAlerts(eALogAlerts); + iXCHCHEStrategy.SetAlertMailAlerts(eAMailAlerts); + iXCHCHEStrategy.SetAlertPushAlerts(eAPushAlerts); + iXCHCHEStrategy.SetAlertTerminalAlerts(eATerminalAlerts); + + // + // Register Strategy ... + RegisterStrategy(iXCHCHEStrategy); + } + } + + // + return result; +} + +// +// Register Strategy ... +void RegisterStrategy(XSCBaseStrategy *strategy) +{ + // + if (strategy == NULL) + { + return; + } + + // + ArrayResize( + strategies, + ArraySize(strategies) + 1 // + ); + + // + strategies[ArraySize(strategies) - 1] = strategy; +} + +// +// Call All Registered Strategis Tick Handler Functions ... +void HandleStrategiesOnTick() +{ + // + int count = ArraySize(strategies); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + // Call Tick Handler Function ... + strategies[i].HandleTick(); + } +} + +// +// Manage Trading States ... +void HandleTradeState() +{ + // + // Implement All Trade States here ... + eaTradeHandler.UpdateData(); + + // + // Do Protection Senarios ... + eaTradeHandler.HandleProtection(); +} + +// +// Time Reporting ... +void HandleTimeReport() +{ + // + // Monthly Report .... + if (eaAlertNewMonths && + eaTimeTracker.IsNewMonth()) + { + // + string msg = "New Month ..."; + + // + eaAlert.Alert(msg); + } + + // + // Weekly Report .... + if (eaAlertNewWeeks && + eaTimeTracker.IsNewWeek()) + { + // + string msg = "New Week ..."; + + // + eaAlert.Alert(msg); + } + + // + // Daily Report .... + if (eaAlertNewDays && + eaTimeTracker.IsNewDay()) + { + // + string msg = "New Day ..."; + + // + eaAlert.Alert(msg); + } + + // + // Hourly Report .... + if (eaAlertNewHours && + eaTimeTracker.IsNewHour()) + { + // + string msg = "New Hour ..."; + + // + eaAlert.Alert(msg); + } +} + +// +// SIGNAL EVENT Handlers ... +// + +// +// All Signals from Strategies Comming Here for Execution or +// Analyzing ... +void OnSignalRecieved( + XSignal &signal, + XCHStrategyConditions &conditions // +) +{ + // + // Check Signal and Conditions Validations ... + + // + if (!signal.IsValid()) + { + return; + } + + // + if (!conditions.IsValid()) + { + return; + } + + // + // Notify When a Raw (Unfiltered) Signal Recieved + // if it's Provided ... + if (eaAlertRawSignals) + { + // + string msg = "Raw " + (IsLong(signal.type) ? "Long" : "Short") + " Signal Recieved: (" + signal.provider + "," + signal.symbol + "," + ToString(signal.period) + ") ..."; + eaAlert.Alert(msg); + } + + // + // Prepare Signal Dynamic Volume + // if Provided ... + if (eaUseDynamicVolume && + eaDynamicVolumeStep > 0 && + eaDynamicVolumeBalanceFactor > 0) + { + // + double dVolume = eaTrader.GetDynamicVolume( + signal.symbol, + eaDynamicVolumeBalanceFactor, + eaDynamicVolumeStep // + ); + + // + if (dVolume > 0) + { + signal.volume = dVolume; + } + + // + eaTradeHandler.UpdateSignal(signal); + } + + // + // Since Signal Filtering done based on + // Strategy and it's not related to Public + // TradeHandler for Seperation of Concern issue, + // we do this here ... + XCHCHEStartegyConditionsParser parser; + bool isFiltered = parser.IsFiltered( + signal, + conditions // + ); + if (isFiltered) + { + // + eaTradeHandler.RemoveSignal(signal); + return; + } + + // // + // // Here we Can Increase Signal Volume if + // // it is not force Filtered ... + // bool isForceFiltered = parser.IsFiltered( + // signal, + // conditions, + // true // + // ); + // if (!isForceFiltered) + // { + // // + // // TODO: + // // Implement Strong Signals Conditions + // // Senarios ... + // forceSignalsCount++; + + // // + // // Alert Froce Strong Signals + // // if Provided ... + // if (eaAlertStrongSignals) + // { + // // + // string msg = "Foce Strong " + (IsLong(signal.type) ? "Long" : "Short") + " Signal Recieved: (" + signal.provider + "," + signal.symbol + "," + ToString(signal.period) + ") ..."; + // eaAlert.Alert(msg); + // } + // } + + // + // Attach Conditions Summary to Signal ... + string conditionsSummary = conditions.GenerateSummary( + false, + false, + true, + false // + ); + + // + signal.conditions = parser.GenerateSignalConditions( + signal, + conditions // + ); // conditionsSummary; + + // + // Execute Signal Using Trade Handler ... + ENUM_X_SIGNAL_EXECUTION_RESULT state; + bool isExecuted = eaTradeHandler.ExecuteSignal( + signal, + state // + ); +} + +// +// Handle StopLoss Triggered Positions ... +void OnStopLossTriggered(const XDeal &deal) +{ + // + // Finish ... + eaTradeHandler.Finish(deal); + + // + ReportBalance(); +} + +// +// Handle Take Profit Triggered Positions ... +void OnTakeProfitTriggered(const XDeal &deal) +{ + // + // Finish ... + eaTradeHandler.Finish(deal); + + // + ReportBalance(); +} + +// +// Handle Force Close a Position ... +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + // + // Finish ... + eaTradeHandler.Finish( + ticket, + position, + comment // + ); + + // + ReportBalance(); +} + +// +// Report Account Balance ... +void ReportBalance() +{ + // + if (!IsRunningOnTestMode()) + { + return; + } + + // + string msg = "Balance: " + ToString(eaTrader.mAccount.GetBalance()); + eaAlert.Log(msg); +} + +// \ No newline at end of file