diff --git a/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 b/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 new file mode 100644 index 00000000..41328ec1 --- /dev/null +++ b/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 @@ -0,0 +1,1053 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: XBackTester +// Description: a Backtest Tools Strategy Tester +// +// 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 XBackTester" +#property icon "../Images/SaherElm_Logo_Color.ico" +#property strict + +// +#define ShortName "XBackTester" + +// +// Imports ... +#include "../Classes/x-saherelm.x-backtester.expert.class.mq5" +#include "../Classes/x-saherelm.x-market.pattern.class.mq5" +#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../Helpers/x-saherelm.xom1.helper.mq5" + +// +// Definitions ... + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +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 + +// +// Indicator Inputs ... +// +input group "Calculation"; + +// +// Short ... +input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period +input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period + +// +// Medium ... +input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period +input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period + +// +// Long ... +input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period +input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period + +// +// Hind ... +input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period +input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period + +// +// PV ... +input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method +input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method + +// +// Others ... +input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level +input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Middle Zone Level +input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level +input double sarStep = 0.02; // SAR Step +input double sarMax = 0.2; // SAR Maximum +input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method +input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To +input int maFastLength = 7; // Fast MA Length +input int maSlowLength = 20; // Slow MA Length +input int zigzagDepth = 12; // ZigZag Depth +input int zigzagDeviation = 5; // ZigZag Deviation +input int zigzagBackStep = 3; // ZigZag Back Step +input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode +input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode + +// +input group "Bar Timer"; +input int barTimeFontSize = 10; // Font Size +input string barTimeFont = "Arial"; // Font +input color barTimeColor = clrYellow; // Text Color +input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position + +// +// Presentation ... +input group "Presentation"; +input bool showPV = true; // Show PV +input bool showSAR = true; // Show Sar +input bool showMAFast = true; // Show MA Fast +input bool showMASlow = true; // Show MA Slow +input bool showBarTime = true; // Show Bar Time +input bool showZigZag = true; // Show ZigZag +input bool showFiboZone = true; // Show Fibo Zone + +// +input int startCalculationForLastBars = 1500; // Calculate Last n Bars + +// +input int sarArrowCode = 159; // Parabolic Sar Arrow Code +input int peakArrowCode = 159; // Peaks Arrow Code +input int valeArrowCode = 159; // Vales Arrow Code + +// +// Define Local Variables ... + +// +string eaLogTag; // EA Log Prefix ... +XCBackTesterEA *eaExpert; // EA Expert ... +XCMarketPatternDetector *eaPatternDetector; // EA Pattern Detector ... + +// +XCPOIDrawer *eaDrawer; // Ea POI Drawer ... +CArrayObj draws; // Drawn Objects ... + +// +XBarTracker eaBarTracker; // EA Bar Traker ... + +// +int eaHandler = INVALID_HANDLE; // Indicator Handler ... +int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ... + +// +ENUM_X_DIRECTION trendDir = X_DIRECTION_NONE; + +// +// Define Indicators Here ... + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Preparing Tags ... + string eaTag = + (IsValid(eaLogSuffix) + ? eaLogSuffix + "_" + : "") + + ShortName; + + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) + { + return INIT_FAILED; + } + + // + // Configure EA Expert Class ... + eaExpert = new XCBackTesterEA(); + + // + // Symbol / Period ... + eaExpert.symbol = _Symbol; + eaExpert.period = _Period; + + // + // Common ... + eaExpert.eaMagicNumber = eaMagicNumber; + eaExpert.eaSlippage = eaSlippage; + eaExpert.eaLogSuffix = eaTag; + + // + // Alert ... + eaExpert.eaEnableAlerts = eaEnableAlerts; + eaExpert.eaLogAlerts = eaLogAlerts; + eaExpert.eaMailAlerts = eaMailAlerts; + eaExpert.eaPushAlerts = eaPushAlerts; + eaExpert.eaTerminalAlerts = eaTerminalAlerts; + + // + // Attach Event Handlers ... + eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged); + eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered); + eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged); + eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaExpert.AddOnModifyPositionEventHandler(OnPositionModified); + eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged); + eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged); + eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed); + + // + // Configure Other Requirements ... + eaExpert.volume = 0.01; + eaExpert.riskInPoint = 200; + eaExpert.allowedTPSLStep = 10; + eaExpert.riskToRewardRatio = 2; + eaExpert.minAllowedRiskInPoint = 20; + + // + // Try to Initialize eaExpert ... + bool isInited = eaExpert.HandleOnInit(); + if (!isInited) + { + // + Print(ShortName, ": Initialization Failed ..."); + return INIT_FAILED; + } + + // + // Initial Indicator Handler ... + eaHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xfima", + "", // Calculation ... + scMethod, + scPeriod, + mcMethod, + mcPeriod, + lcMethod, + lcPeriod, + hcMethod, + hcPeriod, + upperMode, + lowerMode, + fiboUpperZoneLevel, + fiboMiddleZoneLevel, + fiboLowerZoneLevel, + sarStep, + sarMax, + maMethod, + maAppliedTo, + maFastLength, + maSlowLength, + zigzagDepth, + zigzagDeviation, + zigzagBackStep, + zigzagUppersMode, + zigzagLowersMode, + "", // Presentation ... + showPV, + showSAR, + showMAFast, + showMASlow, + showZigZag, + showFiboZone, + startCalculationForLastBars, + sarArrowCode, + peakArrowCode, + valeArrowCode + // + ); + isInited = eaHandler != INVALID_HANDLE; + if (!isInited) + { + // + Print(ShortName, ": Initialization Failed ..."); + return INIT_FAILED; + } + + // + // Initialize Candle Timer Handler ... + eaCTHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.x121.xct", + // + // Inputs ... + barTimeFontSize, // Font Size ... + barTimeFont, // Font ... + barTimeColor, // Text Color ... + barTimeCorner, // Text Position ... + // + // Presentation ... + "", + showBarTime // Show Candle Time + // + ); + isInited = eaCTHandler != INVALID_HANDLE; + if (!isInited) + { + // + Print(ShortName, ": Initialization Failed ..."); + return INIT_FAILED; + } + + // + // Initialize Bar Tracker ... + isInited = eaBarTracker.Init( + _Symbol, + _Period // + ); + if (!isInited) + { + // + Print(ShortName, ": Initialization Failed ..."); + return INIT_FAILED; + } + + // + // Instantiate Market Pattern Detector ... + eaPatternDetector = new XCMarketPatternDetector(); + + // + // Instantiate POI Drawer ... + eaDrawer = new XCPOIDrawer(); + + // + Print(ShortName, ": Initialized Successfully ..."); + 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 + + // + // Destroy Timer ... + eaExpert.HandleOnDeInit(); + + // + // De Init Indicator ... + IndicatorRelease(eaHandler); + + // + eaBarTracker.Clean(); + + // + delete eaDrawer; + ZeroMemory(eaDrawer); + + // + delete eaPatternDetector; + ZeroMemory(eaPatternDetector); + + // + delete eaExpert; + ZeroMemory(eaExpert); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + eaExpert.HandleOnTick(); + + // + DetectPatterns(); +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaExpert.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + eaExpert.HandleOnTimer(); +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ + eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam); +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 && + // + // Indicator Inputs ... + // + // MA ... + maFastLength >= 2 && + maSlowLength >= 2 && + maSlowLength > maFastLength && + // + // SAR ... + sarMax > 0 && + sarStep > 0 && + sarMax > sarStep && + // + // CYCLES ... + (IsValid(scMethod, scPeriod) && + IsValid(mcMethod, mcPeriod) && + IsValid(lcMethod, lcPeriod) && + IsValid(hcMethod, hcPeriod)) && + // + // ZIGZAG ... + zigzagDepth > 0 && + zigzagDeviation > 0 && + zigzagBackStep > 0 && + // + // Validate Upper Mode Detection ... + IsXValid(zigzagUppersMode) && + // + // Validate Lower Mode Detection ... + IsXValid(zigzagLowersMode) + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ + // + // TODO: Use This ... + // EventKillTimer(); +} + +// +// Trade Event Handlers ... + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ + eaExpert.HandleOnStopLossTriggered(deal); +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ + eaExpert.HandleOnTakeProfitTriggered(deal); +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: ULONG ... + * @param position: XPosition instance ... + * @param comment: String ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + // + eaExpert.HandleOnPositionForceClosed( + ticket, + position, + comment // + ); +} + +/** + * Handle Deals Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnDealsChanged(int count) +{ + eaExpert.HandleOnDealsChanged(count); +} + +/** + * Handle Orders Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnOrdersChanged(int count) +{ + eaExpert.HandleOnOrdersChanged(count); +} + +/** + * Handle Positions Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnPositionsChanged(int count) +{ + eaExpert.HandleOnPositionsChanged(count); +} + +/** + * Handle Position Modified ... + * + * @param ticket: ulong, Position Ticket ... + * @param profit: double, Position Profit ... + * @param comment: string, Comment ... + */ +void OnPositionModified( + const ulong ticket, + const double profit, + const string comment // +) +{ + // + eaExpert.HandleOnPositionModified( + ticket, + profit, + comment // + ); +} + +/** + * Handle Position Partial Closed ... + * + * @param ticket: ulong, Position Ticket ... + * @param profit: double, Position Profit ... + * @param comment: string, Comment ... + */ +void OnPositionPartialClosed( + const ulong ticket, + const double profit, + const string comment // +) +{ + // + eaExpert.HandleOnPositionPartialClosed( + ticket, + profit, + comment // + ); +} + +/** + * Handle Trade State Changed ... + * + * @param state: XOnTradeHandlerState instance ... + */ +void OnTradeStateChanged(const XOnTradeHandlerState &state) +{ + eaExpert.HandleOnTradeStateChanged(state); +} + +/** + * Check Market Conditions for Pattern Detection ... + */ +void DetectPatterns() +{ + // + bool isNewBar = eaBarTracker.IsNewBar(); + if (!isNewBar) + { + return; + } + + // + // Initialize 1 Indexed Bar ... + XOHCL cBar; + bool has = cBar.Init( + _Symbol, + _Period, + 1 // + ); + if (!has) + { + return; + } + + // + // Do Analysis ... + + // + ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; + + // + // Define Detection Flags ... + + // + bool detectPinned = false; + bool detectMomentum = false; + bool detectEngulfed = false; + bool detectTrueGaped = false; + + // + bool detectStarPattern = false; + bool detectFlagPattern = false; + bool detectRisingPattern = false; + bool detectPiercingPattern = false; + bool detectSignalKeyBarPattern = false; + + // + bool detectSwingTrend = false; + bool detectSwingTrendBreakes = false; + + // + bool detectSupports = false; + bool detectResistance = false; + + // + // Checking Momentum Bar ... + if (detectMomentum) + { + // + bool isMomentum = eaPatternDetector.IsMomentumBar( + cBar, + iDir // + ); + bool isBullishMomentum = isMomentum && + IsSpecifiedBullish(iDir); + bool isBearishMomentum = isMomentum && + IsSpecifiedBearish(iDir); + if (isMomentum) + { + Print(ToXString(iDir), " Momentum Bar: ", cBar.time); + } + } + + // + // Checking Engulfed Bar ... + if (detectEngulfed) + { + // + bool isEngulfed = eaPatternDetector.IsEngulfedBar( + cBar, + iDir // + ); + bool isBullishEngulfed = isEngulfed && + IsSpecifiedBullish(iDir); + bool isBearishEngulfed = isEngulfed && + IsSpecifiedBearish(iDir); + if (isEngulfed) + { + Print(ToXString(iDir), " Engulfed Bar: ", cBar.time); + } + } + + // + // Checking TruGaped Bar ... + if (detectTrueGaped) + { + // + bool isTrueGaped = eaPatternDetector.IsTrueGapedBar( + cBar, + iDir // + ); + bool isBullishTrueGaped = isTrueGaped && + IsSpecifiedBullish(iDir); + bool isBearishTrueGaped = isTrueGaped && + IsSpecifiedBearish(iDir); + if (isTrueGaped) + { + Print(ToXString(iDir), " TrueGapped Bar: ", cBar.time); + } + } + + // + // Checking Pinned Bar ... + if (detectPinned) + { + bool isPinned = eaPatternDetector.IsPinnedBar( + cBar, + iDir // + ); + bool isBullishPinned = isPinned && + IsSpecifiedBullish(iDir); + bool isBearishPinned = isPinned && + IsSpecifiedBearish(iDir); + if (isPinned) + { + Print(ToXString(iDir), " Pinned Bar: ", cBar.time); + } + } + + // + // Checking Star Pattern ... + if (detectStarPattern) + { + bool isStarPattern = eaPatternDetector.IsStartPattern( + cBar, + iDir // + ); + bool isBullishStarPattern = isStarPattern && + IsSpecifiedBullish(iDir); + bool isBearishStarPattern = isStarPattern && + IsSpecifiedBearish(iDir); + if (isStarPattern) + { + Print(ToXString(iDir), " Star Pattern: ", cBar.time); + } + } + + // + // Checking Piercing Pattern ... + if (detectPiercingPattern) + { + // + bool isPiercingPattern = eaPatternDetector.IsPiercingPattern( + cBar, + iDir // + ); + bool isBullishPiercingPattern = isPiercingPattern && + IsSpecifiedBullish(iDir); + bool isBearishPiercingPattern = isPiercingPattern && + IsSpecifiedBearish(iDir); + if (isPiercingPattern) + { + Print(ToXString(iDir), " Piercing Pattern: ", cBar.time); + } + } + + // + // Checking Rising Pattern ... + if (detectRisingPattern) + { + // + bool isRisingPattern = eaPatternDetector.IsRisingPattern( + cBar, + iDir // + ); + bool isBullishRisingPattern = isRisingPattern && + IsSpecifiedBullish(iDir); + bool isBearishRisingPattern = isRisingPattern && + IsSpecifiedBearish(iDir); + if (isRisingPattern) + { + Print(ToXString(iDir), " Rising Pattern: ", cBar.time); + } + } + + // + // Checking Flag Pattern ... + if (detectFlagPattern) + { + // + XOHCL swingBar; + bool isFlagPattern = eaPatternDetector.IsFlagPattern( + cBar, + iDir, + swingBar // + ); + bool isBullishFlagPattern = isFlagPattern && + IsSpecifiedBullish(iDir); + bool isBearishFlagPattern = isFlagPattern && + IsSpecifiedBearish(iDir); + if (isFlagPattern) + { + Print(ToXString(iDir), " Flag Pattern: ", cBar.time, ", Swing: ", swingBar.time); + } + swingBar.Clean(); + } + + // + // Detect SignalKey Bar Pattern ... + if (detectSignalKeyBarPattern) + { + // + bool isSignalKeyBar = eaPatternDetector.IsSignalKeyBarPattern( + cBar, + iDir // + ); + bool isBullishSignalKeyBar = isSignalKeyBar && + IsSpecifiedBullish(iDir); + bool isBearishSignalKeyBar = isSignalKeyBar && + IsSpecifiedBearish(iDir); + if (isSignalKeyBar) + { + Print(ToXString(iDir), " SignalKey Bar Pattern: ", cBar.time); + } + } + + // + // Detect Swing Trend ... + if (detectSwingTrend) + { + // + XOHCL swings[]; + bool hasSwingTrend = eaPatternDetector.HasSwingTrend( + cBar, + iDir, + swings // + ); + bool hasBullishSwingTrend = hasSwingTrend && + IsSpecifiedBullish(iDir); + bool hasBearishSwingTrend = hasSwingTrend && + IsSpecifiedBearish(iDir); + if (hasSwingTrend) + { + // + Print(ToXString(iDir), " Swing Trend: ", cBar.time); + + // + CChartObjectTrend *iObj; + has = eaDrawer.DrawSwingTrend( + swings, + iDir, + iObj, + true // Ray Right ... + ); + if (has) + { + draws.Add(iObj); + } + } + SpecifiedClean(swings); + } + + // + // Swing Trend Breakes ... + if (detectSwingTrendBreakes) + { + // + XOHCL swings[]; + bool hasSwingTrend = eaPatternDetector.HasSwingTrend( + cBar, + iDir, + swings // + ); + bool hasBullishSwingTrend = hasSwingTrend && + IsSpecifiedBullish(iDir); + bool hasBearishSwingTrend = hasSwingTrend && + IsSpecifiedBearish(iDir); + if (hasSwingTrend) + { + // + if (!HasDirection(trendDir)) + { + trendDir = iDir; + } + } + + // + // Breaked Detection ... + if (trendDir != iDir) + { + // + Print("Trend Dir Breaked to: ", ToXString(iDir)); + trendDir = iDir; + } + + // + SpecifiedClean(swings); + } + + // + // Detect Supports ... + if (detectSupports) + { + // + XOHCL support; + bool hasSupport = eaPatternDetector.HasSupport( + cBar, + support // + ); + if (hasSupport) + { + // + XBoxZone supportBox; + has = ToSupportBox(support, supportBox); + if (has) + { + // + // Draw Box ... + XCBoxObject *iObj; + has = eaDrawer.DrawBox( + supportBox, + iObj // + ); + if (has) + { + // + // Apply Style ... + eaDrawer.ApplyStyle( + iObj, + eaDrawer.boxBullishStyle // + ); + + // + draws.Add(iObj); + } + + // + ZeroMemory(iObj); + } + + // + supportBox.Clean(); + } + support.Clean(); + } + + // + // Detect Resistance ... + if (detectResistance) + { + // + XOHCL resistance; + bool hasResistance = eaPatternDetector.HasResistance( + cBar, + resistance // + ); + if (hasResistance) + { + // + XBoxZone resistanceBox; + has = ToResistanceBox(resistance, resistanceBox); + if (has) + { + // + // Draw Box ... + XCBoxObject *iObj; + has = eaDrawer.DrawBox( + resistanceBox, + iObj // + ); + if (has) + { + // + // Apply Style ... + eaDrawer.ApplyStyle( + iObj, + eaDrawer.boxBearishStyle // + ); + + // + draws.Add(iObj); + } + + // + ZeroMemory(iObj); + } + + // + resistanceBox.Clean(); + } + resistance.Clean(); + } + + // + cBar.Clean(); +} + +// \ No newline at end of file diff --git a/Experts/x-saherelm.xfima.backtester.ea.mq5 b/Experts/x-saherelm.xfima.backtester.ea.mq5 index 41328ec1..0e980bff 100644 --- a/Experts/x-saherelm.xfima.backtester.ea.mq5 +++ b/Experts/x-saherelm.xfima.backtester.ea.mq5 @@ -1,36 +1,30 @@ /////////////////////////////////////////////////////// // -// SaherElm IT Center XTest MQL5 Expert Advisor +// SaherElm IT Center MQL5 Expert Advisor // ------------------------------------------------- -// Name: XBackTester -// Description: a Backtest Tools Strategy Tester +// Name: XFIMAEA +// Description: Base Expert Advisor as Template ... // // 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 XBackTester" #property icon "../Images/SaherElm_Logo_Color.ico" +#property description "SaherElm XFIMA Expert Advisor" #property strict // -#define ShortName "XBackTester" +#define ShortName "XFIMAEA" // -// Imports ... -#include "../Classes/x-saherelm.x-backtester.expert.class.mq5" -#include "../Classes/x-saherelm.x-market.pattern.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Helpers/x-saherelm.xom1.helper.mq5" - -// -// Definitions ... +// Importts ... +#include "../XFIMA/Classes/x-saherelm.xfima.expert.class.mq5" // // Inputs ... @@ -38,124 +32,111 @@ // // Common ... input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix +input long eaMagicNumber = 1694056; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Symbols +// [ +// Name| +// Symbol| +// period| +// (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)| +// maxAllowedSpread| +// maxAllowedPosition| +// ( +// restrictionsPeriod, +// restrictionsMultiplier, +// maxAllowedTPs, +// maxAllowedSLs, +// maxAllowedTrades, +// closeAllOpenTradesAt +// ) +// ] +// +// +// [XFIMA1|EURUSDb|M5||25.0|5|] +// [XFIMA1|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,1,0,2,0)] +// [XFIMA1|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,3,0,2,0)] +input string eaSymbolConfiguration = "[XFIMA1|EURUSDb|M5||25.0|5|]"; // Symbol Configurations + +// +// Management ... +input group "Management"; +input bool eaAllowGuards = false; // Allow Guards +input bool eaAllowTrade = true; // Allow Trade on Signals +input bool eaAllowLongs = true; // Allow Long Trades +input bool eaAllowShorts = true; // Allow Short Trades +input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade + +// +// Volume ... +input group "Volume"; +input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type +input double eaStaticVoluem = 0.0; // Static Volume +input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume +input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing +input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade +input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade +input double eaConstantBalance = 1000.0; // Constant Balance for Calculations // // Alert ... -// Here we Provider All Requirements for -// Configuring Alert Provider ... input group "Alert"; input bool eaEnableAlerts = true; // Enable Alerts +input bool eaSaveAlerts = true; // Save Alerts input bool eaLogAlerts = true; // Log Alerts input bool eaMailAlerts = false; // Mail Alerts -input bool eaPushAlerts = false; // Push Alerts +input bool eaPushAlerts = true; // Push Alerts input bool eaTerminalAlerts = false; // Terminal Alerts // -// Indicator Inputs ... -// -input group "Calculation"; +// Reports ... +input group "Reports"; +input bool eaReportNewMonths = false; // Report New Month +input bool eaReportNewWeeks = false; // Report New Weeks +input bool eaReportNewDays = true; // Report New Days +input bool eaReportNewHours = false; // Report New Hours +input bool eaReportTrades = true; // Report Trades +input bool eaReportSignals = true; // Report Signals +input bool eaReportRestrictions = true; // Report Restrictions +input bool eaReportProtector = true; // Report Protector Actions +input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished // -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period +// Collector ... +input group "Collector"; +input bool eaSaveTrades = true; // Save Trades +input bool eaSaveSignals = true; // Save Signals +input bool eaSaveWins = true; // Save Winning Conditions +input bool eaSaveLosts = true; // Save Lost Conditions +input bool eaSaveRestrictions = true; // Save Restriction Reports // -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period +// Management Panel ... +input group "Management Panel"; +input bool eaShowPanel = false; // Show Management Panel +double eaPanelAllowedTPSLStep = 10; // Value for Change TP/SL in Each Step +double eaPanelMinAllowedRiskInPoint = 20; // Min Allowed Risk in Point +double eaPanelRiskInPoint = 50; // Risk in Point per Trades +double eaPanelRiskToRewardRatio = 2.0; // Risk To Reward per Trades +double eaPanelVolume = X_MIN_VOLUME; // Default volume Per Trade // -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period +// Variables ... // -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// PV ... -input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method - -// -// Others ... -input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Middle Zone Level -input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level -input double sarStep = 0.02; // SAR Step -input double sarMax = 0.2; // SAR Maximum -input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To -input int maFastLength = 7; // Fast MA Length -input int maSlowLength = 20; // Slow MA Length -input int zigzagDepth = 12; // ZigZag Depth -input int zigzagDeviation = 5; // ZigZag Deviation -input int zigzagBackStep = 3; // ZigZag Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - -// -input group "Bar Timer"; -input int barTimeFontSize = 10; // Font Size -input string barTimeFont = "Arial"; // Font -input color barTimeColor = clrYellow; // Text Color -input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show PV -input bool showSAR = true; // Show Sar -input bool showMAFast = true; // Show MA Fast -input bool showMASlow = true; // Show MA Slow -input bool showBarTime = true; // Show Bar Time -input bool showZigZag = true; // Show ZigZag -input bool showFiboZone = true; // Show Fibo Zone - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -input int sarArrowCode = 159; // Parabolic Sar Arrow Code -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Define Local Variables ... - -// -string eaLogTag; // EA Log Prefix ... -XCBackTesterEA *eaExpert; // EA Expert ... -XCMarketPatternDetector *eaPatternDetector; // EA Pattern Detector ... - -// -XCPOIDrawer *eaDrawer; // Ea POI Drawer ... -CArrayObj draws; // Drawn Objects ... - -// -XBarTracker eaBarTracker; // EA Bar Traker ... - -// -int eaHandler = INVALID_HANDLE; // Indicator Handler ... -int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ... - -// -ENUM_X_DIRECTION trendDir = X_DIRECTION_NONE; - -// -// Define Indicators Here ... +XCXFIMAExpret *eaExpert; // // Event Handlers ... -// -// Initialization ... +/** + * Initialize EA Process ... + * + * @return ( int ) + */ int OnInit() { // @@ -167,7 +148,8 @@ int OnInit() ShortName; // - // Validate Inputs and Required Parameters + // Validate Inputs and Required Parameters ... + // for EA to Works fine ... if (!ValidateInputs()) { @@ -183,12 +165,10 @@ int OnInit() // // Configure EA Expert Class ... - eaExpert = new XCBackTesterEA(); + eaExpert = new XCXFIMAExpret(); // - // Symbol / Period ... - eaExpert.symbol = _Symbol; - eaExpert.period = _Period; + // Setting All Inputs to Expert Adviser Class ... // // Common ... @@ -196,20 +176,76 @@ int OnInit() eaExpert.eaSlippage = eaSlippage; eaExpert.eaLogSuffix = eaTag; + // + // Symbols ... + eaExpert.eaSymbolConfiguration = eaSymbolConfiguration; + + // + // Management ... + eaExpert.eaAllowGuards = eaAllowGuards; + eaExpert.eaAllowTrade = eaAllowTrade; + eaExpert.eaAllowLongs = eaAllowLongs; + eaExpert.eaAllowShorts = eaAllowShorts; + eaExpert.eaMaxAllowedDrawdownFactor = eaMaxAllowedDrawdownFactor; + + // + // Volume ... + eaExpert.eaVolumeSelect = eaVolumeSelect; + eaExpert.eaStaticVoluem = eaStaticVoluem; + eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance; + eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume; + eaExpert.eaConstantRiskBalance = eaConstantRiskBalance; + eaExpert.eaConstantPercent = eaConstantPercent; + eaExpert.eaConstantBalance = eaConstantBalance; + // // Alert ... eaExpert.eaEnableAlerts = eaEnableAlerts; + eaExpert.eaSaveAlerts = eaSaveAlerts; eaExpert.eaLogAlerts = eaLogAlerts; eaExpert.eaMailAlerts = eaMailAlerts; eaExpert.eaPushAlerts = eaPushAlerts; eaExpert.eaTerminalAlerts = eaTerminalAlerts; + // + // Reports ... + eaExpert.eaReportNewMonths = eaReportNewMonths; + eaExpert.eaReportNewWeeks = eaReportNewWeeks; + eaExpert.eaReportNewDays = eaReportNewDays; + eaExpert.eaReportNewHours = eaReportNewHours; + eaExpert.eaReportTrades = eaReportTrades; + eaExpert.eaReportSignals = eaReportSignals; + eaExpert.eaReportRestrictions = eaReportRestrictions; + eaExpert.eaReportProtector = eaReportProtector; + eaExpert.eaReportAfterTradesBalance = eaReportAfterTradesBalance; + + // + // Collector ... + eaExpert.eaSaveTrades = eaSaveTrades; + eaExpert.eaSaveSignals = eaSaveSignals; + eaExpert.eaSaveWins = eaSaveWins; + eaExpert.eaSaveLosts = eaSaveLosts; + eaExpert.eaSaveRestrictions = eaSaveRestrictions; + + // + // Management Panel ... + eaExpert.eaShowPanel = eaShowPanel; + eaExpert.eaPanelAllowedTPSLStep = eaPanelAllowedTPSLStep; + eaExpert.eaPanelMinAllowedRiskInPoint = eaPanelMinAllowedRiskInPoint; + eaExpert.eaPanelRiskInPoint = eaPanelRiskInPoint; + eaExpert.eaPanelRiskToRewardRatio = eaPanelRiskToRewardRatio; + eaExpert.eaPanelVolume = eaPanelVolume; + // // Attach Event Handlers ... + eaExpert.AddOnSignalEventHandler(OnSignalTriggered); + eaExpert.onGuardedEventHandler = OnGuardedTriggered; eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged); eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered); eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged); + eaExpert.canAnalyseEventHandler = CanAnalyseEventTriggered; eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaExpert.checkForGuardEventHandler = CheckForGuardTriggered; eaExpert.AddOnModifyPositionEventHandler(OnPositionModified); eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged); eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged); @@ -217,12 +253,7 @@ int OnInit() eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed); // - // Configure Other Requirements ... - eaExpert.volume = 0.01; - eaExpert.riskInPoint = 200; - eaExpert.allowedTPSLStep = 10; - eaExpert.riskToRewardRatio = 2; - eaExpert.minAllowedRiskInPoint = 20; + // TODO: Attach other Requirements if necessary ... // // Try to Initialize eaExpert ... @@ -234,177 +265,76 @@ int OnInit() return INIT_FAILED; } - // - // Initial Indicator Handler ... - eaHandler = iCustom( - _Symbol, - _Period, - "x-saherelm.xfima", - "", // Calculation ... - scMethod, - scPeriod, - mcMethod, - mcPeriod, - lcMethod, - lcPeriod, - hcMethod, - hcPeriod, - upperMode, - lowerMode, - fiboUpperZoneLevel, - fiboMiddleZoneLevel, - fiboLowerZoneLevel, - sarStep, - sarMax, - maMethod, - maAppliedTo, - maFastLength, - maSlowLength, - zigzagDepth, - zigzagDeviation, - zigzagBackStep, - zigzagUppersMode, - zigzagLowersMode, - "", // Presentation ... - showPV, - showSAR, - showMAFast, - showMASlow, - showZigZag, - showFiboZone, - startCalculationForLastBars, - sarArrowCode, - peakArrowCode, - valeArrowCode - // - ); - isInited = eaHandler != INVALID_HANDLE; - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Candle Timer Handler ... - eaCTHandler = iCustom( - _Symbol, - _Period, - "x-saherelm.x121.xct", - // - // Inputs ... - barTimeFontSize, // Font Size ... - barTimeFont, // Font ... - barTimeColor, // Text Color ... - barTimeCorner, // Text Position ... - // - // Presentation ... - "", - showBarTime // Show Candle Time - // - ); - isInited = eaCTHandler != INVALID_HANDLE; - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Bar Tracker ... - isInited = eaBarTracker.Init( - _Symbol, - _Period // - ); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Instantiate Market Pattern Detector ... - eaPatternDetector = new XCMarketPatternDetector(); - - // - // Instantiate POI Drawer ... - eaDrawer = new XCPOIDrawer(); - // Print(ShortName, ": Initialized Successfully ..."); return INIT_SUCCEEDED; } -// -// DeInitialization ... +/** + * De Initialize Expert ... + * + * @param reason: int, DeInitialization 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 + * + */ 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 + // Destroy Timer ... + // If Initialized ... // - // Destroy Timer ... + // De Init Expert Class Instance ... eaExpert.HandleOnDeInit(); // - // De Init Indicator ... - IndicatorRelease(eaHandler); - - // - eaBarTracker.Clean(); - - // - delete eaDrawer; - ZeroMemory(eaDrawer); - - // - delete eaPatternDetector; - ZeroMemory(eaPatternDetector); - - // + // Cleanup Resources ... delete eaExpert; ZeroMemory(eaExpert); } -// -// On Tick Handler ... +/** + * Handle Tick for Processing ... + */ void OnTick() { - // eaExpert.HandleOnTick(); - - // - DetectPatterns(); } -// -// Handle On Trade Event ... +/** + * Handle On Trade Processing ... + */ void OnTrade() { eaExpert.HandleOnTrade(); } -// -// On Timer ... +/** + * Handle On Timer Processing ... + */ void OnTimer() { eaExpert.HandleOnTimer(); } -// -// Chart Event Handler ... +/** + * Handle On Chart Event Processing ... + + * @param id: int, Specified Event ID ... + * @param lparam: long, type event parameter + * @param dparam: double, type event parameter + * @param sparam: string, type event parameter + */ void OnChartEvent( const int id, const long &lparam, @@ -416,118 +346,65 @@ void OnChartEvent( } // -// Custom Functions ... +// Event Listeners ... /** - * Validate all Inputs of Expert Adviser ... + * Handle CanAnalyse Event Triggered ... + * + * @param symbol: Symbol ... + * @param period: Period ... + * @param time: Analysing Time ... * * @return ( bool ) */ -bool ValidateInputs() +bool CanAnalyseEventTriggered( + string symbol, + ENUM_TIMEFRAMES period, + datetime time // +) { - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - eaSlippage > 0 && - eaMagicNumber > 0 && - // - // Indicator Inputs ... - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // + return eaExpert.HandleCanAnalyseEventTriggered( + symbol, + period, + time // ); - if (!isCommonValid) - { - // - errMessage += "common configurations error;" + "\n"; - } - - // - result = - // - // Common ... - isCommonValid && - // - // Otere ... - true - // - ; - - // - if (!result) - { - // - // Since here Logger not Initiallized, we Use Raw Print Command ... - Print(ShortName + " Errors: \n", errMessage); - } - - // - return result; } /** - * Initialize Timer ... + * Check For Guard Event Handler ... * - * @return ( bool ) + * @param guards: XGuard[] + * + * @return ( int ) */ -bool InitTimer() +int CheckForGuardTriggered(XGuard &guards[]) { - // - bool result = false; - - // - // TODO: Initialize Timer if necessary ... - // result = EventSetTimer(1); - // result = EventSetMillisecondTimer(100); - result = true; - - // - return result; + return eaExpert.CheckForGuardTriggered(guards); } /** - * Destroy Timer ... + * Handle Guard Events ... + * + * @param action: ENUM_X_GUARD_ACTIONS + * @param positions: XPosition[] */ -void DestroyTimer() +void OnGuardedTriggered( + ENUM_X_GUARD_ACTIONS action, + XPosition &positions[] // +) { - // - // TODO: Use This ... - // EventKillTimer(); + eaExpert.OnGuardedTriggered(action, positions); } -// -// Trade Event Handlers ... +/** + * Trigger OnSignal Event ... + * + * @param signal: XSignal + */ +void OnSignalTriggered(XSignal &signal) +{ + eaExpert.HandleOnSignalTriggered(signal); +} /** * Handle StopLoss Triggered Positions ... @@ -652,402 +529,86 @@ void OnTradeStateChanged(const XOnTradeHandlerState &state) eaExpert.HandleOnTradeStateChanged(state); } +// +// Custom Functions ... + /** - * Check Market Conditions for Pattern Detection ... + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) */ -void DetectPatterns() +bool ValidateInputs() { // - bool isNewBar = eaBarTracker.IsNewBar(); - if (!isNewBar) - { - return; - } + bool result = false; // - // Initialize 1 Indexed Bar ... - XOHCL cBar; - bool has = cBar.Init( - _Symbol, - _Period, - 1 // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // ); - if (!has) - { - return; - } - - // - // Do Analysis ... - - // - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Define Detection Flags ... - - // - bool detectPinned = false; - bool detectMomentum = false; - bool detectEngulfed = false; - bool detectTrueGaped = false; - - // - bool detectStarPattern = false; - bool detectFlagPattern = false; - bool detectRisingPattern = false; - bool detectPiercingPattern = false; - bool detectSignalKeyBarPattern = false; - - // - bool detectSwingTrend = false; - bool detectSwingTrendBreakes = false; - - // - bool detectSupports = false; - bool detectResistance = false; - - // - // Checking Momentum Bar ... - if (detectMomentum) + if (!isCommonValid) { // - bool isMomentum = eaPatternDetector.IsMomentumBar( - cBar, - iDir // - ); - bool isBullishMomentum = isMomentum && - IsSpecifiedBullish(iDir); - bool isBearishMomentum = isMomentum && - IsSpecifiedBearish(iDir); - if (isMomentum) - { - Print(ToXString(iDir), " Momentum Bar: ", cBar.time); - } + errMessage += "common configurations error;" + "\n"; } // - // Checking Engulfed Bar ... - if (detectEngulfed) + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) { // - bool isEngulfed = eaPatternDetector.IsEngulfedBar( - cBar, - iDir // - ); - bool isBullishEngulfed = isEngulfed && - IsSpecifiedBullish(iDir); - bool isBearishEngulfed = isEngulfed && - IsSpecifiedBearish(iDir); - if (isEngulfed) - { - Print(ToXString(iDir), " Engulfed Bar: ", cBar.time); - } + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); } // - // Checking TruGaped Bar ... - if (detectTrueGaped) - { - // - bool isTrueGaped = eaPatternDetector.IsTrueGapedBar( - cBar, - iDir // - ); - bool isBullishTrueGaped = isTrueGaped && - IsSpecifiedBullish(iDir); - bool isBearishTrueGaped = isTrueGaped && - IsSpecifiedBearish(iDir); - if (isTrueGaped) - { - Print(ToXString(iDir), " TrueGapped Bar: ", cBar.time); - } - } + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; // - // Checking Pinned Bar ... - if (detectPinned) - { - bool isPinned = eaPatternDetector.IsPinnedBar( - cBar, - iDir // - ); - bool isBullishPinned = isPinned && - IsSpecifiedBullish(iDir); - bool isBearishPinned = isPinned && - IsSpecifiedBearish(iDir); - if (isPinned) - { - Print(ToXString(iDir), " Pinned Bar: ", cBar.time); - } - } + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; // - // Checking Star Pattern ... - if (detectStarPattern) - { - bool isStarPattern = eaPatternDetector.IsStartPattern( - cBar, - iDir // - ); - bool isBullishStarPattern = isStarPattern && - IsSpecifiedBullish(iDir); - bool isBearishStarPattern = isStarPattern && - IsSpecifiedBearish(iDir); - if (isStarPattern) - { - Print(ToXString(iDir), " Star Pattern: ", cBar.time); - } - } + return result; +} +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ // - // Checking Piercing Pattern ... - if (detectPiercingPattern) - { - // - bool isPiercingPattern = eaPatternDetector.IsPiercingPattern( - cBar, - iDir // - ); - bool isBullishPiercingPattern = isPiercingPattern && - IsSpecifiedBullish(iDir); - bool isBearishPiercingPattern = isPiercingPattern && - IsSpecifiedBearish(iDir); - if (isPiercingPattern) - { - Print(ToXString(iDir), " Piercing Pattern: ", cBar.time); - } - } - - // - // Checking Rising Pattern ... - if (detectRisingPattern) - { - // - bool isRisingPattern = eaPatternDetector.IsRisingPattern( - cBar, - iDir // - ); - bool isBullishRisingPattern = isRisingPattern && - IsSpecifiedBullish(iDir); - bool isBearishRisingPattern = isRisingPattern && - IsSpecifiedBearish(iDir); - if (isRisingPattern) - { - Print(ToXString(iDir), " Rising Pattern: ", cBar.time); - } - } - - // - // Checking Flag Pattern ... - if (detectFlagPattern) - { - // - XOHCL swingBar; - bool isFlagPattern = eaPatternDetector.IsFlagPattern( - cBar, - iDir, - swingBar // - ); - bool isBullishFlagPattern = isFlagPattern && - IsSpecifiedBullish(iDir); - bool isBearishFlagPattern = isFlagPattern && - IsSpecifiedBearish(iDir); - if (isFlagPattern) - { - Print(ToXString(iDir), " Flag Pattern: ", cBar.time, ", Swing: ", swingBar.time); - } - swingBar.Clean(); - } - - // - // Detect SignalKey Bar Pattern ... - if (detectSignalKeyBarPattern) - { - // - bool isSignalKeyBar = eaPatternDetector.IsSignalKeyBarPattern( - cBar, - iDir // - ); - bool isBullishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBullish(iDir); - bool isBearishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBearish(iDir); - if (isSignalKeyBar) - { - Print(ToXString(iDir), " SignalKey Bar Pattern: ", cBar.time); - } - } - - // - // Detect Swing Trend ... - if (detectSwingTrend) - { - // - XOHCL swings[]; - bool hasSwingTrend = eaPatternDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - Print(ToXString(iDir), " Swing Trend: ", cBar.time); - - // - CChartObjectTrend *iObj; - has = eaDrawer.DrawSwingTrend( - swings, - iDir, - iObj, - true // Ray Right ... - ); - if (has) - { - draws.Add(iObj); - } - } - SpecifiedClean(swings); - } - - // - // Swing Trend Breakes ... - if (detectSwingTrendBreakes) - { - // - XOHCL swings[]; - bool hasSwingTrend = eaPatternDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - if (!HasDirection(trendDir)) - { - trendDir = iDir; - } - } - - // - // Breaked Detection ... - if (trendDir != iDir) - { - // - Print("Trend Dir Breaked to: ", ToXString(iDir)); - trendDir = iDir; - } - - // - SpecifiedClean(swings); - } - - // - // Detect Supports ... - if (detectSupports) - { - // - XOHCL support; - bool hasSupport = eaPatternDetector.HasSupport( - cBar, - support // - ); - if (hasSupport) - { - // - XBoxZone supportBox; - has = ToSupportBox(support, supportBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = eaDrawer.DrawBox( - supportBox, - iObj // - ); - if (has) - { - // - // Apply Style ... - eaDrawer.ApplyStyle( - iObj, - eaDrawer.boxBullishStyle // - ); - - // - draws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - supportBox.Clean(); - } - support.Clean(); - } - - // - // Detect Resistance ... - if (detectResistance) - { - // - XOHCL resistance; - bool hasResistance = eaPatternDetector.HasResistance( - cBar, - resistance // - ); - if (hasResistance) - { - // - XBoxZone resistanceBox; - has = ToResistanceBox(resistance, resistanceBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = eaDrawer.DrawBox( - resistanceBox, - iObj // - ); - if (has) - { - // - // Apply Style ... - eaDrawer.ApplyStyle( - iObj, - eaDrawer.boxBearishStyle // - ); - - // - draws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - resistanceBox.Clean(); - } - resistance.Clean(); - } - - // - cBar.Clean(); + // TODO: Use This ... + // EventKillTimer(); } // \ No newline at end of file