diff --git a/BKP/Main/Providers/x-saherelm.xuspy5.provider.inputs.lib.mq5 b/BKP/Main/Providers/x-saherelm.xuspy5.provider.inputs.lib.mq5 deleted file mode 100644 index b20e55a2..00000000 --- a/BKP/Main/Providers/x-saherelm.xuspy5.provider.inputs.lib.mq5 +++ /dev/null @@ -1,283 +0,0 @@ -/////////////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 XUSPY5 Signal Provider Library Inputs -// ----------------------------------------------------------- -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Include Logger ... -#include "../Libraries/x-saherelm.log.lib.mq5" - -// -// Include Classes ... -#include "../Classes/x-saherelm.class.lib.mq5" - -// -input group "XUSPY5 Provider"; - -// -// Commonly Used Configurations ... -input group "XUSPY5 Common"; -// -// Provider ... -input bool xUSPY5EnableProvider = true; // Enable Provider -input int xUSPY5NumberOfItemsPerTick = 30; // Number Of items Readed In Each Tick -// -// Alerts ... -input bool xUSPY5EnableAlerts = true; // Enable Events Alert -input bool xUSPY5EnableHourlyAlerts = false; // Send Alert on each new Hour -input bool xUSPY5EnableDailyAlerts = false; // Send Alert on each new Day -input bool xUSPY5EnableWeeklyAlerts = false; // Send Alert on each new Week -input bool xUSPY5EnableMonthlyAlerts = true; // Send Alert on each new Month -// -// Reports ... -input bool xUSPY5EnableDailyReports = false; // Send Report on each new Day -input bool xUSPY5EnableWeeklyReports = false; // Send Report on each new Week -input bool xUSPY5EnableMonthlyReports = true; // Send Report on each new Month - -// -// Trader and Expert Specific Configurations ... -input group "XUSPY5 Trader"; -input int xUSPY5MagicNumber = 16940561; // Trader MagicNumber -input int xUSPY5Slippage = 10; // Trader Slippage - -// -// Trades Management Configurations ... -input group "XUSPY5 Trade Management"; -input bool xUSPY5AllowLongTrades = true; // Allow Long Trades -input bool xUSPY5AllowShortTrades = true; // Allow Short Trades - -// -// Risk Management Configurations ... -input group "XUSPY5 Risk Management"; -// -// Trade Count ... -input int xUSPY5MaxAllowedTrades = 10; // Max Allowed Trades at Same Time -input ENUM_X_CROSS_SIGNAL_METHOD xUSPY5CrossSignalsMethod = X_CROSS_SIGNAL_REGULAR; // Handle Cross Signals Method -// -// Max Allowed Trade Age ... -input int xUSPY5MaxAllowedTradeAge = 2000; // Detect Long Time Trades -input ENUM_X_GUARD_ACTIONS xUSPY5OldTradesAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1; // What to do with Old Trades -// -// Trade Volume Specific Configurations ... -input double xUSPY5StaticVolumeFactor = 0.0002; // Static Volume baesd on Balance -input ENUM_STATIC_VOLUME_METHODS xUSPY5StaticVolumeMethod = X_STATIC_VOLUME_BASED_ON_BALANCE; // How to Calculate Static Volume -input double xUSPY5VolumeMultiplier = 0; // Volume Increase Multiplier -input double xUSPY5ApplyVolumeMultiplierFactor = 0; // Apply Volume Multiplier Rate based on Balance -input double xUSPY5MaxSupportedVolumePerTradeFactor = 0; // Max Supported Volume Per Trade Factor based on Balance -input double xUSPY5IncreasedMaxSupportedVolumeRate = 0; // Increase Max Supported Volume based on Balance -// -// Trade Profits ... -input double xUSPY5MinRewardInPips = 6; // Minimum Reward Per Trade in Pips -input double xUSPY5RiskFreeStepInPips = 0; // Make Trades Risk Free Steps in Pips -input double xUSPY5RiskFreeRate = 0; // Volume Multiplier for Risk Free Trades -// -// Guard Riskable Money and Profits ... -input double xUSPY5CriticalDrawDownFactor = 0.30; // Critical Allowed Drawdown Factor based on Balance -input ENUM_X_GUARD_ACTIONS xUSPY5CriticalGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5; // Specify Guard Action on Critical Drawdown -input double xUSPY5MaxAllowedDrawDownFactor = 0.40; // Max Allowed Drawdown Factor based on Balance -input ENUM_X_GUARD_ACTIONS xUSPY5MaxAllowedGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10; // Specify Guard Action on Max Allowed Drawdown -input int xUSPY5GuardStopoutFiredAfterTouches = 5; // Guard Stopout all Trades if Max Allowed Drawdown touched - -// -// Account Conditions for Trading ... -input double xUSPY5BalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades -input double xUSPY5FreeMarginFactorForOpenTrades = 0.8; // Minimum Free Margin for Open Trades - -// -// May be Used Later as Input Params ... -bool xUSPY5UseVirtualTPSl = false; // Use Virtual TP SL -bool xUSPY5EnableSignalAlerts = false; // Send Signal Alert - -// -// Validate Inputs before Initialization ... -bool XUSPY5ValidateInputs() -{ - // - bool result = false; - - // - // Implement Other Verifications ... - - // - // Check Trading Availability ... - bool isTradeAvailable = xUSPY5AllowLongTrades || xUSPY5AllowShortTrades; - if (!isTradeAvailable) - { - LogMessage("XUSPY5 => Warning: Trading disabled ..."); - } - - // - // Chekc Number of reading items per tick ... - result = xUSPY5NumberOfItemsPerTick >= 5; - if (!result) - { - // - LogMessage("XUSPY5 invalid Number of items Reading Per Tick ..."); - - // - return result; - } - - // - // Check Max Allowed Trades Count ... - result = isTradeAvailable && xUSPY5MaxAllowedTrades >= 1; - if (!result) - { - // - LogMessage("XUSPY5 Number of Trades not valid ..."); - - // - return result; - } - - // - // Check Free Margin ... - result = - isTradeAvailable && - xUSPY5FreeMarginFactorForOpenTrades > 0 && - xUSPY5FreeMarginFactorForOpenTrades < 1; - if (!result) - { - // - LogMessage("XUSPY5 Invalid Free Margin ..."); - - // - return result; - } - - // - // Check min Balance for Open Trades ... - result = - isTradeAvailable && - xUSPY5BalanceFactorForOpenTrades > 0 && - xUSPY5BalanceFactorForOpenTrades < 1; - if (!result) - { - // - LogMessage("XUSPY5 Invalid Min Balance for Open Trades ..."); - - // - return result; - } - - // - // Check Min Reward Per Trade ... - result = xUSPY5MinRewardInPips > 0; - if (!result) - { - // - LogMessage("XUSPY5 Invalid Min Reward Per Trade ..."); - - // - return result; - } - - // - // Check Trades Volume ... - result = xUSPY5StaticVolumeFactor > 0; - if (!result) - { - // - LogMessage("XUSPY5 Invalid Static Volume ..."); - - // - return result; - } - - // - // Check Volume Multiplier ... - result = xUSPY5VolumeMultiplier >= 0; - if (!result) - { - // - LogMessage("XUSPY5 Invalid Volume Multiplier ..."); - - // - return result; - } - - // - result = - xUSPY5CriticalDrawDownFactor == 0 || (xUSPY5CriticalDrawDownFactor > 0 && - xUSPY5CriticalDrawDownFactor < 1); - if (!result) - { - // - LogMessage("XUSPY5 Invalid Critical DrawDown Factor ..."); - - // - return result; - } - - // - result = - xUSPY5MaxAllowedDrawDownFactor == 0 || (xUSPY5MaxAllowedDrawDownFactor > 0 && - xUSPY5MaxAllowedDrawDownFactor < 1); - if (!result) - { - // - LogMessage("XUSPY5 Invalid Max Allowed DrawDown Factor ..."); - - // - return result; - } - - // - // Check Guard Actions ... - // - result = - xUSPY5CriticalDrawDownFactor > 0 && - xUSPY5CriticalDrawDownFactor < 1 && - xUSPY5MaxAllowedDrawDownFactor > 0 && - xUSPY5MaxAllowedDrawDownFactor < 1; - if (!result) - { - // - LogMessage("XUSPY5 For Critical Drawdown, you have to Specify Max Drawdown also ..."); - - // - return result; - } - - // - result = xUSPY5CriticalDrawDownFactor > 0 && xUSPY5CriticalDrawDownFactor < xUSPY5MaxAllowedDrawDownFactor; - if (!result) - { - // - LogMessage("XUSPY5 Critical Drawdown must Smaller than Max Drawdown ..."); - - // - return result; - } - - // - if (xUSPY5CriticalDrawDownFactor > 0 && xUSPY5CriticalGuardAction == X_GUARD_DO_NOTHING) - { - LogMessage("XUSPY5 IMPORTANT you Specified Critical Drawdown, but there is no any Guard Action ..."); - } - - // - if (xUSPY5MaxAllowedDrawDownFactor > 0 && xUSPY5MaxAllowedGuardAction == X_GUARD_DO_NOTHING) - { - LogMessage("XUSPY5 IMPORTANT you Specified Max Allowed Drawdown, but there is no any Guard Action ..."); - } - - // - result = true; - - // - return result; -} \ No newline at end of file diff --git a/BKP/Main/Classes/x-saherelm.class.lib.mq5 b/Classes/x-saherelm.class.lib.mq5 similarity index 100% rename from BKP/Main/Classes/x-saherelm.class.lib.mq5 rename to Classes/x-saherelm.class.lib.mq5 diff --git a/BKP/Main/Classes/x-saherelm.nn.lib.mq5 b/Classes/x-saherelm.nn.lib.mq5 similarity index 100% rename from BKP/Main/Classes/x-saherelm.nn.lib.mq5 rename to Classes/x-saherelm.nn.lib.mq5 diff --git a/BKP/Main/Classes/x-saherelm.provider.lib.mq5 b/Classes/x-saherelm.provider.lib.mq5 similarity index 100% rename from BKP/Main/Classes/x-saherelm.provider.lib.mq5 rename to Classes/x-saherelm.provider.lib.mq5 diff --git a/BKP/Main/Experts/x-saherelm.xuspy5.ea.mq5 b/Experts/x-saherelm.xuschf5.ea.mq5 similarity index 67% rename from BKP/Main/Experts/x-saherelm.xuspy5.ea.mq5 rename to Experts/x-saherelm.xuschf5.ea.mq5 index 351c8632..0838146b 100644 --- a/BKP/Main/Experts/x-saherelm.xuspy5.ea.mq5 +++ b/Experts/x-saherelm.xuschf5.ea.mq5 @@ -17,7 +17,7 @@ #property copyright "Copyright 2023, SaherElm IT Center" #property link "https://saherelm.ir" #property version "1.00" -#property description "SaherElm XUSPY5 EA" +#property description "SaherElm XUSCHF5 EA" #property strict // @@ -28,9 +28,9 @@ input group "Commons"; // // XCTIMER inputs ... -input bool xUSPY5ShowCandleTimer = true; // Show Condle Remaining Time -input color xUSPY5CandleTimerColot = clrYellow; // Candle Timer Color -input ENUM_BASE_CORNER xUSPY5CandleTimerCorner = CORNER_RIGHT_LOWER; // Where to Show Candle Timer +input bool xUSCHF5ShowCandleTimer = true; // Show Condle Remaining Time +input color xUSCHF5CandleTimerColot = clrYellow; // Candle Timer Color +input ENUM_BASE_CORNER xUSCHF5CandleTimerCorner = CORNER_RIGHT_LOWER; // Where to Show Candle Timer // // END Inputs ... @@ -57,8 +57,8 @@ input ENUM_BASE_CORNER xUSPY5CandleTimerCorner = CORNER_RIGHT_LOWER; // Where to #include "../Libraries/x-saherelm.draw.lib.mq5" // -// XUSPY5 Signal Provider ... -#include "../Providers/x-saherelm.xuspy5.provider.lib.mq5" +// XUSCHF5 Signal Provider ... +#include "../Providers/x-saherelm.xuschf5.provider.lib.mq5" // // END Including Providers ... @@ -67,13 +67,13 @@ input ENUM_BASE_CORNER xUSPY5CandleTimerCorner = CORNER_RIGHT_LOWER; // Where to // // START Global Definitions: Variables, Properties and etc ... // -bool isXUSPY5NewHour; -bool isXUSPY5NewDay; -bool isXUSPY5NewWeek; -bool isXUSPY5NewMonth; +bool isXUSCHF5NewHour; +bool isXUSCHF5NewDay; +bool isXUSCHF5NewWeek; +bool isXUSCHF5NewMonth; // -int xUSPY5CTimerHandler = INVALID_HANDLE; +int xUSCHF5CTimerHandler = INVALID_HANDLE; // // END Global Definitions: Variables, Properties and etc ... // @@ -87,7 +87,7 @@ int xUSPY5CTimerHandler = INVALID_HANDLE; int OnInit() { // - logTag = "XUSPY5EA"; + logTag = "XUSCHF5EA"; drawPrefix = logTag; alertPrefix = logTag; @@ -107,17 +107,17 @@ int OnInit() } // - // Initialize XUSPY5 Provider ... - if (!XUSPY5InitSignalProviderLibrary()) + // Initialize XUSCHF5 Provider ... + if (!XUSCHF5InitSignalProviderLibrary()) { return INIT_PARAMETERS_INCORRECT; } // // Init XCTimer ... - if (xUSPY5ShowCandleTimer) + if (xUSCHF5ShowCandleTimer) { - if (!XUSPY5CTimerInit()) + if (!XUSCHF5CTimerInit()) { return INIT_FAILED; } @@ -148,15 +148,15 @@ void OnDeinit(const int reason) // Here we can handle De Initialization Reasons ... // - // De Initialize XUSPY5 Provider ... - XUSPY5DeinitSignalProviderLibrary(reason); + // De Initialize XUSCHF5 Provider ... + XUSCHF5DeinitSignalProviderLibrary(reason); // // De Init XDraw Library ... // OnDeinitDrawLibrary(); // - IndicatorRelease(xUSPY5CTimerHandler); + IndicatorRelease(xUSCHF5CTimerHandler); } // @@ -166,15 +166,15 @@ void OnTick() // // Handle Monthly Alert ... bool isFirstMonth = xMonth == -1; - isXUSPY5NewMonth = IsNewMonth(); + isXUSCHF5NewMonth = IsNewMonth(); bool canMonthlyAlert = - isXUSPY5NewMonth && - xUSPY5EnableAlerts && - xUSPY5EnableMonthlyAlerts; + isXUSCHF5NewMonth && + xUSCHF5EnableAlerts && + xUSCHF5EnableMonthlyAlerts; bool canMonthlyReport = !isFirstMonth && canMonthlyAlert && - xUSPY5EnableMonthlyReports; + xUSCHF5EnableMonthlyReports; if (canMonthlyAlert) { // @@ -185,7 +185,7 @@ void OnTick() if (canMonthlyReport) { // - string report = xUSPY5Reporter.GenerateReportString(XREPORT_MONTHLY); + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_MONTHLY); // message = "Last Month Report:\n" + report; @@ -193,7 +193,7 @@ void OnTick() // // Reset Report ... - xUSPY5Reporter.Reset(XREPORT_MONTHLY); + xUSCHF5Reporter.Reset(XREPORT_MONTHLY); // SendAlert(message); @@ -202,15 +202,15 @@ void OnTick() // // Handle Weekly Alert ... bool isFirstWeek = xDayOfWeek == -1; - isXUSPY5NewWeek = IsNewWeek(); + isXUSCHF5NewWeek = IsNewWeek(); bool canWeeklyAlert = - isXUSPY5NewWeek && - xUSPY5EnableAlerts && - xUSPY5EnableWeeklyAlerts; + isXUSCHF5NewWeek && + xUSCHF5EnableAlerts && + xUSCHF5EnableWeeklyAlerts; bool canWeeklyReport = !isFirstWeek && canWeeklyAlert && - xUSPY5EnableWeeklyReports; + xUSCHF5EnableWeeklyReports; if (canWeeklyAlert) { // @@ -221,7 +221,7 @@ void OnTick() if (canWeeklyReport) { // - string report = xUSPY5Reporter.GenerateReportString(XREPORT_WEEKLY); + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_WEEKLY); // message = "Last Week Report:\n" + report; @@ -229,7 +229,7 @@ void OnTick() // // Reset Report ... - xUSPY5Reporter.Reset(XREPORT_WEEKLY); + xUSCHF5Reporter.Reset(XREPORT_WEEKLY); // SendAlert(message); @@ -238,15 +238,15 @@ void OnTick() // // Handle Daily Alert ... bool isFirstDay = xDay == -1; - isXUSPY5NewDay = IsNewDay(); + isXUSCHF5NewDay = IsNewDay(); bool canDailyAlert = - isXUSPY5NewDay && - xUSPY5EnableAlerts && - xUSPY5EnableDailyAlerts; + isXUSCHF5NewDay && + xUSCHF5EnableAlerts && + xUSCHF5EnableDailyAlerts; bool canDailyReport = !isFirstDay && canDailyAlert && - xUSPY5EnableDailyReports; + xUSCHF5EnableDailyReports; if (canDailyAlert) { // @@ -257,7 +257,7 @@ void OnTick() if (canDailyReport) { // - string report = xUSPY5Reporter.GenerateReportString(XREPORT_DAILY); + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_DAILY); // message = "Last Week Report:\n" + report; @@ -265,7 +265,7 @@ void OnTick() // // Reset Report ... - xUSPY5Reporter.Reset(XREPORT_DAILY); + xUSCHF5Reporter.Reset(XREPORT_DAILY); // SendAlert(message); @@ -274,11 +274,11 @@ void OnTick() // // Handle Hourly Alert ... bool isFirstHour = xHour == -1; - isXUSPY5NewHour = IsNewHour(); + isXUSCHF5NewHour = IsNewHour(); bool canHourlyAlert = - isXUSPY5NewHour && - xUSPY5EnableAlerts && - xUSPY5EnableHourlyAlerts; + isXUSCHF5NewHour && + xUSCHF5EnableAlerts && + xUSCHF5EnableHourlyAlerts; if (canHourlyAlert) { // @@ -290,33 +290,33 @@ void OnTick() // // Prevent Going Forward if user Disable it ... - if (xUSPY5EnableProvider) + if (xUSCHF5EnableProvider) { // - // Handle Processing on XUSPY5 Signal Provider ... - XUSPY5SignalProviderDoControlState(); + // Handle Processing on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderDoControlState(); } // // Check Can Ignore Tick or not .. - bool canIgnoreTick = xUSPY5IsTestMode + bool canIgnoreTick = xUSCHF5IsTestMode ? !IsNewCandle() - : !IsNewCandle() && xUSPY5WaitUntilNextCandle; + : !IsNewCandle() && xUSCHF5WaitUntilNextCandle; if (canIgnoreTick) { return; } // - xUSPY5WaitUntilNextCandle = false; + xUSCHF5WaitUntilNextCandle = false; // // Prevent Going Forward if user Disable it ... - if (xUSPY5EnableProvider) + if (xUSCHF5EnableProvider) { // - // Handle Processing on XUSPY5 Signal Provider ... - XUSPY5SignalProviderHandleTick(); + // Handle Processing on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderHandleTick(); } } @@ -327,11 +327,11 @@ void OnTrade() // // Prevent Going Forward if user Disable it ... - if (xUSPY5EnableProvider) + if (xUSCHF5EnableProvider) { // - // Handle Processing Trades on XUSPY5 Signal Provider ... - XUSPY5SignalProviderHandleTrade(); + // Handle Processing Trades on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderHandleTrade(); } } @@ -354,8 +354,8 @@ bool ValidateInputs() // Validate Args ... // - // Validate XUSPY5 Provider Inputs ... - result = XUSPY5ValidateInputs(); + // Validate XUSCHF5 Provider Inputs ... + result = XUSCHF5ValidateInputs(); if (!result) { return false; @@ -370,23 +370,23 @@ bool ValidateInputs() return result; } -bool XUSPY5CTimerInit() +bool XUSCHF5CTimerInit() { // bool result = true; // - xUSPY5CTimerHandler = iCustom( + xUSCHF5CTimerHandler = iCustom( _Symbol, _Period, "x-saherelm.xctimer.indicator", // // Inputs ... - xUSPY5CandleTimerColot, - xUSPY5CandleTimerCorner); + xUSCHF5CandleTimerColot, + xUSCHF5CandleTimerCorner); // - if (xUSPY5CTimerHandler == INVALID_HANDLE) + if (xUSCHF5CTimerHandler == INVALID_HANDLE) { result = false; } diff --git a/BKP/Main/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 b/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 rename to Helpers/x-saherelm.xama.indicator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 b/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 rename to Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 b/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 rename to Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 b/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 rename to Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 diff --git a/BKP/Main/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 b/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 similarity index 100% rename from BKP/Main/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 rename to Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xama.indicator.mq5 b/Indicators/x-saherelm.xama.indicator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xama.indicator.mq5 rename to Indicators/x-saherelm.xama.indicator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xchlh.oscillator.mq5 b/Indicators/x-saherelm.xchlh.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xchlh.oscillator.mq5 rename to Indicators/x-saherelm.xchlh.oscillator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xchma.oscillator.mq5 b/Indicators/x-saherelm.xchma.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xchma.oscillator.mq5 rename to Indicators/x-saherelm.xchma.oscillator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xctimer.indicator.mq5 b/Indicators/x-saherelm.xctimer.indicator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xctimer.indicator.mq5 rename to Indicators/x-saherelm.xctimer.indicator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xfi.oscillator.mq5 b/Indicators/x-saherelm.xfi.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xfi.oscillator.mq5 rename to Indicators/x-saherelm.xfi.oscillator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xlh.indicator.mq5 b/Indicators/x-saherelm.xlh.indicator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xlh.indicator.mq5 rename to Indicators/x-saherelm.xlh.indicator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xobd.indicator.mq5 b/Indicators/x-saherelm.xobd.indicator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xobd.indicator.mq5 rename to Indicators/x-saherelm.xobd.indicator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xrsi.oscillator.mq5 b/Indicators/x-saherelm.xrsi.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xrsi.oscillator.mq5 rename to Indicators/x-saherelm.xrsi.oscillator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xtd.oscillator.mq5 b/Indicators/x-saherelm.xtd.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xtd.oscillator.mq5 rename to Indicators/x-saherelm.xtd.oscillator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xtm.indicator.mq5 b/Indicators/x-saherelm.xtm.indicator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xtm.indicator.mq5 rename to Indicators/x-saherelm.xtm.indicator.mq5 diff --git a/BKP/Main/Indicators/x-saherelm.xts.oscillator.mq5 b/Indicators/x-saherelm.xts.oscillator.mq5 similarity index 100% rename from BKP/Main/Indicators/x-saherelm.xts.oscillator.mq5 rename to Indicators/x-saherelm.xts.oscillator.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.alert.lib.mq5 b/Libraries/x-saherelm.alert.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.alert.lib.mq5 rename to Libraries/x-saherelm.alert.lib.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.common.lib.mq5 b/Libraries/x-saherelm.common.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.common.lib.mq5 rename to Libraries/x-saherelm.common.lib.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.draw.lib.mq5 b/Libraries/x-saherelm.draw.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.draw.lib.mq5 rename to Libraries/x-saherelm.draw.lib.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.http.lib.mq5 b/Libraries/x-saherelm.http.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.http.lib.mq5 rename to Libraries/x-saherelm.http.lib.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.log.lib.mq5 b/Libraries/x-saherelm.log.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.log.lib.mq5 rename to Libraries/x-saherelm.log.lib.mq5 diff --git a/BKP/Main/Libraries/x-saherelm.models.lib.mq5 b/Libraries/x-saherelm.models.lib.mq5 similarity index 100% rename from BKP/Main/Libraries/x-saherelm.models.lib.mq5 rename to Libraries/x-saherelm.models.lib.mq5 diff --git a/Projects/XUSCHF5/Classes/.gitkeep b/Projects/XUSCHF5/Classes/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Classes/x-saherelm.class.lib.mq5 b/Projects/XUSCHF5/Classes/x-saherelm.class.lib.mq5 new file mode 100644 index 00000000..68f48471 --- /dev/null +++ b/Projects/XUSCHF5/Classes/x-saherelm.class.lib.mq5 @@ -0,0 +1,10316 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XClass +// Description: provides all classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +#include +#include +#include +#include +#include +#include +// +#include "../Libraries/x-saherelm.draw.lib.mq5" +#include "../Libraries/x-saherelm.alert.lib.mq5" +#include "../Libraries/x-saherelm.models.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Constant Definitions ... +// + +static uchar _md5_PADDING[64] = + { + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +#define _md5_F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define _md5_G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define _md5_H(x, y, z) ((x) ^ (y) ^ (z)) +#define _md5_I(x, y, z) ((y) ^ ((x) | (~z))) +#define _md5_ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + +#define _md5_FF(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_F((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define _md5_GG(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_G((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define _md5_HH(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_H((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define _md5_II(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_I((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } + +#define _md5_INIT_STATE_0 0x67452301 +#define _md5_INIT_STATE_1 0xefcdab89 +#define _md5_INIT_STATE_2 0x98badcfe +#define _md5_INIT_STATE_3 0x10325476 + +#define _md5_S11 7 +#define _md5_S12 12 +#define _md5_S13 17 +#define _md5_S14 22 + +#define _md5_S21 5 +#define _md5_S22 9 +#define _md5_S23 14 +#define _md5_S24 20 + +#define _md5_S31 4 +#define _md5_S32 11 +#define _md5_S33 16 +#define _md5_S34 23 + +#define _md5_S41 6 +#define _md5_S42 10 +#define _md5_S43 15 +#define _md5_S44 21 + +// +// END Constant Definitions ... +// + +// +// START Model Definitions ... +// + +// +string X_SIGNAL_TP = "TP"; +string X_SIGNAL_SL = "SL"; +string X_SIGNAL_TYPE = "TY"; +string X_SIGNAL_TICKET = "T"; +string X_SIGNAL_RISKFREE_STEP = "RFS"; +string X_SIGNAL_RISKFREE_RATE = "RFR"; + +// +// Model Signal Handler Result on XCTrade Class ... +struct XTraderHandlerResult +{ + // + // List Of Closed On SL Signals ... + XSignal sl[]; + + // + // List Of Closed On TP Signals ... + XSignal tp[]; + + // + // List Of Risk Free Signals ... + XSignal rf[]; +}; + +// +// Model OnTrade Event Handler Result on XCTrade Class ... +struct XOnTradeHandlerResult +{ + // + bool hasNewDeal; + int newDeals; + + // + bool hasNewOrder; + int newOrders; + + // + bool hasNewPosition; + int newPositions; + + // + bool hasNewHistoryOrder; + int newHistoryOrders; +}; + +// +// Model Guard Action Applied Signals ... +struct XGuardHandlerResult +{ + // + // Critical Guard ... + XSignal criticals[]; + + // + // Max Guard ... + XSignal maxes[]; + + // + // Old ... + XSignal olds[]; + + // + // Determines Stopout Action Cals or not ... + bool isStopOut; +}; + +// +// Define Volume States ... +struct XVolumeInfo +{ + // + // Current Available Static Volume ... + double staticVolume; + + // + // Static Volume Calculation Method ... + string staticVolumeCalculationMethod; + + // + // Current Maximum Appliable Volume ... + double maxAllowedVolume; + + // + // Static Volume Increase Multiplier ... + double volumeIncreaseMultiplier; + + // + // Multiply Volume Based On Balance Growing ... + double balanceGowingToApplyMultiplier; + + // + // Where to Increase MaxAllowed Volume ... + double balanceGrowingToIncreaseMaxAllowedVolume; +}; + +// +// Model a Simple Provider Status ... +struct XSignallerInfo +{ + // + // Provider Name ... + string name; + + // + // Number of Longs ... + int longs; + + // + // Number of Shorts ... + int shorts; +}; + +// +// Model Some of Usefull Signals and Market Data ... +struct XSummaryInfo +{ + // + // Define Max Signal Volume ... + double maxSignalVolume; + + // + // Max DrawDown ... + double maxDrawDown; + + // + // Max DrawUp ... + double maxDrawUp; + + // + // Max Number of Same Time Signals ... + int maxSameTimeSignals; + + // + // Number of Long Trades ... + int longSignals; + + // + // Number of Short Trades ... + int shortSignals; + + // + // Number of TPs Attached ... + int numberOfTPs; + + // + // Number of SLs Attached ... + int numberOfSLs; +}; + +// +// Model Account info ... +struct XAccountInfo +{ + // + // User Account ... + string user; + + // + // Name of Client ... + string name; + + // + // Trade Server Name ... + string server; + + // + // Broker Name ... + string broker; + + // + // Account Trade Mode ... + ENUM_ACCOUNT_TRADE_MODE mode; + + // + // Account Leverage ... + long leverage; + + // + // Currency ... + string currency; + + // + // Deposit ... + double deposit; + + // + // Balance ... + double balance; + + // + // Min Balance for Open Trades ... + double minBalanceForOpenTrades; +}; + +// +// this is a Model Which holds Reports for Specific Time Periods ... +struct XReport +{ + // + datetime start; + + // + datetime end; + + // + XAccountInfo accountInfo; + + // + XVolumeInfo volumeInfo; + + // + XSignallerInfo signallersInfo[]; + + // + XSummaryInfo summaryInfo; +}; + +// +// an Enumeration Object which determines Report Type ... +enum ENUM_XREPORT_TYPES +{ + // + // Main Report ... + XREPORT_MAIN, + // + // Daily Report ... + XREPORT_DAILY, + // + // Weekly Report ... + XREPORT_WEEKLY, + // + // Monthly Report ... + XREPORT_MONTHLY, +}; + +// +// a Signal Protection Structure ... +struct XProtectedSignal +{ + // + ulong ticket; + + // + datetime time[]; + + // + double profit[]; +}; + +// +// Represent Collector State Based on Time ... +struct XCollector +{ + // + // time in checking ... + datetime time; + + // + // Signal Volume ... + double volume; + + // + // Max DrawDown in Check Time ... + double maxDrawDown; + + // + // Max Allowed Volume in Check Time ... + double maxAllowedVolume; + + // + // Minimum required Balance for Opening Trades at Check Time ... + double minBalanceForOpenTrade; +}; + +// +// Cross Signals Methods ... +enum ENUM_X_CROSS_SIGNAL_METHOD +{ + // + // Do Nothing and Ignore them ... + X_CROSS_SIGNAL_DO_NOTHING, + // + // Accept all Cross Signals and Act Usually ... + X_CROSS_SIGNAL_REGULAR, + // + // Accept all Cross Signals and for Directional Act Usually and for Indirectional Ac Important ... + X_CROSS_SIGNAL_DIRECTION_REGULAR_INDIRECTION_IMPORTANT, + // + // Accept all Cross Signals and for Directional Act Important and for Indirectional Ac Usually ... + X_CROSS_SIGNAL_DIRECTION_IMPORTANT_INDIRECTION_REGULAR, + // + // Accept Only Indirectional Signals and Act Usually ... + X_CROSS_SIGNAL_INDIRECTION_REGULAR, + // + // Accept Only Directional Signals and Act Usually ... + X_CROSS_SIGNAL_DIRECTION_REGULAR, + // + // Accept Only Indirectional Signals and Act Important ... + X_CROSS_SIGNAL_INDIRECTION_IMPORTANT, + // + // Accept Only Directional Signals and Act Important ... + X_CROSS_SIGNAL_DIRECTION_IMPORTANT, +}; + +// +// the Action which Guard Handler Can Done when Attacked ... +enum ENUM_X_GUARD_ACTIONS +{ + // + // Do Nothing ... + X_GUARD_DO_NOTHING, + // + // Close All Open Positions ... + X_GUARD_CLOSE_ALL, + // + // Close Max In Drawdown Position ... + X_GUARD_CLOSE_MAX_IN_DD, + // + // Partial Close Max In Drawdown Position by 1% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1, + // + // Partial Close Max In Drawdown Position by 2% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_2, + // + // Partial Close Max In Drawdown Position by 3% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_3, + // + // Partial Close Max In Drawdown Position by 5% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5, + // + // Partial Close Max In Drawdown Position by 10% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10, + // + // Partial Close Max In Drawdown Position by 15% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_15, + // + // Partial Close Max In Drawdown Position by 20% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_20, + // + // Partial Close Max In Drawdown Position by 25% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_25, + // + // Partial Close Max In Drawdown Position by 30% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_30, + // + // Partial Close Max In Drawdown Position by 40% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_40, + // + // Partial Close Max In Drawdown Position by 50% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_50, + // + // Partial Close Max In Drawdown Position by 60% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_60, + // + // Partial Close Max In Drawdown Position by 70% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_70, + // + // Partial Close Max In Drawdown Position by 75% of Volume ... + X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_75, +}; + +// +// Guard Reason ... +enum ENUM_X_GUARD_REASONS +{ + // + // Critical ... + X_GUARDED_CRITICAL, + // + // Max ... + X_GUARDED_MAX, + // + // Old ... + X_GUARDED_OLD +}; + +// +// All Suuported Support Positions Guard ... +enum ENUM_X_GUARD_SUPPORT_METHODS +{ + // + // Ignore Supporting ... + X_SUPPORT_DO_NOTHING, + // + // Full Both Side Support ... + X_SUPPORT_FULL, + // + // Indirectional Supports On Drawing Down ... + X_SUPPORT_IN_DRAWDOWN_INDIRECTIONAL, + // + // Directional Supports On Drawing Up ... + X_SUPPORT_IN_DRAWUP_DIRECTIONAL, +}; + +// +// END Model Definitions ... +// + +// +// START Overrides ... +// + +// +// XBase Class ... +class XCBase +{ + // + // Public ... +public: + // + // Protected ... +protected: + // + void AddItemToBuffer( + double item, // Specified Item + double &buffer[] // Specified Buffer + ) + { + // + int bufferSize = ArraySize(buffer); + + // + ArrayResize( + buffer, + bufferSize + 1); + + // + buffer[bufferSize] = item; + } + void AddItemToBuffer( + datetime item, // Specified Item + datetime &buffer[] // Specified Buffer + ) + { + // + int bufferSize = ArraySize(buffer); + + // + ArrayResize( + buffer, + bufferSize + 1); + + // + buffer[bufferSize] = item; + } + void AddItemToBuffer( + XSignal &item, + XSignal &buffer[]) + { + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; + } + void AddItemToBuffer( + XCollector &item, // Specified Item + XCollector &buffer[] // Specified Buffer + ) + { + // + int bufferSize = ArraySize(buffer); + + // + ArrayResize( + buffer, + bufferSize + 1); + + // + buffer[bufferSize] = item; + } + void AddItemToBuffer( + XSignallerInfo &item, + XSignallerInfo &buffer[]) + { + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; + } + void AddItemToBuffer( + XProtectedSignal &item, // Item ... + XProtectedSignal &buffer[] // Buffer ... + ) + { + // + int bufferSize = ArraySize(buffer); + + // + ArrayResize( + buffer, + bufferSize + 1); + buffer[bufferSize] = item; + } + + // + void CleanBuffer(double &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XDeal &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XOrder &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XSignal &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XCollector &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XSignallerInfo &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + void CleanBuffer(XProtectedSignal &buffer[]) + { + // + ArrayFree(buffer); + ArrayResize(buffer, 0); + } + + // + void CopyBuffer( + const XSignallerInfo &source[], // Source Buffer ... + XSignallerInfo &dest[] // Dest Buffer ... + ) + { + // + CleanBuffer(dest); + + // + int sourceCount = ArraySize(source); + if (sourceCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = 0; i < sourceCount; i++) + { + // + XSignallerInfo iInfo = source[i]; + + // + AddItemToBuffer( + iInfo, + dest); + } + } + void CopyBuffer( + XProtectedSignal &source[], // Source Buffer to Copy + XProtectedSignal &dest[] // Fill this buffer using source + ) + { + // + CleanBuffer(dest); + + // + int sourceCount = ArraySize(source); + if (sourceCount <= 0) + { + return; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + XProtectedSignal iItem = source[i]; + + // + AddItemToBuffer( + iItem, + dest); + } + } + + // + // Private ... +private: +}; + +// +// XCTrade Base Class ... +class XSCTrade : public CTrade +{ +public: + // + // Modify Specific Position, by Specific Comment ... + bool PositionModify( + const string symbol, // Symbol + const double sl, // Stop Loss + const double tp, // Take Profit + const string comment = "" // Comment For Modify + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!SelectPosition(symbol)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // setting request + m_request.action = TRADE_ACTION_SLTP; + m_request.symbol = symbol; + m_request.magic = m_magic; + m_request.sl = sl; + m_request.tp = tp; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specified Comment ... + if (StringLen(comment) > 0) + { + m_request.comment = comment; + } + + // + // action and return the result + return (OrderSend(m_request, m_result)); + } + bool PositionModify( + const ulong ticket, // Position Ticket + const double sl, // Stop Loss + const double tp, // Take Profit + const string comment = "" // Comment For Modify + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // setting request + m_request.action = TRADE_ACTION_SLTP; + m_request.position = ticket; + m_request.symbol = PositionGetString(POSITION_SYMBOL); + m_request.magic = m_magic; + m_request.sl = sl; + m_request.tp = tp; + + // + // Specified Comment ... + if (StringLen(comment) > 0) + { + m_request.comment = comment; + } + + // + // action and return the result + return (OrderSend(m_request, m_result)); + } + + // + // Close Specific Position, by Specific Comment ... + bool PositionClose( + const string symbol, // Symbol + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + bool partial_close = false; + int retry_count = 10; + uint retcode = TRADE_RETCODE_REJECT; + + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + do + { + // + // check + if (SelectPosition(symbol)) + { + // + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + } + else + { + // + // position not found + m_result.retcode = retcode; + return (false); + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.symbol = symbol; + m_request.volume = PositionGetDouble(POSITION_VOLUME); + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specify Comment ... + m_request.comment = comment; + + // + // check volume + double max_volume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX); + if (m_request.volume > max_volume) + { + // + m_request.volume = max_volume; + partial_close = true; + } + else + { + partial_close = false; + } + + // + // hedging? just send order + if (IsHedging()) + { + return (OrderSend(m_request, m_result)); + } + + // + // order send + if (!OrderSend(m_request, m_result)) + { + // + if (--retry_count != 0) + { + continue; + } + + // + if (retcode == TRADE_RETCODE_DONE_PARTIAL) + { + m_result.retcode = retcode; + } + + // + return (false); + } + + // + //--- WARNING. If position volume exceeds the maximum volume allowed for deal, + //--- and when the asynchronous trade mode is on, for safety reasons, position is closed not completely, + //--- but partially. It is decreased by the maximum volume allowed for deal. + if (m_async_mode) + { + break; + } + + // + retcode = TRADE_RETCODE_DONE_PARTIAL; + if (partial_close) + { + Sleep(1000); + } + } while (partial_close); + + // + // succeed + return (true); + } + bool PositionClose( + const ulong ticket, // Position Ticket + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + string symbol = PositionGetString(POSITION_SYMBOL); + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.position = ticket; + m_request.symbol = symbol; + m_request.volume = PositionGetDouble(POSITION_VOLUME); + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + + // + // Specify Comment ... + m_request.comment = comment; + + // + // close position + return (OrderSend(m_request, m_result)); + } + + // + // Partial Close Specific Position, by Specific Comment ... + bool PositionClosePartial( + const string symbol, // Symbol + const double volume, // Partial Closing Volume + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + uint retcode = TRADE_RETCODE_REJECT; + + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // for hedging mode only + if (!IsHedging()) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if (SelectPosition(symbol)) + { + // + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + } + else + { + // + // position not found + m_result.retcode = retcode; + return (false); + } + + // + // check volume + double position_volume = PositionGetDouble(POSITION_VOLUME); + if (position_volume > volume) + { + position_volume = volume; + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.symbol = symbol; + m_request.volume = position_volume; + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specifieng Comment ... + m_request.comment = comment; + + // + // hedging? just send order + return (OrderSend(m_request, m_result)); + } + bool PositionClosePartial( + const ulong ticket, // Position Ticket + const double volume, // Partial Closing Volume + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // for hedging mode only + if (!IsHedging()) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + string symbol = PositionGetString(POSITION_SYMBOL); + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + + // + // check volume + double position_volume = PositionGetDouble(POSITION_VOLUME); + if (position_volume > volume) + { + position_volume = volume; + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.position = ticket; + m_request.symbol = symbol; + m_request.volume = position_volume; + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + + // + // Specifieng Comment ... + m_request.comment = comment; + + // + // close position + return (OrderSend(m_request, m_result)); + } +}; +// +// END Overrides ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +// XCMD5 a library for Hashing ... +class XCMD5 : public XCBase +{ + // + // Public Provides ... +public: + // + // Protected Provides ... + + // + // Constructor ... + XCMD5(void) {} + + // + // Deconstructor ... + ~XCMD5(void) {} + + // + // Hash Specified Char Array ... + string Hash( + uchar &source[], // Specify Char Array to Hash + int length = 0 // Specify Length of Char Array which required to hash + ) + { + // + string result = ""; + + // + int sourceCount = ArraySize(source); + + // + // Validate Args ... + if ( + sourceCount <= 0 || + (sourceCount > 0 && length > sourceCount)) + { + return result; + } + + // + // Normalize Args ... + if (length == 0) + { + length = sourceCount; + } + + // + // Init MD5 ... + MD5Init(); + + // + // Update Buffer ... + MD5Update(source, length); + + // + // Calculate Result ... + result = MD5Final(); + + // + return result; + } + + // + // Hash Specified String ... + string Hash( + string source // Specified String + ) + { + // + string result = ""; + + // + // Converts String to Char Array ... + uchar bytes[]; + StringToCharArray( + source, + bytes, + 0, + StringLen(source)); + + // + result = Hash( + bytes, + ArraySize(bytes)); + + // + return result; + } + +protected: + // + // Private Provides ... +private: + // + uint m_lMD5[4]; + uint m_nCount[2]; + uchar m_lpszBuffer[64]; + + // + // Convert Byte to DWord ... + void ByteToDWord(int &out[], uint &in[], uint len) + { + // + uint i = 0; + uint j = 0; + + // + for (; j < len; i++, j += 4) + { + out[i] = (int)in[j] | (int)in[j + 1] << 8 | (int)in[j + 2] << 16 | (int)in[j + 3] << 24; + } + } + + // + // Convert DWord to Byte ... + void DWordToByte(uchar &out[], int &in[], uint len) + { + // + uint i = 0; + uint j = 0; + + // + for (; j < len; i++, j += 4) + { + // + out[j] = (uchar)(in[i] & 0xff); + out[j + 1] = (uchar)((in[i] >> 8) & 0xff); + out[j + 2] = (uchar)((in[i] >> 16) & 0xff); + out[j + 3] = (uchar)((in[i] >> 24) & 0xff); + } + } + + // + // Init MD5 Array ... + void MD5Init() + { + // + ArrayInitialize(m_lpszBuffer, 64); + + // + m_nCount[0] = m_nCount[1] = 0; + m_lMD5[0] = _md5_INIT_STATE_0; + m_lMD5[1] = _md5_INIT_STATE_1; + m_lMD5[2] = _md5_INIT_STATE_2; + m_lMD5[3] = _md5_INIT_STATE_3; + } + + // + // Update MD5 ... + void MD5Update(uchar &inBuf[], uint inLen) + { + // + int i, ii; + int mdi; + + // + uint in[16]; + int i0 = 0; + + // + mdi = (int)((m_nCount[0] >> 3) & 0x3F); + + // + if ((m_nCount[0] + ((uint)inLen << 3)) < m_nCount[0]) + { + m_nCount[1]++; + } + + // + m_nCount[0] += ((uint)inLen << 3); + m_nCount[1] += ((uint)inLen >> 29); + + // + while ((inLen--) > 0) + { + // + m_lpszBuffer[mdi++] = inBuf[i0++]; + if (mdi == 0x40) + { + // + for (i = 0, ii = 0; i < 16; i++, ii += 4) + { + in[i] = (((uint)m_lpszBuffer[ii + 3]) << 24) | (((uint)m_lpszBuffer[ii + 2]) << 16) | (((uint)m_lpszBuffer[ii + 1]) << 8) | ((uint)m_lpszBuffer[ii]); + } + + // + Transform(m_lMD5, in); + + // + mdi = 0; + } + } + } + + // + // Finalize an MD5 Expression ... + string MD5Final() + { + // + uchar bits[8]; + int nIndex; + uint nPadLen; + const int nMD5Size = 16; + uchar lpszMD5[16]; + string temp; + string out = ""; + int i; + + // + DWordToByte(bits, m_nCount, 8); + nIndex = (int)((m_nCount[0] >> 3) & 0x3f); + nPadLen = (nIndex < 56) ? (56 - nIndex) : (120 - nIndex); + MD5Update(_md5_PADDING, nPadLen); + MD5Update(bits, 8); + DWordToByte(lpszMD5, m_lMD5, nMD5Size); + + // + for (i = 0; i < nMD5Size; i++) + { + // + if (lpszMD5[i] == 0) + { + temp = "00"; + } + else if (lpszMD5[i] <= 15) + { + temp = StringFormat("0%x", lpszMD5[i]); + } + else + { + temp = StringFormat("%x", lpszMD5[i]); + } + + // + out += temp; + } + + // + lpszMD5[0] = '\0'; + + // + return (out); + } + + // + // Transform Buffers ... + void Transform(uint &buf[], uint &in[]) + { + // + uint a = buf[0], b = buf[1], c = buf[2], d = buf[3]; + + // + _md5_FF(a, b, c, d, in[0], _md5_S11, 0xD76AA478); + _md5_FF(d, a, b, c, in[1], _md5_S12, 0xE8C7B756); + _md5_FF(c, d, a, b, in[2], _md5_S13, 0x242070DB); + _md5_FF(b, c, d, a, in[3], _md5_S14, 0xC1BDCEEE); + _md5_FF(a, b, c, d, in[4], _md5_S11, 0xF57C0FAF); + _md5_FF(d, a, b, c, in[5], _md5_S12, 0x4787C62A); + _md5_FF(c, d, a, b, in[6], _md5_S13, 0xA8304613); + _md5_FF(b, c, d, a, in[7], _md5_S14, 0xFD469501); + _md5_FF(a, b, c, d, in[8], _md5_S11, 0x698098D8); + _md5_FF(d, a, b, c, in[9], _md5_S12, 0x8B44F7AF); + _md5_FF(c, d, a, b, in[10], _md5_S13, 0xFFFF5BB1); + _md5_FF(b, c, d, a, in[11], _md5_S14, 0x895CD7BE); + _md5_FF(a, b, c, d, in[12], _md5_S11, 0x6B901122); + _md5_FF(d, a, b, c, in[13], _md5_S12, 0xFD987193); + _md5_FF(c, d, a, b, in[14], _md5_S13, 0xA679438E); + _md5_FF(b, c, d, a, in[15], _md5_S14, 0x49B40821); + + // + _md5_GG(a, b, c, d, in[1], _md5_S21, 0xF61E2562); + _md5_GG(d, a, b, c, in[6], _md5_S22, 0xC040B340); + _md5_GG(c, d, a, b, in[11], _md5_S23, 0x265E5A51); + _md5_GG(b, c, d, a, in[0], _md5_S24, 0xE9B6C7AA); + _md5_GG(a, b, c, d, in[5], _md5_S21, 0xD62F105D); + _md5_GG(d, a, b, c, in[10], _md5_S22, 0x02441453); + _md5_GG(c, d, a, b, in[15], _md5_S23, 0xD8A1E681); + _md5_GG(b, c, d, a, in[4], _md5_S24, 0xE7D3FBC8); + _md5_GG(a, b, c, d, in[9], _md5_S21, 0x21E1CDE6); + _md5_GG(d, a, b, c, in[14], _md5_S22, 0xC33707D6); + _md5_GG(c, d, a, b, in[3], _md5_S23, 0xF4D50D87); + _md5_GG(b, c, d, a, in[8], _md5_S24, 0x455A14ED); + _md5_GG(a, b, c, d, in[13], _md5_S21, 0xA9E3E905); + _md5_GG(d, a, b, c, in[2], _md5_S22, 0xFCEFA3F8); + _md5_GG(c, d, a, b, in[7], _md5_S23, 0x676F02D9); + _md5_GG(b, c, d, a, in[12], _md5_S24, 0x8D2A4C8A); + + // + _md5_HH(a, b, c, d, in[5], _md5_S31, 0xFFFA3942); + _md5_HH(d, a, b, c, in[8], _md5_S32, 0x8771F681); + _md5_HH(c, d, a, b, in[11], _md5_S33, 0x6D9D6122); + _md5_HH(b, c, d, a, in[14], _md5_S34, 0xFDE5380C); + _md5_HH(a, b, c, d, in[1], _md5_S31, 0xA4BEEA44); + _md5_HH(d, a, b, c, in[4], _md5_S32, 0x4BDECFA9); + _md5_HH(c, d, a, b, in[7], _md5_S33, 0xF6BB4B60); + _md5_HH(b, c, d, a, in[10], _md5_S34, 0xBEBFBC70); + _md5_HH(a, b, c, d, in[13], _md5_S31, 0x289B7EC6); + _md5_HH(d, a, b, c, in[0], _md5_S32, 0xEAA127FA); + _md5_HH(c, d, a, b, in[3], _md5_S33, 0xD4EF3085); + _md5_HH(b, c, d, a, in[6], _md5_S34, 0x04881D05); + _md5_HH(a, b, c, d, in[9], _md5_S31, 0xD9D4D039); + _md5_HH(d, a, b, c, in[12], _md5_S32, 0xE6DB99E5); + _md5_HH(c, d, a, b, in[15], _md5_S33, 0x1FA27CF8); + _md5_HH(b, c, d, a, in[2], _md5_S34, 0xC4AC5665); + + // + _md5_II(a, b, c, d, in[0], _md5_S41, 0xF4292244); + _md5_II(d, a, b, c, in[7], _md5_S42, 0x432AFF97); + _md5_II(c, d, a, b, in[14], _md5_S43, 0xAB9423A7); + _md5_II(b, c, d, a, in[5], _md5_S44, 0xFC93A039); + _md5_II(a, b, c, d, in[12], _md5_S41, 0x655B59C3); + _md5_II(d, a, b, c, in[3], _md5_S42, 0x8F0CCC92); + _md5_II(c, d, a, b, in[10], _md5_S43, 0xFFEFF47D); + _md5_II(b, c, d, a, in[1], _md5_S44, 0x85845DD1); + _md5_II(a, b, c, d, in[8], _md5_S41, 0x6FA87E4F); + _md5_II(d, a, b, c, in[15], _md5_S42, 0xFE2CE6E0); + _md5_II(c, d, a, b, in[6], _md5_S43, 0xA3014314); + _md5_II(b, c, d, a, in[13], _md5_S44, 0x4E0811A1); + _md5_II(a, b, c, d, in[4], _md5_S41, 0xF7537E82); + _md5_II(d, a, b, c, in[11], _md5_S42, 0xBD3AF235); + _md5_II(c, d, a, b, in[2], _md5_S43, 0x2AD7D2BB); + _md5_II(b, c, d, a, in[9], _md5_S44, 0xEB86D391); + + // + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; + } +}; + +// +// XSaherElm Account Info Class ... +class XCAccountInfo : public XCBase +{ + // + // Public properties ... +public: + // + // Constructro ... + void XCAccountInfo() + { + // + mAccountInfo = new CAccountInfo(); + + // + mInitialBalance = mAccountInfo.Balance(); + } + + // + // Deconstructor ... + void ~XCAccountInfo() + { + // + mInitialBalance = 0; + } + + // + // User Account ... + long GetUserAccount() + { + return mAccountInfo.Login(); + } + + // + // Account Leverage ... + long GetLeverage() + { + return mAccountInfo.Leverage(); + } + + // + // Get Trade Expert State ... + bool CanExpertTrade() + { + return mAccountInfo.TradeExpert(); + } + + // + // User Account Trade Mopde (ENUM_ACCOUNT_TRADE_MODE) ... + // -------------------------- + // ACCOUNT_TRADE_MODE_DEMO + // ACCOUNT_TRADE_MODE_CONTEST + // ACCOUNT_TRADE_MODE_REAL + ENUM_ACCOUNT_TRADE_MODE GetTradeMode() + { + return mAccountInfo.TradeMode(); + } + + // + // Get Account Balance ... + double GetBalance() + { + return mAccountInfo.Balance(); + } + + // + // Get Initial Deposit Balance ... + double GetInitialBalance() + { + return mInitialBalance; + } + + // + // Get the amount of give Credit ... + double GetCredit() + { + return mAccountInfo.Credit(); + } + + // + // Get the amount of current Profit on account ... + double GetProfit() + { + return mAccountInfo.Profit(); + } + + // + // Get the amount of current Equity on account ... + double GetEquity() + { + return mAccountInfo.Equity(); + } + + // + // Get the amount of reserved Margin ... + double GetMargin() + { + return mAccountInfo.Margin(); + } + + // + // Get the amount of free Margin ... + double GetFreeMargin() + { + return mAccountInfo.FreeMargin(); + } + + // + // Get the Level of Margin ... + double GetMarginLevel() + { + return mAccountInfo.MarginLevel(); + } + + // + // Get the Level Of Margin for a Deposit ... + double GetMarginCall() + { + return mAccountInfo.MarginCall(); + } + + // + // Get the Level of Margin for Stop out ... + double GetMarginStopOut() + { + return mAccountInfo.MarginStopOut(); + } + + // + // Get the Client Name ... + string GetName() + { + return mAccountInfo.Name(); + } + + // + // Get the Trade Server Name ... + string GetServerName() + { + return mAccountInfo.Server(); + } + + // + // Get deposit Currency Name ... + string GetCurrency() + { + return mAccountInfo.Currency(); + } + + // + // Get the Company Name that serves an Account ... + string GetCompany() + { + return mAccountInfo.Company(); + } + + // + // Calculate Profits for the current account based on passed parameters ... + double CalculateTradeProfit( + const string symbol, // trading symbol + ENUM_ORDER_TYPE type, // order type + double volume, // volume + double entry, // open price + double exit // close price + ) + { + // + double result = mAccountInfo.OrderProfitCheck( + symbol, + type, + volume, + entry, + exit); + + // + return result; + } + + // + // Calculate amount of margin which required for trade operation ... + double CalculateMarging( + const string symbol, // trading symbol + ENUM_ORDER_TYPE type, // order type + double volume, // volume + double entry // open price + ) + { + // + double result = mAccountInfo.MarginCheck( + symbol, + type, + volume, + entry); + + // + return result; + } + + // + // Calculate amount of free margin left after trade operation ... + double CalculateFreeMarging( + const string symbol, // trading symbol + ENUM_ORDER_TYPE type, // order type + double volume, // volume + double entry // open price + ) + { + // + double result = mAccountInfo.FreeMarginCheck( + symbol, + type, + volume, + entry); + + // + return result; + } + + // + // Calculate the Maximum possible volume of trade operation ... + double CalculateMaxVolume( + const string symbol, // trading symbol + ENUM_ORDER_TYPE type, // order type + double entry, // open price + double percent = 100 // percent of available margin + ) + { + // + double result = mAccountInfo.MaxLotCheck( + symbol, + type, + entry, + percent); + + // + return result; + } + + // + // Protected properties ... +protected: + // + // Private properties ... +private: + // + // Initial Account Balance ... + double mInitialBalance; + + // + // Account Info ... + CAccountInfo mAccountInfo; +}; + +// +// XSaherElm Report Info Class ... +class XCReporter : public XCBase +{ + // + // Public Provided ... +public: + // + // Constructro ... + void XCReporter() + { + // + mAccountInfo = new XCAccountInfo(); + + // + Reset(); + } + + // + // Deconstructor ... + void ~XCReporter() + { + } + + // + // Reset Specific Report ... + void Reset( + ENUM_XREPORT_TYPES type // Specify Report Type + ) + { + CleanReport(type); + } + + // + // Reset All Reports ... + void Reset() + { + // + CleanReport(XREPORT_MAIN); + CleanReport(XREPORT_MONTHLY); + CleanReport(XREPORT_WEEKLY); + CleanReport(XREPORT_DAILY); + } + + // + // Update Volume Info ... + void UpdateReportVolumeInfo( + ENUM_XREPORT_TYPES type, // Specified Report Type + // + double staticVolume, // Current Available Static Volume + string staticVolumeCalculationMethod, // Static Volume Calculation Method + double maxAllowedVolume, // Current Maximum Appliable Volume + double volumeIncreaseMultiplier, // Static Volume Increase Multiplier + double balanceGowingToApplyMultiplier, // Multiply Volume Based On Balance Growing + double balanceGrowingToIncreaseMaxAllowedVolume // Where to Increase MaxAllowed Volume + ) + { + // + // Filling Account Info ... + FillReportAccountInfo(type); + + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + // + FillingVolumeInfo( + mMainReport, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + // + FillingVolumeInfo( + mMonthlyReport, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + // + FillingVolumeInfo( + mWeeklyReport, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + break; + + // + // Daily ... + case XREPORT_DAILY: + // + FillingVolumeInfo( + mDailyReport, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + break; + } + } + + // + // Update Volume Info on All Reports ... + void UpdateReportsVolumeInfo( + double staticVolume, // Current Available Static Volume + string staticVolumeCalculationMethod, // Static Volume Calculation Method + double maxAllowedVolume, // Current Maximum Appliable Volume + double volumeIncreaseMultiplier, // Static Volume Increase Multiplier + double balanceGowingToApplyMultiplier, // Multiply Volume Based On Balance Growing + double balanceGrowingToIncreaseMaxAllowedVolume // Where to Increase MaxAllowed Volume + ) + { + // + // Main ... + UpdateReportVolumeInfo( + XREPORT_MAIN, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + + // + // Monthly ... + UpdateReportVolumeInfo( + XREPORT_MONTHLY, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + + // + // Weekly ... + UpdateReportVolumeInfo( + XREPORT_WEEKLY, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + + // + // Daily ... + UpdateReportVolumeInfo( + XREPORT_DAILY, + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + } + + // + // Add Specific Signal to Report ... + void AddSignalToReport( + ENUM_XREPORT_TYPES type, // Specified Report Type + const XSignal &signal, // Specified Signal + const string &providers[] // Specified Signal Providers + ) + { + // + // + // Filling Account Info ... + FillReportAccountInfo(type); + + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + AddSignalToReport( + mMainReport, + signal, + providers); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + AddSignalToReport( + mMonthlyReport, + signal, + providers); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + AddSignalToReport( + mWeeklyReport, + signal, + providers); + break; + + // + // Daily ... + case XREPORT_DAILY: + AddSignalToReport( + mDailyReport, + signal, + providers); + break; + } + } + + // + // Add Specific Signal to All Reports ... + void AddSignalToReports( + const XSignal &signal, // Specified Signal + const string &providers[] // Specified Signal Providers + ) + { + // + // Main ... + AddSignalToReport( + XREPORT_MAIN, + signal, + providers); + + // + // Monthly ... + AddSignalToReport( + XREPORT_MONTHLY, + signal, + providers); + + // + // Weekly ... + AddSignalToReport( + XREPORT_WEEKLY, + signal, + providers); + + // + // Daily ... + AddSignalToReport( + XREPORT_DAILY, + signal, + providers); + } + + // + // Report a TP for Specific Report ... + void AddTradeTPInReport( + ENUM_XREPORT_TYPES type // Specified Report Type + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + AddTradeTPInReport(mMainReport); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + AddTradeTPInReport(mMonthlyReport); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + AddTradeTPInReport(mWeeklyReport); + break; + + // + // Daily ... + case XREPORT_DAILY: + AddTradeTPInReport(mDailyReport); + break; + } + } + + // + // Report a TP for All Reports ... + void AddTradeTPInReports() + { + // + // Main ... + AddTradeTPInReport(XREPORT_MAIN); + + // + // Monthly ... + AddTradeTPInReport(XREPORT_MONTHLY); + + // + // Weekly ... + AddTradeTPInReport(XREPORT_WEEKLY); + + // + // Daily ... + AddTradeTPInReport(XREPORT_DAILY); + } + + // + // Report a SL for Specific Report ... + void AddTradeSLInReport( + ENUM_XREPORT_TYPES type // Specified Report Type + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + AddTradeSLInReport(mMainReport); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + AddTradeSLInReport(mMonthlyReport); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + AddTradeSLInReport(mWeeklyReport); + break; + + // + // Daily ... + case XREPORT_DAILY: + AddTradeSLInReport(mDailyReport); + break; + } + } + + // + // Report a SL for All Reports ... + void AddTradeSLInReports() + { + // + // Main ... + AddTradeSLInReport(XREPORT_MAIN); + + // + // Monthly ... + AddTradeSLInReport(XREPORT_MONTHLY); + + // + // Weekly ... + AddTradeSLInReport(XREPORT_WEEKLY); + + // + // Daily ... + AddTradeSLInReport(XREPORT_DAILY); + } + + // + // Update Number of Same Time Trades in Specific Report ... + void UpdateMaxSameTimeTradesInReport( + ENUM_XREPORT_TYPES type, // Specified Report Type + int value // number of same time trades + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + UpdateMaxSameTimeTradesInReport( + mMainReport, + value); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + UpdateMaxSameTimeTradesInReport( + mMonthlyReport, + value); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + UpdateMaxSameTimeTradesInReport( + mWeeklyReport, + value); + break; + + // + // Daily ... + case XREPORT_DAILY: + UpdateMaxSameTimeTradesInReport( + mDailyReport, + value); + break; + } + } + + // + // Update Number of Same Time Trades in All Report ... + void UpdateMaxSameTimeTradesInReports( + int value // number of same time trades + ) + { + // + // Main ... + UpdateMaxSameTimeTradesInReport( + XREPORT_MAIN, + value); + + // + // Monthly ... + UpdateMaxSameTimeTradesInReport( + XREPORT_MONTHLY, + value); + + // + // Weekly ... + UpdateMaxSameTimeTradesInReport( + XREPORT_WEEKLY, + value); + + // + // Daily ... + UpdateMaxSameTimeTradesInReport( + XREPORT_DAILY, + value); + } + + // + // Update Max DrawDown in Specific Report ... + void UpdateMaxDrawDownInReport( + ENUM_XREPORT_TYPES type, // Specified Report Type + double value // draw down value + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + UpdateMaxDrawDownInReport( + mMainReport, + value); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + UpdateMaxDrawDownInReport( + mMonthlyReport, + value); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + UpdateMaxDrawDownInReport( + mWeeklyReport, + value); + break; + + // + // Daily ... + case XREPORT_DAILY: + UpdateMaxDrawDownInReport( + mDailyReport, + value); + break; + } + } + + // + // Update Max DrawDown in All Report ... + void UpdateMaxDrawDownInReports( + double value // draw down value + ) + { + // + // Main ... + UpdateMaxDrawDownInReport( + XREPORT_MAIN, + value); + + // + // Monthly ... + UpdateMaxDrawDownInReport( + XREPORT_MONTHLY, + value); + + // + // Weekly ... + UpdateMaxDrawDownInReport( + XREPORT_WEEKLY, + value); + + // + // Daily ... + UpdateMaxDrawDownInReport( + XREPORT_DAILY, + value); + } + + // + // Update Max DrawUp in Specific Report ... + void UpdateMaxDrawUpInReport( + ENUM_XREPORT_TYPES type, // Specified Report Type + double value // draw up value + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + UpdateMaxDrawUpInReport( + mMainReport, + value); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + UpdateMaxDrawUpInReport( + mMonthlyReport, + value); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + UpdateMaxDrawUpInReport( + mWeeklyReport, + value); + break; + + // + // Daily ... + case XREPORT_DAILY: + UpdateMaxDrawUpInReport( + mDailyReport, + value); + break; + } + } + + // + // Update Max DrawUp in All Report ... + void UpdateMaxDrawUpInReports( + double value // draw up value + ) + { + // + // Main ... + UpdateMaxDrawUpInReport( + XREPORT_MAIN, + value); + + // + // Monthly ... + UpdateMaxDrawUpInReport( + XREPORT_MONTHLY, + value); + + // + // Weekly ... + UpdateMaxDrawUpInReport( + XREPORT_WEEKLY, + value); + + // + // Daily ... + UpdateMaxDrawUpInReport( + XREPORT_DAILY, + value); + } + + // + // Update Min Balance for Open Trades in Specific Report ... + void UpdateMinBalanceForOpenTradesInReport( + ENUM_XREPORT_TYPES type, // Specified Report Type + double value // min balance for open trades + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + UpdateMinBalanceForOpenTradesInReport( + mMainReport, + value); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + UpdateMinBalanceForOpenTradesInReport( + mMonthlyReport, + value); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + UpdateMinBalanceForOpenTradesInReport( + mWeeklyReport, + value); + break; + + // + // Daily ... + case XREPORT_DAILY: + UpdateMinBalanceForOpenTradesInReport( + mDailyReport, + value); + break; + } + } + + // + // Update Min Balance for Open Trades in All Report ... + void UpdateMinBalanceForOpenTradesInReports( + double value // min balance for open trades + ) + { + // + // Main ... + UpdateMinBalanceForOpenTradesInReport( + XREPORT_MAIN, + value); + + // + // Monthly ... + UpdateMinBalanceForOpenTradesInReport( + XREPORT_MONTHLY, + value); + + // + // Weekly ... + UpdateMinBalanceForOpenTradesInReport( + XREPORT_WEEKLY, + value); + + // + // Daily ... + UpdateMinBalanceForOpenTradesInReport( + XREPORT_DAILY, + value); + } + + // + // Gnerate Specific Type Of Report String Representation ... + string GenerateReportString( + ENUM_XREPORT_TYPES type, // Specified Report Type + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + result = GenerateReportString( + mMainReport, + separator); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + result = GenerateReportString( + mMonthlyReport, + separator); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + result = GenerateReportString( + mWeeklyReport, + separator); + break; + + // + // Daily ... + case XREPORT_DAILY: + result = GenerateReportString( + mDailyReport, + separator); + break; + } + + // + return result; + } + + // + // Protected Provided ... +protected: + // + // Private Provided ... +private: + // + // Account Info Instance ... + XCAccountInfo mAccountInfo; + + // + // Main Report ... + XReport mMainReport; + + // + // Monthly Report ... + XReport mMonthlyReport; + + // + // Weekly Report ... + XReport mWeeklyReport; + + // + // Daily Report ... + XReport mDailyReport; + + // + // Clean Specific Report ... + void CleanReport( + XReport &report // Specified Report + ) + { + // + datetime time = TimeCurrent(); + + // + // Reset Times ... + report.start = time; + report.end = -1; + + // + // Reset Account Info ... + FillReportAccountInfo(report); + + // + // Reset Summary Info ... + report.summaryInfo.maxDrawUp = 0; + report.summaryInfo.maxDrawDown = 0; + report.summaryInfo.longSignals = 0; + report.summaryInfo.numberOfTPs = 0; + report.summaryInfo.numberOfSLs = 0; + report.summaryInfo.shortSignals = 0; + report.summaryInfo.maxSignalVolume = 0; + report.summaryInfo.maxSameTimeSignals = 0; + + // + // Reset Volume Info ... + report.volumeInfo.staticVolume = 0; + report.volumeInfo.maxAllowedVolume = 0; + report.volumeInfo.volumeIncreaseMultiplier = 0; + report.volumeInfo.balanceGowingToApplyMultiplier = 0; + report.volumeInfo.staticVolumeCalculationMethod = NULL; + report.volumeInfo.balanceGrowingToIncreaseMaxAllowedVolume = 0; + + // + // Reset Signallers Info ... + CleanBuffer(report.signallersInfo); + } + void CleanReport( + ENUM_XREPORT_TYPES type // Specify Report Type + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + CleanReport(mMainReport); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + CleanReport(mMonthlyReport); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + CleanReport(mWeeklyReport); + break; + + // + // Daily ... + case XREPORT_DAILY: + CleanReport(mDailyReport); + break; + } + } + + // + // Update Specific Reports End Time ... + void FillReportEndTime( + XReport &report // Specified Report + ) + { + // + datetime time = TimeCurrent(); + report.end = time; + } + + // + // Filleing Report Account Info ... + void FillReportAccountInfo( + XReport &report // Specified Report + ) + { + // + FillReportEndTime(report); + + // + report.accountInfo.user = (string)mAccountInfo.GetUserAccount(); + report.accountInfo.name = mAccountInfo.GetName(); + report.accountInfo.server = mAccountInfo.GetServerName(); + report.accountInfo.broker = mAccountInfo.GetCompany(); + report.accountInfo.mode = mAccountInfo.GetTradeMode(); + report.accountInfo.leverage = mAccountInfo.GetLeverage(); + report.accountInfo.currency = mAccountInfo.GetCurrency(); + report.accountInfo.deposit = mAccountInfo.GetInitialBalance(); + report.accountInfo.balance = mAccountInfo.GetBalance(); + } + void FillReportAccountInfo( + ENUM_XREPORT_TYPES type // Specify Report Type + ) + { + // + switch (type) + { + // + // Main ... + case XREPORT_MAIN: + FillReportAccountInfo(mMainReport); + break; + + // + // Monthly ... + case XREPORT_MONTHLY: + FillReportAccountInfo(mMonthlyReport); + break; + + // + // Weekly ... + case XREPORT_WEEKLY: + FillReportAccountInfo(mWeeklyReport); + break; + + // + // Daily ... + case XREPORT_DAILY: + FillReportAccountInfo(mDailyReport); + break; + } + } + + // + // Filling Volume Info ... + void FillingVolumeInfo( + XReport &report, // Specified Report + // + double staticVolume, // Current Available Static Volume + string staticVolumeCalculationMethod, // Static Volume Calculation Method + double maxAllowedVolume, // Current Maximum Appliable Volume + double volumeIncreaseMultiplier, // Static Volume Increase Multiplier + double balanceGowingToApplyMultiplier, // Multiply Volume Based On Balance Growing + double balanceGrowingToIncreaseMaxAllowedVolume // Where to Increase MaxAllowed Volume + ) + { + // + FillReportEndTime(report); + + // + report.volumeInfo.staticVolume = staticVolume; + report.volumeInfo.maxAllowedVolume = maxAllowedVolume; + report.volumeInfo.volumeIncreaseMultiplier = volumeIncreaseMultiplier; + report.volumeInfo.staticVolumeCalculationMethod = staticVolumeCalculationMethod; + report.volumeInfo.balanceGowingToApplyMultiplier = balanceGowingToApplyMultiplier; + report.volumeInfo.balanceGrowingToIncreaseMaxAllowedVolume = balanceGrowingToIncreaseMaxAllowedVolume; + } + + // + // Add Signal to Report ... + void AddSignalToReport( + XReport &report, // Specified Report + const XSignal &signal, // Specified Signal + const string &providers[] // Specified Signal Providers + ) + { + // + FillReportEndTime(report); + + // + double volume = signal.volume; + bool isLong = signal.type == X_SIGNAL_LONG; + + // + // Update Longs and Shorts ... + if (isLong) + { + report.summaryInfo.longSignals++; + } + else + { + report.summaryInfo.shortSignals++; + } + + // + // Chack Max Volume ... + if (volume > report.summaryInfo.maxSignalVolume) + { + report.summaryInfo.maxSignalVolume = volume; + } + + // + // Update Signallers Info ... + for (int i = 0; i < ArraySize(providers); i++) + { + // + string iProvider = providers[i]; + + // + AddOrUpdateSignaller( + report, + iProvider, + signal); + } + } + + // + // Add or Update Signaller Info of Specific Report ... + void AddOrUpdateSignaller( + XReport &report, // Specified Report + const string provider, // Signal Provider name + const XSignal &signal // Specified Signal + ) + { + // + int providerIdx = -1; + int signallersInfoCount = 0; + bool isLong = signal.type == X_SIGNAL_LONG; + + // + // Prepare New One Provider ... + XSignallerInfo info = {}; + info.name = provider; + if (isLong) + { + info.longs = 1; + } + else + { + info.shorts = 1; + } + + // + // Find Provider idx if Exists ... + providerIdx = FindProviderInSignallersInfo( + provider, + report.signallersInfo); + + // + // Check IDX ... + if (providerIdx > -1) + { + // + // Update Exists ... + if (isLong) + { + report.signallersInfo[providerIdx].longs++; + } + else + { + report.signallersInfo[providerIdx].shorts++; + } + } + else + { + // + // Add New One ... + AddItemToBuffer( + info, + report.signallersInfo); + } + } + + // + // Add TP in Report ... + void AddTradeTPInReport( + XReport &report // Specified Report + ) + { + // + FillReportEndTime(report); + + // + report.summaryInfo.numberOfTPs++; + } + + // + // Add SL in Report ... + void AddTradeSLInReport( + XReport &report // Specified Report + ) + { + // + FillReportEndTime(report); + + // + report.summaryInfo.numberOfSLs++; + } + + // + // Update Number of Same Time Trades in Report ... + void UpdateMaxSameTimeTradesInReport( + XReport &report, // Specified Report + int value // number of same time trades + ) + { + // + // Validate Args ... + if (value <= report.summaryInfo.maxSameTimeSignals) + { + return; + } + + // + FillReportEndTime(report); + + // + report.summaryInfo.maxSameTimeSignals = value; + } + + // + // Update Number of Same Time Trades in Report ... + void UpdateMaxDrawUpInReport( + XReport &report, // Specified Report + double value // draw up value + ) + { + // + // Validate Args ... + if (value <= report.summaryInfo.maxDrawUp) + { + return; + } + + // + FillReportEndTime(report); + + // + report.summaryInfo.maxDrawUp = value; + } + + // + // Update Number of Same Time Trades in Report ... + void UpdateMaxDrawDownInReport( + XReport &report, // Specified Report + double value // draw down value + ) + { + // + // Validate Args ... + if (value <= report.summaryInfo.maxDrawDown) + { + return; + } + + // + FillReportEndTime(report); + + // + report.summaryInfo.maxDrawDown = value; + } + + // + // Update Min Balance for Open Trades Value in Report ... + void UpdateMinBalanceForOpenTradesInReport( + XReport &report, // Specified Report + double value // min balance for open trades + ) + { + // + // Validate Arg ... + if (value <= 0) + { + return; + } + + // + FillReportEndTime(report); + + // + report.accountInfo.minBalanceForOpenTrades = value; + } + + // + // Generate Specific Report String Representation ... + string GenerateReportString( + XReport &report, // Specified Report + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + // Start and End Date ... + result += "Start: " + (string)report.start + separator; + result += "End: " + (string)report.end + separator; + + // + // Account Info ... + string accountStr = GenerateAccountInfoReportString(report.accountInfo); + result += "Account: " + separator + accountStr + separator; + + // + // Summary Info ... + string summaryStr = GenerateSummaryInfoReportString(report.summaryInfo); + result += "Summary: " + separator + summaryStr + separator; + + // + // Volume Info ... + string volumeStr = GenerateVolumeInfoReportString(report.volumeInfo); + result += "Volume: " + separator + volumeStr + separator; + + // + // Signallers Info ... + string signallersStr = GenerateSignallersInfoReportString(report.signallersInfo); + result += "Signallers: " + separator + signallersStr + separator; + + // + return result; + } + + // + // Generate Account info String Representation ... + string GenerateAccountInfoReportString( + XAccountInfo &info, // Specified Account Info + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + // Generate Report ... + result += "user: " + info.user + separator; + result += "name: " + info.name + separator; + result += "server: " + info.server + separator; + result += "broker: " + info.broker + separator; + result += "mode: " + EnumToString(info.mode) + separator; + result += "leverage: " + (string)info.leverage + separator; + result += "currency: " + info.currency + separator; + result += "deposit: " + (string)info.deposit + separator; + result += "balance: " + (string)info.balance + separator; + result += "minBalanceForTrading: " + (string)info.minBalanceForOpenTrades + separator; + + // + return result; + } + + // + // Generate Summary info String Representation ... + string GenerateSummaryInfoReportString( + XSummaryInfo &info, // Specified Summary Info + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + // Generate Report ... + result += "longSignals: " + (string)info.longSignals + separator; + result += "shortSignals: " + (string)info.shortSignals + separator; + result += "numberOfTps: " + (string)info.numberOfTPs + separator; + result += "numberOfSLs: " + (string)info.numberOfSLs + separator; + result += "maxDrawUp: " + (string)info.maxDrawUp + separator; + result += "maxDrawDown: " + (string)info.maxDrawDown + separator; + result += "maxSignalVolume: " + (string)info.maxSignalVolume + separator; + result += "maxSameTimeSignals: " + (string)info.maxSameTimeSignals + separator; + + // + return result; + } + + // + // Generate Volume info String Representation ... + string GenerateVolumeInfoReportString( + XVolumeInfo &info, // Specified Volume Info + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + // Generate Report ... + result += "staticVolume: " + (string)info.staticVolume + separator; + result += "staticVolumeCalculationMethod: " + info.staticVolumeCalculationMethod + separator; + result += "maxAllowedVolume: " + (string)info.maxAllowedVolume + separator; + result += "volumeIncreaseMultiplier: " + (string)info.volumeIncreaseMultiplier + separator; + result += "balanceGowingToApplyMultiplier: " + (string)info.balanceGowingToApplyMultiplier + separator; + result += "balanceGrowingToIncreaseMaxAllowedVolume: " + (string)info.balanceGrowingToIncreaseMaxAllowedVolume + separator; + + // + return result; + } + + // + // Generate Signallers info String Representation ... + string GenerateSignallersInfoReportString( + XSignallerInfo &infos[], // Specified Signallers Info + string separator = "\n" // Separator + ) + { + // + string result = ""; + + // + // Validate Signallers Array Size ... + int signallersCount = ArraySize(infos); + if (signallersCount <= 0) + { + // + result += "EMPTY" + separator; + return result; + } + + // + // Generate Report ... + for (int i = 0; i < signallersCount; i++) + { + // + XSignallerInfo iSignaller = infos[i]; + + // + result += "name: " + iSignaller.name + separator; + result += "longs: " + (string)iSignaller.longs + separator; + result += "shorts: " + (string)iSignaller.shorts + separator; + + // + if (i < signallersCount - 1) + { + result += separator; + } + } + // + return result; + } + + // + // Find a Provider Index in SignallersInfo ... + int FindProviderInSignallersInfo( + string provider, // Specified Provider Name ... + XSignallerInfo &infoBuffer[] // Specified XSignallerInfo Buffer ... + ) + { + // + int result = -1; + + // + int bufferSize = ArraySize(infoBuffer); + if (bufferSize <= 0) + { + return result; + } + + // + // Loop through buffer to find provider index ... + for (int i = 0; i < bufferSize; i++) + { + // + XSignallerInfo iInfo = infoBuffer[i]; + + // + if (iInfo.name != provider) + { + continue; + } + + // + result = i; + } + + // + return result; + } +}; + +// +// a Class For Collectiong Info ... +class XCCollector : public XCBase +{ + // + // Public ... +public: + // + // Constructor ... + XCCollector() + { + Reset(); + } + + // + // Deconstructor ... + ~XCCollector() {} + + // + // Reset All Collectors ... + void Reset() + { + Clean(); + } + + // + // Count Data ... + int Count() + { + // + int result = 0; + + // + result = ArraySize(mTimes); + + // + return result; + } + + // + // TODO: Implement Business Logic here ... + + // + // Add Specific item to Collection ... + bool Add( + XCollector &item // Specified Info + ) + { + // + bool result = false; + + // + // Validate Args ... + result = IsValid( + item, + false); + if (!result) + { + return result; + } + + // + // Add Items Values to Buffers ... + // + AddItemToBuffer( + item.time, + mTimes); + + // + AddItemToBuffer( + item.volume, + mVolumes); + + // + AddItemToBuffer( + item.maxDrawDown, + mMaxDrawDowns); + + // + AddItemToBuffer( + item.maxAllowedVolume, + mMaxAllowedVolumes); + + // + AddItemToBuffer( + item.minBalanceForOpenTrade, + mMinBalanceForTradePrices); + + // + return result; + } + + // + // Retrieve Specific Item ... + bool Get( + XCollector &item, // Hold's Result + int index = 0 // Specified Index to Retrieve + ) + { + // + bool result = false; + + // + result = IsValidIndex(index); + if (!result) + { + return result; + } + + // + // Filling Item ... + item.time = mTimes[index]; + item.volume = mVolumes[index]; + item.maxDrawDown = mMaxDrawDowns[index]; + item.maxAllowedVolume = mMaxAllowedVolumes[index]; + item.minBalanceForOpenTrade = mMinBalanceForTradePrices[index]; + + // + return result; + } + XCollector Get( + int index = 0 // Specified Index to Retrieve + ) + { + // + XCollector result = {}; + + // + bool isValidIndex = IsValidIndex(index); + if (!isValidIndex) + { + return result; + } + + // + // Filling Item ... + result.time = mTimes[index]; + result.volume = mVolumes[index]; + result.maxDrawDown = mMaxDrawDowns[index]; + result.maxAllowedVolume = mMaxAllowedVolumes[index]; + result.minBalanceForOpenTrade = mMinBalanceForTradePrices[index]; + + // + return result; + } + bool Get( + XCollector &item, // Hold's Result + datetime time // Specified Index to Retrieve + ) + { + // + bool result = false; + + // + if (time <= 0) + { + return result; + } + + // + int timesCount = ArraySize(mTimes); + result = timesCount > 0; + if (!result) + { + return result; + } + + // + int index = -1; + for (int i = 0; i < timesCount; i++) + { + // + datetime iTime = mTimes[i]; + + // + if (iTime == time) + { + // + index = i; + break; + } + } + + // + result = index >= 0; + if (!result) + { + return result; + } + + // + result = Get( + item, + index); + + // + return result; + } + XCollector Get( + datetime time // Specified Index to Retrieve + ) + { + // + XCollector result = {}; + + // + if (time <= 0) + { + return result; + } + + // + int timesCount = ArraySize(mTimes); + if (timesCount <= 0) + { + return result; + } + + // + int index = -1; + for (int i = 0; i < timesCount; i++) + { + // + datetime iTime = mTimes[i]; + + // + if (iTime == time) + { + // + index = i; + break; + } + } + + // + if (index <= -1) + { + return result; + } + + // + result = Get( + index); + + // + return result; + } + + // + // Retrieve All ... + void GetAll( + XCollector &result[], // Hold's Result + bool reversal = false // Extract Direction + ) + { + // + CleanBuffer(result); + + // + int timesCount = ArraySize(mTimes); + if (timesCount <= 0) + { + return; + } + + // + if (!reversal) + { + // + for (int i = 0; i < timesCount; i++) + { + // + XCollector iCollector = Get(i); + + // + AddItemToBuffer( + iCollector, + result); + } + } + else + { + // + for (int i = timesCount - 1; i >= 0; i--) + { + // + XCollector iCollector = Get(i); + + // + AddItemToBuffer( + iCollector, + result); + } + } + } + + // + // Extract History ... + void Extract( + XCollector &result[], // Hold's Result + int start, // Start Index + int end // End Index + ) + { + // + CleanBuffer(result); + + // + // Validate Args ... + if ( + end < 0 || + start < 0 || + (start == 0 && end == 0) || + MathAbs(start - end == 0)) + { + return; + } + + // + // Validate Start and End Index ... + bool isValidEnd = IsValidIndex(end); + bool isValidStart = IsValidIndex(start); + if (!isValidEnd || !isValidStart) + { + return; + } + + // + bool direction = end > start; + if (direction) + { + // + for (int i = start; i < end - 1; i++) + { + // + XCollector iCollect = Get(i); + + // + AddItemToBuffer( + iCollect, + result); + } + } + else + { + // + for (int i = end - 1; i >= start; i--) + { + // + XCollector iCollect = Get(i); + + // + AddItemToBuffer( + iCollect, + result); + } + } + } + + // + // Validate an Item ... + bool IsValid( + XCollector &item, // Specified Info + bool ignoreTime = true // Ignore Times Checking ... + ) + { + // + bool result = false; + + // + // Check Each Items contains Correct Value ... + // + result = item.volume >= 0; + if (!result) + { + return result; + } + + // + result = item.maxDrawDown >= 0; + if (!result) + { + return result; + } + + // + result = item.maxAllowedVolume >= 0; + if (!result) + { + return result; + } + + // + result = item.minBalanceForOpenTrade >= 0; + if (!result) + { + return result; + } + + // + // Check Time has Proper Value ... + result = item.time > 0; + if (!result) + { + return result; + } + + // + // Check time bigger than last Time ... + int timesCount = ArraySize(mTimes); + if ( + !ignoreTime && + timesCount >= 0) + { + // + // Retrieve Last Added Times ... + datetime lastTime; + result = GetLastItem(lastTime, mTimes); + if (!result) + { + return result; + } + + // + // Compare Last Time by current Time ... + result = item.time > lastTime; + if (!result) + { + return result; + } + } + + // + return result; + } + + // + // Generate Logging String Representation ... + string GenerateString( + XCollector &item, // Specified Info + string separator = "\n" // Separator Character + ) + { + // + string result = ""; + + // + result += "time: " + (string)item.time + separator; + result += "volume: " + (string)item.volume + separator; + result += "maxDrawDown: " + (string)item.maxDrawDown + separator; + result += "maxAllowedVolume: " + (string)item.maxAllowedVolume + separator; + result += "minBalanceForOpenTrade: " + (string)item.minBalanceForOpenTrade + separator; + + // + return result; + } + + // + // Protected ... +protected: + // + // Private ... +private: + // + // Max Draw Up touched till now ... + double mMaxDrawUp; + + // + // Max Draw Down touched till now ... + double mMaxDrawDown; + + // + // Last Time for Checks ... + datetime mTimes[]; + + // + // Volume at the Check Time ... + double mVolumes[]; + + // + // DrawDown for each Check ... + double mMaxDrawDowns[]; + + // + // Max Allowed Volume for each check ... + double mMaxAllowedVolumes[]; + + // + // Min Balance for Open Trades for Each Check ... + double mMinBalanceForTradePrices[]; + + // + // Reset ... + void Clean() + { + // + mMaxDrawUp = 0; + mMaxDrawDown = 0; + + // + CleanBuffer(mTimes); + CleanBuffer(mVolumes); + CleanBuffer(mMaxDrawDowns); + CleanBuffer(mMaxAllowedVolumes); + CleanBuffer(mMinBalanceForTradePrices); + } + + // + // Validate Index ... + bool IsValidIndex( + int index // Specified Index + ) + { + // + bool result = false; + + // + int bufferSize = ArraySize(mTimes); + if (bufferSize <= 0) + { + return result; + } + + // + result = index <= bufferSize - 1; + + // + return result; + } +}; + +// +// a Class for Managing Volumes ... +class XCVolumeManager : public XCBase +{ + // + // Public ... +public: + // + // Constructor ... + XCVolumeManager( + double staticVolumeRate, // Static Volume Calculation Mutiplier + ENUM_STATIC_VOLUME_METHODS volumeMethod = X_STATIC_VOLUME_BASED_ON_DEPOSIT, // How to Calculate Static Volume + double volumeMultiplier = 0, // Volume Multiplier + double volumeMultiplierAppliedRate = 0, // Apply Volume Multiplier when Balance Increased by this rate + double maxAllowedVolume = 0, // Max Allowed Volume + double increaseMaxAllowedVolumeRate = 0 // Increase Max Allowed Volumes when Balance Increased by this rate + ) + { + // + mAccountInfo = new XCAccountInfo(); + + // + ResetForceVolumeMultiplier(); + + // + mVolumeMethod = volumeMethod; + mStaticVoluemRate = staticVolumeRate; + mVolumeMultiplier = volumeMultiplier; + mMaxAllowedVolume = maxAllowedVolume; + mVolumeMultiplierAppliedRate = volumeMultiplierAppliedRate; + mIncreaseMaxAllowedVolumeRate = increaseMaxAllowedVolumeRate; + } + + // + // Deconstructor ... + ~XCVolumeManager(void) {} + + // + // Check Volume Multiplier ... + bool CanUseVolumeMultiplier() + { + // + bool result = false; + + // + result = + mVolumeMultiplier > 0 && + mVolumeMultiplierAppliedRate > 0; + + // + return result; + } + + // + // Check Max Volume ... + bool CanUseMaxVolume() + { + // + bool result = false; + + // + result = + mMaxAllowedVolume > 0; + + // + return result; + } + + // + // Calculate Volume for Position ... + double CalculateVolume( + int numberOfOpenPositions = 0, // Number Of Open Signals + string symbol = NULL // Specify Symbol + ) + { + // + double result = 0; + + // + // Normalize Symbol ... + if (StringLen(symbol) == 0) + { + symbol = _Symbol; + } + + // + // Static Volume ... + result = GetStaticVolume(); + + // + double multiplier = GetVolumeMultiplier(); + result *= multiplier; + + // + // Check Max Allowed Volume Exists ... + double maxAllowedVolume = GetMaxAllowedVolume(); + if (maxAllowedVolume > 0) + { + // + result = + result > maxAllowedVolume + ? maxAllowedVolume + : result; + } + + // + // Check Number of Open Positions ... + if (numberOfOpenPositions >= 0) + { + // + // Decrease Volume ... + result /= (1 + numberOfOpenPositions); + } + + // + // Apply Force Volume Multiplier ... + result *= mForceVolumeMultiplier; + + // + // Retrieve Symbol Volume Info ... + result = NormalizeVolume(result, symbol, 2); + + // + return result; + } + + // + // Calculate Volume Multiplier ... + double GetVolumeMultiplier() + { + // + double result = 1; + + // + double deposit = mAccountInfo.GetInitialBalance(); + double balance = mAccountInfo.GetBalance(); + bool canUseVolumeMultiplier = CanUseVolumeMultiplier(); + if ( + balance < deposit || + !canUseVolumeMultiplier) + { + return result; + } + + // + // Apply Multiplier to Volume ... + double baseGrowBalance = deposit * mVolumeMultiplierAppliedRate; + double balanceGrows = balance - deposit; + if (balanceGrows < baseGrowBalance) + { + return result; + } + + // + double applyMultiplierTimes = balanceGrows / baseGrowBalance; + double roundedApplyMultiplierTimes = MathRound(applyMultiplierTimes); + + // + if (applyMultiplierTimes < roundedApplyMultiplierTimes) + { + applyMultiplierTimes -= (1 - (roundedApplyMultiplierTimes - applyMultiplierTimes)); + } + + // + // Calculate result ... + result = applyMultiplierTimes * mVolumeMultiplier; + + // + return result; + } + + // + // Retrieve Required Balance Grows for Increase Max Allowed Volume ... + double GetIncreaseMaxAllowedVolumeBalance() + { + // + double result = 0; + + // + if ( + mMaxAllowedVolume <= 0 || + mIncreaseMaxAllowedVolumeRate <= 0) + { + return result; + } + + // + result = mAccountInfo.GetInitialBalance() * mIncreaseMaxAllowedVolumeRate; + + // + return result; + } + + // + // Calculate Max Allowed Volume ... + double GetMaxAllowedVolume() + { + // + double result = 0; + + // + // Validate Args ... + result = + mMaxAllowedVolume <= 0 + ? 0 + : mMaxAllowedVolume; + + // + double deposit = mAccountInfo.GetInitialBalance(); + double balance = mAccountInfo.GetBalance(); + bool canUseMaxAllowedVolume = CanUseMaxVolume(); + if ( + balance <= deposit || + !canUseMaxAllowedVolume || + mIncreaseMaxAllowedVolumeRate <= 0) + { + // + return result; + } + + // + // Apply Multiplier to Volume ... + double baseGrowBalance = GetIncreaseMaxAllowedVolumeBalance(); + double balanceGrows = balance - deposit; + if (balanceGrows < baseGrowBalance) + { + return result; + } + + // + double applyMultiplierTimes = balanceGrows / baseGrowBalance; + double roundedApplyMultiplierTimes = MathRound(applyMultiplierTimes); + + // + if (applyMultiplierTimes < roundedApplyMultiplierTimes) + { + applyMultiplierTimes -= (1 - (roundedApplyMultiplierTimes - applyMultiplierTimes)); + } + + // + result *= applyMultiplierTimes; + + // + return result; + } + + // + // Get Static Volume ... + double GetStaticVolume() + { + // + double result = 0; + + // + double deposit = mAccountInfo.GetInitialBalance(); + double balance = mAccountInfo.GetBalance(); + + // + switch (mVolumeMethod) + { + // + case X_STATIC_VOLUME_BASED_ON_DEPOSIT: + result = mStaticVoluemRate * deposit; + break; + + // + case X_STATIC_VOLUME_BASED_ON_BALANCE: + result = mStaticVoluemRate * balance; + break; + } + + // + return result; + } + + // + // Reset Froce Volume Multiplier ... + void ResetForceVolumeMultiplier() + { + mForceVolumeMultiplier = 1; + } + + // + // Retrieve Current Force Volume Multiplier ... + double GetCurrentForceVolumeMultiplier() + { + return mForceVolumeMultiplier; + } + + // + // Retrieve Next Increase Multiplier Price ... + double GetIncreaseMultiplierBalance() + { + return mAccountInfo.GetInitialBalance() * mVolumeMultiplierAppliedRate; + } + + // + // Change Force Volume Multiplier ... + void ChangeForceVolumeMultiplier( + double rate // Change rate + ) + { + // + // Normalize rate ... + if (rate <= 1) + { + rate = 1; + } + + // + mForceVolumeMultiplier = rate; + } + + // + // Increase Force Volume Multiplier ... + void IncreaseForceVolumeMultiplier() + { + mForceVolumeMultiplier += 0.5; + } + + // + // Decrease Force Volume Multiplier ... + void DecreaseForceVolumeMultiplier() + { + // + if (mForceVolumeMultiplier <= 1) + { + return; + } + + // + mForceVolumeMultiplier -= 0.5; + } + + // + // Generate Current State Log String ... + string GenerateStateString( + string separator = "\n" // Log Separator ... + ) + { + // + string result = ""; + + // + // Normallize Separator ... + if (StringLen(separator) == 0) + { + separator = "\n"; + } + + // + result += "ForceVolumeMultiplier: " + (string)mForceVolumeMultiplier + separator; + // + result += "StaticVoluemRate: " + (string)mStaticVoluemRate + separator; + result += "StaticVoluem: " + (string)GetStaticVolume() + separator; + result += "VolumeMethod: " + EnumToString(mVolumeMethod) + separator; + // + result += "VolumeMultiplier: " + (string)mVolumeMultiplier + separator; + result += "VolumeMultiplierAppliedRate: " + (string)mVolumeMultiplierAppliedRate + separator; + // + result += "MaxAllowedVolume: " + (string)mMaxAllowedVolume + separator; + result += "IncreaseMaxAllowedVolumeRate: " + (string)mIncreaseMaxAllowedVolumeRate + separator; + + // + return result; + } + + // + // Protected ... +protected: + // + // Private ... +private: + // + // an Instance of Account Info for reading Balance and Deposit and etc ... + XCAccountInfo mAccountInfo; + + // + // Force Volume Rate Multiplier ... + double mForceVolumeMultiplier; + + // + // Static Volume Calculation Mutiplier ... + double mStaticVoluemRate; + + // + // How to Calculate Static Volume ... + ENUM_STATIC_VOLUME_METHODS mVolumeMethod; + + // + // Volume Multiplier ... + double mVolumeMultiplier; + + // + // Apply Volume Multiplier when Balance Increased by this rate ... + double mVolumeMultiplierAppliedRate; + + // + // Max Allowed Volume + double mMaxAllowedVolume; + + // + // Increase Max Allowed Volumes when Balance Increased by this rate + double mIncreaseMaxAllowedVolumeRate; +}; + +// +// a Class For Managing Signals Additional Data ... +class XCSignalManager : public XCBase +{ + // + // Public ... +public: + // + // Constructor ... + XCSignalManager(void) + { + CleanData(); + } + + // + // Deconstructor ... + ~XCSignalManager(void) {} + + // + void Reset() + { + CleanData(); + } + + // + // Retrieve All Signals ... + void GetAll( + XSignal &result[] // Hold's Result + ) + { + // + CleanBuffer(result); + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + AddItemToBuffer( + iSignal, + result); + } + } + + // + // Count Items ... + int Count() + { + return ArraySize(mSignals); + } + + // + // Retrieve Specific Signal by Ticket ... + XSignal Get( + ulong ticket // Signals Ticket ... + ) + { + // + XSignal result = {}; + + // + // Check Exists ... + bool isExists = IsExists(ticket); + if (!isExists) + { + return result; + } + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + if (iSignal.ticket == ticket) + { + // + result = iSignal; + break; + } + } + + // + return result; + } + + // + // Check Signal Exists or not ... + bool IsExists( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + if (iSignal.ticket == ticket) + { + // + result = true; + break; + } + } + + // + return result; + } + bool IsExists( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + if (iSignal.ticket == signal.ticket) + { + // + result = true; + break; + } + } + + // + return result; + } + + // + // Add Signal ... + bool Add( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + // Validate Args ... + if (signal.ticket <= 0) + { + return result; + } + + // + // Chekc Signal Exists ... + bool isExists = IsExists(signal); + if (isExists) + { + return result; + } + + // + AddItemToBuffer( + signal, + mSignals); + result = true; + + // + return result; + } + + // + // Update Specific Buffer ... + bool Update( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + // Validate Args ... + if (signal.ticket <= 0) + { + return result; + } + + // + // Chekc Signal Exists ... + bool isExists = IsExists(signal); + if (!isExists) + { + return result; + } + + // + // Remove Signal ... + Remove(signal); + + // + // Add new One ... + AddItemToBuffer( + signal, + mSignals); + + // + result = true; + + // + return result; + } + + // + // Remove Signal ... + bool Remove( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + // Check Signal Exists ... + bool isExists = IsExists(ticket); + if (!isExists) + { + return result; + } + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return result; + } + + // + XSignal signals[]; + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + if (iSignal.ticket != ticket) + { + AddItemToBuffer( + iSignal, + signals); + } + } + + // + // Now we have to Clean All Signals and Replace them by signals[] buffer ... + UpdateData(signals); + + // + result = true; + return result; + } + bool Remove( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + // Check Signal Exists ... + bool isExists = IsExists(signal); + if (!isExists) + { + return result; + } + + // + int signalsCount = ArraySize(mSignals); + if (signalsCount <= 0) + { + return result; + } + + // + XSignal signals[]; + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = mSignals[i]; + + // + if (iSignal.ticket != signal.ticket) + { + AddItemToBuffer( + iSignal, + signals); + } + } + + // + // Now we have to Clean All Signals and Replace them by signals[] buffer ... + UpdateData(signals); + + // + result = true; + return result; + } + + // + // Add Or Update ... + bool AddOrUpdate( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + // Validate Args ... + if (signal.ticket <= 0) + { + return result; + } + + // + // Chekc Signal Exists ... + bool isExists = IsExists(signal); + if (!isExists) + { + result = Add(signal); + } + else + { + result = Update(signal); + } + + // + return result; + } + + // + // Protected ... +protected: + // + // Private ... +private: + // + // Holds Signals ... + XSignal mSignals[]; + + // + // Clean All Exists Data ... + void CleanData() + { + CleanBuffer(mSignals); + } + + // + // Update Data ... + void UpdateData( + XSignal &source[] // a Buffer which needs to Replace ... + ) + { + // + CleanData(); + + // + int sourceCount = ArraySize(source); + if (sourceCount <= 0) + { + return; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + XSignal iSignal = source[i]; + + // + AddItemToBuffer( + iSignal, + mSignals); + } + } +}; + +// +// XSaherElm Trade Class ... +class XCTrade : public XCBase +{ + // + // all public features ... +public: + // + // Constructor ... + void XCTrade( + string tag, // Specify a Tag for Trader instance + string symbol, // Specify Trader Symbol + int slippage, // Specify Slippage + ulong magicNumber, // Specify Magic Number + bool useVirtualTPSL, // Use Virtual TP SL + int maxAllowedTrades, // Specify Max Allowed Trades + double minBallanceForOpenTrades, // Specify Minimum Balance for Open Trades + double minAllowedFreeMarginForOpenTrades, // Specify Minimum Free Marging for Open Trades + bool useSignalProtector = true // Specify Use Signal Protector or not + ) + { + // + mTag = tag; + mSymbol = symbol; + mSlippage = slippage; + mMagicNumber = magicNumber; + mUseVirtualTPSL = useVirtualTPSL; + mMaxAllowedTrades = maxAllowedTrades; + mMinBallanceForOpenTrades = minBallanceForOpenTrades; + mMinAllowedFreeMarginForOpenTrades = minAllowedFreeMarginForOpenTrades; + + // + mTrader = new XSCTrade(); + + // + mTrader.SetAsyncMode(false); + mTrader.SetDeviationInPoints(mSlippage); + mTrader.SetExpertMagicNumber(mMagicNumber); + + // + // Setting Log Level ... + mTrader.LogLevel(LOG_LEVEL_ERRORS); + + // + mSignalManager = new XCSignalManager(); + + // + Reset(); + } + + // + // Deconstructor ... + void ~XCTrade() + { + } + + // + // START Configuring Class Functions ... + // + + // + // Reset all Variables ... + void Reset() + { + // + mSignalManager.Reset(); + + // + mDaysForRead = 1; + mScanStarted = false; + + // + // Reset On Trade Counter ... + ResetOnTradeContext(); + + // + // Init On Trade Context ... + InitOnTradeContext(); + } + + // + // END Configuring Class Functions ... + // + + // + // START Count ... + // + + // + // Count Open Positions ... + int Count() + { + // + int result = 0; + + // + int total = PositionsTotal(); + for (int i = 0; i < total; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + if (mPositionInfo.Symbol() != mSymbol) + { + continue; + } + + // + result++; + } + + // + return result; + } + + // + // Count Longs ... + int CountLongs() + { + int result = CountByType(X_SIGNAL_LONG); + return result; + } + + // + // Count Shorts ... + int CountShorts() + { + int result = CountByType(X_SIGNAL_SHORT); + return result; + } + + // + // Count Specific Type Of Positions ... + int CountByType(ENUM_POSITION_TYPE type) + { + // + int result = 0; + + // + int total = PositionsTotal(); + for (int i = 0; i < total; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Symbol() != mSymbol) + { + continue; + } + + // + if (mPositionInfo.PositionType() != type) + { + continue; + } + + // + result++; + } + + // + return result; + } + + // + // Count By Type ... + int CountByType(ENUM_X_SIGNAL_TYPE type) + { + // + // Validate Args ... + ENUM_POSITION_TYPE mType = POSITION_TYPE_BUY; + if (type == X_SIGNAL_LONG) + { + mType = POSITION_TYPE_BUY; + } + else if (type == X_SIGNAL_SHORT) + { + mType = POSITION_TYPE_SELL; + } + + // + int result = CountByType(mType); + return result; + } + + // + // END Count ... + // + + // + // START Retrieve ... + // + + // + // Retrieve Specified Position by it's Ticket ... + XSignal GetSignal( + ulong ticket // Specified Ticket + ) + { + // + XSignal result = {}; + + // + result = PositionToSignal(ticket); + + // + return result; + } + + // + // Get Last Signal ... + XSignal GetLastSignal() + { + // + XSignal result = {}; + + // + XSignal signals[]; + GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + result = signals[0]; + + // + return result; + } + + // + // Retrieve Last Executed Signal ... + bool GetLastSignal(XSignal &signal) + { + // + bool result = false; + + // + XSignal signals[]; + GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + signal = signals[0]; + result = true; + + // + return result; + } + + // + // Retrieve All Positions ... + void GetSignals( + XSignal &result[] // Holds Result ... + ) + { + // + CleanBuffer(result); + + // + int totalPositions = PositionsTotal(); + for (int i = 0; i < totalPositions; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + if (mPositionInfo.Symbol() != mSymbol) + { + continue; + } + + // + // Position to Signal ... + XSignal signal = PositionToSignal(i); + Add( + signal, + result); + } + } + + // + // Retrieve Type Specific Signals ... + void GetSignals( + XSignal &result[], // Holds Result ... + ENUM_X_SIGNAL_TYPE type // Specified Sginal Type ... + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals(signals); + + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = signalsCount - 1; i >= 0; i--) + { + // + XSignal iSignal = signals[i]; + + // + if (type == X_SIGNAL_UNKNOWN) + { + Add( + iSignal, + result); + } + else if (iSignal.type == type) + { + Add( + iSignal, + result); + } + } + } + + // + // Filter Signals By Searching Comments ... + void FilterSignals( + XSignal &result[], // Holds Result ... + const string query, // Search in Comment Qeury ... + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specified Sginal Type ... + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + + // + // Validate Args ... + if ( + StringLen(query) <= 0 || + signalsCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + int queryPos = StringFind( + iSignal.comment, + query); + bool isContains = queryPos > -1; + if (!isContains) + { + continue; + } + + // + Add( + iSignal, + result); + } + } + + // + // Get All Trades Which Candle Passed after Open ... + void GetOldSignals( + XSignal &result[], // Holds Result + int life, // Max Candle Passed after Trades Open + ENUM_TIMEFRAMES period = NULL, // Calculate Candles based on time frame + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + // Normalize Period ... + if (period == NULL) + { + period = _Period; + } + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + // Current Time Frame Candle Index ... + int currentBarIndex = 0; + + // + // Loop through Positions ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + // Retrieve Trade Open Bar Index based on Current Period ... + int tradeOpenBarIndex = iBarShift( + mSymbol, + period, + iSignal.time); + + // + // Calculate Trade Life ... + int diff = MathAbs(currentBarIndex - tradeOpenBarIndex); + + // + bool isPassed = diff >= life; + if (isPassed) + { + // + Add( + iSignal, + result); + } + } + } + + // + // Get In Profit Signals ... + void GetInProfitSignals( + XSignal &result[], // Holds Result + double minProfit = 0, // Minimum Profit To Close Trades + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + bool isPassed = minProfit <= 0 && iSignal.profit > 0 + ? true + : iSignal.profit >= minProfit; + if (isPassed) + { + Add( + iSignal, + result); + } + } + } + + // + // Get In Drawdown Signals ... + void GetInDrawdownSignals( + XSignal &result[], // Holds Result + double maxDrawDown = 0, // Minimum Profit To Close Trades + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + bool isPassed = maxDrawDown <= 0 && iSignal.profit < 0 + ? true + : iSignal.profit >= (-1 * maxDrawDown); + if (isPassed) + { + Add( + iSignal, + result); + } + } + } + + // + // Retrieve Max In Draw Down Trade ... + XSignal GetMaxInDrawdownSignal( + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + XSignal result = {}; + + // + XSignal signals[]; + GetInDrawdownSignals( + signals, + 0, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + result = + (result.ticket <= 0 && + result.profit == 0) || + result.profit > iSignal.profit + ? iSignal + : result; + } + + // + return result; + } + + // + // Calculate Profits Of all Open Signals ... + double GetSignalsProfit( + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + double result = 0; + + // + XSignal signals[]; + GetSignals(signals, type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + result += iSignal.profit; + } + + // + return result; + } + + // + // END Retrieve ... + // + + // + // START Signal Execution Actions ... + // + + // + // Execute a Signal in Market ... + ENUM_EXECUTION_SIGNAL_RESULT ExecuteSignal( + XSignal &signal, // Specified Signal + bool ignoreNumberOfTraes = false, // Ignore Number of Trades + bool checkAccountConditions = true // Check Account Balance, Equity and Free Margin for Signal Execution + ) + { + // + ENUM_EXECUTION_SIGNAL_RESULT result = X_TRADER_UNKNOWN_ERROR; + + // + // Validate Signal ... + bool isValid = IsValidSignal(signal); + if (!isValid) + { + // + result = X_TRADER_INVALID_SIGNAL_ERROR; + return result; + } + + // + // Check Account Equity ... + bool isEquityPassed = !checkAccountConditions + ? true + : IsEquityReadyForTrade(); + if (!isEquityPassed) + { + // + result = X_TRADER_NOT_ENOUGH_EQUITY_ERROR; + return result; + } + + // + // Check Account Balance ... + bool isBalancePassed = !checkAccountConditions + ? true + : IsBalanceReadyForTrade(); + if (!isBalancePassed) + { + // + result = X_TRADER_NOT_ENOUGH_BALANCE_ERROR; + return result; + } + + // + // Check Account FreeMargin ... + bool isFreeMarginPassed = !checkAccountConditions + ? true + : IsFreeMarginReadyForTrade(); + if (!isFreeMarginPassed) + { + // + result = X_TRADER_NOT_ENOUGH_MARIGIN_ERROR; + return result; + } + + // + // Check Number of Open Trades ... + int openTradesCount = Count(); + bool isTradeCountPassed = ignoreNumberOfTraes + ? true + : openTradesCount < mMaxAllowedTrades; + if (!isTradeCountPassed) + { + // + result = X_TRADER_MAX_TRADES_REACHED_ERROR; + return result; + } + + // + bool isExecuted = + signal.type == X_SIGNAL_LONG + ? Buy( + signal.volume, + signal.entry, + mUseVirtualTPSL + ? 0 + : signal.sl, + mUseVirtualTPSL + ? 0 + : signal.tp, + signal.comment) + : signal.type == X_SIGNAL_SHORT + ? Sell( + signal.volume, + signal.entry, + mUseVirtualTPSL + ? 0 + : signal.sl, + mUseVirtualTPSL + ? 0 + : signal.tp, + signal.comment) + : false; + if (isExecuted) + { + // + ulong ticket = PositionGetTicket(PositionsTotal() - 1); + + // + signal.id = ticket; + signal.ticket = ticket; + + // + AddOrUpdateSignalInfo(signal); + + // + result = X_TRADER_SUCCEED_EXECUTION; + } + + // + return result; + } + + // + // This Function, Handling Following Works on Open Positions: + // - Close On SL if Reached ... + // - Close On TP if Reached ... + // - Make Risk Free Trades ... + bool HandleSignals( + XTraderHandlerResult &handlerResult, // Holds Result + bool ignoreRiskFree = false // Ignore Risk Free Trdaes + ) + { + // + bool result = false; + + // + // Cleanup Result ... + CleanBuffer(handlerResult.sl); + CleanBuffer(handlerResult.tp); + CleanBuffer(handlerResult.rf); + + // + // Reading Open Positions ... + XSignal signals[]; + GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + double deviation = mSlippage * GetPoints(mSymbol); + + // + // Loop ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + bool isLong = iSignal.type == X_SIGNAL_LONG; + double entry = GetEntry(iSignal.symbol, iSignal.type); + double exit = GetExit(iSignal.symbol, iSignal.type); + double spread = GetSpread(iSignal.symbol); + double appliedTPPrice = + iSignal.tp > 0 + ? isLong + ? iSignal.tp - deviation + : iSignal.tp + deviation + : 0; + double appliedSLPrice = + iSignal.sl > 0 + ? isLong + ? iSignal.sl + deviation + : iSignal.sl - deviation + : 0; + + // + double usedPrice = exit; + + // + bool isSLTouched = + isLong + ? usedPrice <= appliedSLPrice + : usedPrice >= appliedSLPrice; + + // + bool isTPTouched = + isLong + ? usedPrice >= appliedTPPrice + : usedPrice <= appliedTPPrice; + + // + // Handle SL ... + if ( + // + iSignal.sl > 0 + // + && + // + isSLTouched + // + && + // + mUseVirtualTPSL) + { + // + string comment = GenerateSignalSLComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + AddItemToBuffer( + iSignal, + handlerResult.sl); + } + } + + // + // Handle TP ... + if ( + // + iSignal.tp > 0 + // + && + // + isTPTouched + // + && + // + mUseVirtualTPSL) + { + // + string comment = GenerateSignalTPComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + AddItemToBuffer( + iSignal, + handlerResult.tp); + } + } + + // + // Handle Risk Free ... + if ( + // + !ignoreRiskFree + // + && + // + iSignal.riskFreeStep > 0 + // + && + // + iSignal.riskFreeRate > 0 + // + ) + { + // + // Make Signals Risk Free Only if Signal In Profit ... + if (iSignal.profit <= 0) + { + continue; + } + + // + // Base Price is ENTRY, then Last Level, in each level SL is Last Level ... + // + // Calculate Risk Free Level/Multiplier ... + double level = 0; + double roundedLevel = 0; + double rStepPrice = PipsToPrice(iSignal.riskFreeStep); + double rBasePrice = + iSignal.sl > 0 && + iSignal.sl > iSignal.entry + ? iSignal.sl + : iSignal.entry; + + // + double exit = GetExit(iSignal.type); + + // + // Check Base Price for Signal reached with Exit Price ... + bool isExitPriceReachedBasePrice = + isLong + ? exit > rBasePrice + : exit < rBasePrice; + if (!isExitPriceReachedBasePrice) + { + continue; + } + + // + // Calculate Risk Free Step Multiplier ... + level = MathAbs(exit - rBasePrice) / rStepPrice; + + // + // Check Level Must Bigger than 1 ... + if (level < 1) + { + continue; + } + + // + // Normalize Level ... + roundedLevel = MathRound(level); + if (level < roundedLevel) + { + level -= (1 - (roundedLevel - level)); + } + else if (level > roundedLevel) + { + level -= (level - roundedLevel); + } + + // + // Generate Comment ... + string comment = GenerateSignalRFComment(iSignal, (int)level); + + // + // Calculate SL ... + double slDistance = spread; + double sl = + isLong + ? exit - slDistance + : exit + slDistance; + + // + // Increase TP One Level if Exists ... + double tp = iSignal.tp; + if (iSignal.tp > 0 && (isLong + ? iSignal.tp < rBasePrice + rStepPrice + : iSignal.tp > rBasePrice - rStepPrice)) + { + // + tp = + isLong + ? iSignal.tp + rStepPrice + : iSignal.tp - rStepPrice; + } + + // + double rVolume = NormalizeVolume((iSignal.volume * iSignal.riskFreeRate), iSignal.symbol); + + // + // Update Signal Volume ... + double volume = iSignal.volume - rVolume; + + // + bool isClosedPartial = + ClosePartial( + iSignal.ticket, + rVolume, + comment); + if (isClosedPartial) + { + // + bool isModified = true; + if (!mUseVirtualTPSL) + { + // + isModified = Modify( + iSignal.ticket, + sl, + tp, + comment); + } + + // + if (isModified) + { + // + // Try to Update Signal ... + XSignal s = mSignalManager.Get(iSignal.ticket); + + // + // Apply Changes on Signal ... + s.sl = sl; + s.tp = tp; + s.volume = volume; + + // + // Update Signal ... + bool isUpdated = false; + bool isRemoved = false; + if (volume == 0) + { + isRemoved = mSignalManager.Remove(s); + } + else if (volume > 0) + { + isUpdated = mSignalManager.AddOrUpdate(s); + } + if ( + isUpdated || + isRemoved) + { + // + AddItemToBuffer( + s, + handlerResult.rf); + } + } + } + else + { + mSignalManager.Remove(iSignal.ticket); + } + } + } + + // + result = + ArraySize(handlerResult.tp) > 0 || + ArraySize(handlerResult.sl) > 0 || + ArraySize(handlerResult.rf) > 0; + + // + return result; + } + + // + // Close All Trades ... + void CloseSignals( + XSignal &result[], // Holds Result + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + string comment = GenerateSignalForceCloseComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + Add( + iSignal, + result); + } + } + } + + // + // Close Pyramid Signals ... + void CloseInPyramidSignals( + XSignal &result[], // Holds Result + double pyramid = 0, // Close Pyramid Profit + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetSignals( + signals, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + double profit = 0; + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + profit += iSignal.profit; + } + + // + // Normalize Pyramid ... + if (pyramid < 0) + { + pyramid = 0; + } + + // + if (profit > pyramid) + { + CloseSignals(result); + } + } + + // + // Close All Trades Which Candle Passed after Open ... + void CloseOldSignals( + XSignal &result[], // Holds Result + int life, // Max Candle Passed after Trades Open + ENUM_TIMEFRAMES period = NULL, // Calculate Candles based on time frame + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetOldSignals( + signals, + life, + period, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + string comment = GenerateSignalAgeComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + Add( + iSignal, + result); + } + } + } + + // + // Close In Profit Signals ... + void CloseInProfitSignals( + XSignal &result[], // Holds Result + double minProfit = 0, // Minimum Profit To Close Trades + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetInProfitSignals( + signals, + minProfit, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + string comment = GenerateSignalProfitComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + Add( + iSignal, + result); + } + } + } + + // + // Close In Drawdown Signals ... + void CloseInDrawdownSignals( + XSignal &result[], // Holds Result + double maxDrawDown = 0, // Minimum Profit To Close Trades + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Specify Type of Positions + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + GetInDrawdownSignals( + signals, + maxDrawDown, + type); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + string comment = GenerateSignalProfitComment(iSignal); + + // + bool isClosed = Close( + iSignal.ticket, + comment); + if (isClosed) + { + Add( + iSignal, + result); + } + } + } + + // + // END Signal Execution Actions ... + // + + // + // START Actions ... + // + + // + // Force Open a Buy/Long Position ... + bool Buy( + double volume, // position volume + double price, // execution price + double sl = 0, // stop loss price + double tp = 0, // take profit price + const string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.Buy( + volume, + mSymbol, + price, + sl, + tp, + comment); + + // + return result; + } + + // + // Send BUY LIMIT order ... + bool BuyLimit( + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.BuyLimit( + volume, + price, + mSymbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // Send BUY STOP order ... + bool BuyStop( + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.BuyStop( + volume, + price, + mSymbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // Force Open a Sell/Short Position ... + bool Sell( + double volume, // position volume + double price, // execution price + double sl = 0, // stop loss price + double tp = 0, // take profit price + const string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.Sell( + volume, + mSymbol, + price, + sl, + tp, + comment); + + // + return result; + } + + // + // Send SELL LIMIT order ... + bool SellLimit( + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.SellLimit( + volume, + price, + mSymbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // Send SELL STOP order ... + bool SellStop( + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = "" // comment + ) + { + // + bool result = false; + + // + result = mTrader.SellStop( + volume, + price, + mSymbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // Modify Position ... + bool Modify( + const ulong ticket, // position ticket + double sl = 0, // stop loss price + double tp = 0, // take profit + const string comment = "" // comment + ) + { + // + bool result = false; + + // + // Validate Args ... + if (tp <= 0 && sl <= 0) + { + result = false; + return result; + } + + // + result = mTrader.PositionModify( + ticket, + sl, + tp, + comment); + if (result) + { + // + if (mSignalManager.IsExists(ticket)) + { + // + XSignal signal = GetSignal(ticket); + + // + mSignalManager.Update(signal); + } + } + + // + return result; + } + + // + // Close Position By Ticket ... + bool Close( + ulong ticket, // Position Ticket + string comment = "" // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + // Try to Select Position ... + if (!mPositionInfo.SelectByTicket(ticket)) + { + return result; + } + + // + // Close Position By Specific Comment ... + result = mTrader.PositionClose( + ticket, + mSlippage, + comment); + if (result) + { + // + if (mSignalManager.IsExists(ticket)) + { + mSignalManager.Remove(ticket); + } + } + + // + return result; + } + + // + // Close Partial By Ticket ... + bool ClosePartial( + ulong ticket, // Position Ticket + double volume, // Volume Size for Partial Closing + string comment = "" // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + if (!mPositionInfo.SelectByTicket(ticket)) + { + return result; + } + + // + result = mTrader.PositionClosePartial( + ticket, + volume, + mSlippage, + comment); + if (result) + { + // + if (mSignalManager.IsExists(ticket)) + { + // + XSignal signal = GetSignal(ticket); + + // + mSignalManager.Update(signal); + } + } + + // + return result; + } + + // + // END Actions ... + // + + // + // START Account Related ... + // + + // + // Retrieve Minimum Balance For Open Trades ... + double GetMinBalanceForOpenTrades() + { + // + double result = mMinBallanceForOpenTrades; + + // + double balance = mAccountInfo.GetBalance(); + double deposit = mAccountInfo.GetInitialBalance(); + if (balance > deposit) + { + // + double rate = mMinBallanceForOpenTrades / deposit; + + // + double ratedBalance = balance * rate; + + // + result = MathMax(mMinBallanceForOpenTrades, ratedBalance); + } + + // + return result; + } + + // + // Check Account Has Minimum Balance For Trade ... + bool IsBalanceReadyForTrade() + { + // + bool result = false; + + // + double minBalance = GetMinBalanceForOpenTrades(); + result = mAccountInfo.GetBalance() >= minBalance; + + // + return result; + } + + // + // Check Free Margin Has Enough For Trade ... + bool IsFreeMarginReadyForTrade() + { + // + bool result = false; + + // + double freeMargin = mAccountInfo.GetFreeMargin(); + + // + result = freeMargin >= mMinAllowedFreeMarginForOpenTrades; + + // + return result; + } + + // + // Check Equity Has Enough For Trade ... + bool IsEquityReadyForTrade() + { + // + bool result = false; + + // + double equity = mAccountInfo.GetEquity(); + + // + result = equity >= mMinAllowedFreeMarginForOpenTrades; + + // + return result; + } + + // + // END Account Related ... + // + + // + // START Signal Related ... + // + + // + // Validate Signal ... + bool IsValidSignal( + XSignal &signal // Specified Signal for Execution + ) + { + // + bool result = false; + + // + // Validate Signal Type ... + result = signal.type != X_SIGNAL_UNKNOWN; + if (!result) + { + return result; + } + + // + // Check Symbol ... + result = StringLen(signal.symbol) == 0 ? true : signal.symbol == mSymbol; + if (!result) + { + return result; + } + + // + // Check magic number ... + result = signal.magicNumber <= 0 ? true : signal.magicNumber == mMagicNumber; + if (!result) + { + return result; + } + + // + // Check Entry ... + result = signal.entry > 0; + if (!result) + { + return result; + } + + // // + // // Check SL ... + // // For Fix RiskFree Issues Ignore this ... + // result = signal.sl == 0 ? true : signal.type == X_SIGNAL_LONG ? signal.sl < signal.entry + // : signal.sl > signal.entry; + // if (!result) + // { + // return result; + // } + + // + // Check TP ... + result = signal.tp == 0 ? true : signal.type == X_SIGNAL_LONG ? signal.tp > signal.entry + : signal.tp < signal.entry; + if (!result) + { + return result; + } + + // + // Check Volume ... + result = signal.volume > 0; + if (!result) + { + return result; + } + + // + // Check Time ... + result = signal.time > 0; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Get Signal InDirection (Reversal) Type ... + ENUM_X_SIGNAL_TYPE GetSignalIndirectionType( + XSignal &signal // Specified Signal + ) + { + // + ENUM_X_SIGNAL_TYPE result = X_SIGNAL_UNKNOWN; + + // + switch (signal.type) + { + // + case X_SIGNAL_LONG: + result = X_SIGNAL_SHORT; + break; + + // + case X_SIGNAL_SHORT: + result = X_SIGNAL_LONG; + break; + } + + // + return result; + } + + // + // Get Signal InDirection (Reversal) Type ... + ENUM_X_SIGNAL_TYPE GetIndirectionSignalType( + ENUM_X_SIGNAL_TYPE type // Specified Type + ) + { + // + ENUM_X_SIGNAL_TYPE result = X_SIGNAL_UNKNOWN; + + // + switch (type) + { + // + case X_SIGNAL_LONG: + result = X_SIGNAL_SHORT; + break; + + // + case X_SIGNAL_SHORT: + result = X_SIGNAL_LONG; + break; + } + + // + return result; + } + + // + // Calculate SignalAge ... + int GetSignalAge( + datetime time // Signal Execution Time + ) + { + // + int result = 0; + + // + // Validate Arg ... + if (time <= 0) + { + return result; + } + + // + int sIndex = iBarShift( + mSymbol, + _Period, + time); + + // + datetime cTime = iTime( + mSymbol, + _Period, + 0); + int cIndex = iBarShift( + mSymbol, + _Period, + cTime); + + // + result = MathAbs(cIndex - sIndex); + + // + return result; + } + int GetSignalAge( + datetime time, // Signal Execution Time + ENUM_TIMEFRAMES period // Specify Time Frame + ) + { + // + int result = 0; + + // + // Validate Arg ... + if (time <= 0) + { + return result; + } + + // + int sIndex = iBarShift( + mSymbol, + period, + time); + + // + datetime cTime = iTime( + mSymbol, + period, + 0); + int cIndex = iBarShift( + mSymbol, + _Period, + cTime); + + // + result = MathAbs(cIndex - sIndex); + + // + return result; + } + int GetSignalAge( + XSignal &signal // Specified Signal + ) + { + // + int result = 0; + + // + // Validate Arg ... + if ( + signal.time <= 0 || + !IsValid(signal, mMagicNumber)) + { + return result; + } + + // + result = GetSignalAge(signal.time); + + // + return result; + } + int GetSignalAge( + XSignal &signal, // Specify Signal + ENUM_TIMEFRAMES period // Specify Time Frame + ) + { + // + int result = 0; + + // + // Validate Arg ... + if ( + signal.time <= 0 || + !IsValid(signal, mMagicNumber)) + { + return result; + } + + // + result = GetSignalAge( + signal.time, + period); + + // + return result; + } + + // + // Prepare a Signall ... + XSignal GenerateSignal( + ENUM_X_SIGNAL_TYPE type, // Signal Type + double tp = 0, // Take Profit + double sl = 0, // Stop Loss + double volume = 0, // Volume + double riskFreeStep = 0, // Risk Free Step Price + double riskFreeRate = 0 // Risk Free Rate + ) + { + // + XSignal result = {}; + + // + // Validate Arg ... + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + // Check Signal Type ... + bool isLong = type == X_SIGNAL_LONG; + + // + // Retrieve entry Price ... + double entry = GetEntry(mSymbol, type); + double spread = GetSpread(mSymbol); + + // + result.tp = tp; + result.sl = sl; + result.type = type; + result.entry = entry; + result.symbol = mSymbol; + result.magicNumber = mMagicNumber; + result.riskFreeStep = riskFreeStep; + result.riskFreeRate = riskFreeRate; + result.time = iTime(mSymbol, _Period, 0); + result.volume = NormalizeVolume(volume, mSymbol); + + // + // Since we Use signal instance to Generate Comment, this must be at the end ... + result.comment = GenerateSignalComment(result); + + // + return result; + } + + // + // Convert a Signal to String Representation ... + string ToString( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + if (!IsValid(signal, mMagicNumber) || signal.ticket <= 0) + { + return result; + } + + // + // TICKET ... + // it is very importants since they hold position info ... + result += X_SIGNAL_TICKET + "(" + (string)signal.ticket + ")"; + + // + // TYPE ... + string typeStr = GetSignalType(signal.type); + result += "_" + X_SIGNAL_TYPE + "(" + typeStr + ")"; + + // + // TP ... + result += "_" + X_SIGNAL_TP + "(" + (string)signal.tp + ")"; + + // + // SL ... + result += "_" + X_SIGNAL_SL + "(" + (string)signal.sl + ")"; + + // + // RFS ... + result += "_" + X_SIGNAL_RISKFREE_STEP + "(" + (string)signal.riskFreeStep + ")"; + + // + // RFR ... + result += "_" + X_SIGNAL_RISKFREE_RATE + "(" + (string)signal.riskFreeRate + ")"; + + // + return result; + } + + // + // Generate Comments for Specific Signal ... + string GenerateSignalComment( + ENUM_X_SIGNAL_TYPE type, // Specify Kind Signal Type + double volume, // Signal Volume + bool isCrossSignal = false // Specify Signal Cross + ) + { + // + string result = ""; + + // + string typeStr = GetSignalType(type); + if ( + volume <= 0 || + StringLen(typeStr) == 0) + { + return result; + } + + // + volume = NormalizeVolume(volume, mSymbol); + + // + result = mTag + (!isCrossSignal ? "" : "_Cross_") + "_" + typeStr; + + // + return result; + } + string GenerateSignalComment( + XSignal &signal, // Specified Signal + bool isCrossSignal = false // Specify Signal Cross + ) + { + // + string result = GenerateSignalComment( + signal.type, + signal.volume, + isCrossSignal + // + ); + + // + return result; + } + + // + // Generate Signal RF TP Comment ... + string GenerateSignalRFComment( + XSignal &signal, // Specified Signal + int level // Which Step of RFS + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + double exit = NormalizePrice(GetExit(signal.symbol, signal.type), signal.symbol); + + // + string prefix = X_SIGNAL_RISKFREE_STEP + "(" + (string)signal.ticket + ")"; + // + result = + // + level > 0 + ? prefix + "_" + (string)level + ": " + (string)exit + : prefix + ": " + (string)exit; + // + ; + + // + return result; + } + + // + // Generate Signal TP Comment ... + string GenerateSignalTPComment( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + double exit = NormalizePrice(GetExit(signal.symbol, signal.type), signal.symbol); + + // + result = + // + X_SIGNAL_TP + "(" + (string)signal.ticket + "): " + (string)exit; + // + ; + + // + return result; + } + + // + // Generate Signal SL Comment ... + string GenerateSignalSLComment( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + double exit = NormalizePrice(GetExit(signal.symbol, signal.type), signal.symbol); + + // + result = + // + X_SIGNAL_SL + "(" + (string)signal.ticket + "): " + (string)exit; + // + ; + + // + return result; + } + + // + // Generate Signal Profit Comment ... + string GenerateSignalProfitComment( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + result = + // + "Profit(" + (string)signal.ticket + "): " + (string)signal.profit; + // + ; + + // + return result; + } + + // + // Generate Signal Force Close Comment ... + string GenerateSignalForceCloseComment( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + result = + // + "FC(" + (string)signal.ticket + "): " + (string)signal.profit; + // + ; + + // + return result; + } + + // + // Generate Signal Age Comment ... + string GenerateSignalAgeComment( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Signal and it's Ticket ... + if (!IsValidSignal(signal) || signal.ticket <= 0) + { + return result; + } + + // + int age = GetSignalAge(signal); + + // + result = + // + "(" + (string)signal.ticket + ") A: " + (string)age + ", P:" + (string)signal.profit; + // + ; + + // + return result; + } + + // + // Generate a Signal Object name for Draw Events On Chart ... + string GenerateSignalObjectName( + ulong ticket // Specify Ticket + ) + { + // + string result = ""; + + // + // Validate Arg ... + if (ticket <= 0) + { + return result; + } + + // + // TICKET ... + // it is very importants since they hold position info ... + result += "T(" + (string)ticket + ")"; + + // + return result; + } + string GenerateSignalObjectName( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + // Validate Arg ... + if (!IsValid(signal, mMagicNumber)) + { + return result; + } + + // + result = GenerateSignalObjectName(signal.ticket); + + // + return result; + } + + // + // Genrate a Signal Event Object Name ... + string GenerateSignalEventObjectName( + ulong ticket // Specify Ticket + ) + { + // + string result = ""; + + // + result = GenerateSignalObjectName(ticket) + "_Event"; + + // + return result; + } + string GenerateSignalEventObjectName( + XSignal &signal // Specified Signal + ) + { + // + string result = ""; + + // + result = GenerateSignalEventObjectName(signal.ticket); + + // + return result; + } + + // + // END Signal Related ... + // + + // + // START Deals ... + // + + // + // Count Deals ... + int DealsCount( + datetime start = -1, // Start Date + datetime end = -1 // End Date + ) + { + // + int result = 0; + + // + XDeal deals[]; + GetDeals( + deals, + start, + end); + result = ArraySize(deals); + + // + return result; + } + + // + // Retrieve All Deals ... + void GetDeals( + XDeal &result[], // Hold's Result + datetime start = -1, // Start Date + datetime end = -1 // End Date + ) + { + // + CleanBuffer(result); + + // + // Select History if Start and End date provided ... + if (start > -1) + { + // + // Normalize End date ... + if (end == -1) + { + end = TimeCurrent(); + } + + // + bool isSelect = HistorySelect(start, end); + if (!isSelect) + { + return; + } + } + + // + int total = HistoryDealsTotal(); + if (total <= 0) + { + return; + } + + // + // Loop ... + for (int i = total - 1; i >= 0; i--) + { + // + // Select by Index ... + bool isSelect = mDealInfo.SelectByIndex(i); + if (!isSelect) + { + continue; + } + + // + // Check Magic ... + ulong magic = mDealInfo.Magic(); + bool isMagicSame = magic == mMagicNumber; + if (!isMagicSame) + { + continue; + } + + // + // Check Symbol ... + string symbol = mDealInfo.Symbol(); + bool isSymbolSame = symbol == mSymbol; + if (!isSymbolSame) + { + continue; + } + + // + XDeal deal = ToXDealByIndex(i); + + // + Add( + deal, + result); + } + } + + // + // Retrieve Last Deal ... + XDeal GetLastDeal() + { + // + XDeal result = {}; + + // + XDeal deals[]; + GetDeals(deals); + int dealsCount = ArraySize(deals); + if (dealsCount <= 0) + { + return result; + } + + // + result = deals[0]; + + // + return result; + } + + // + // END Deals ... + // + + // + // START Orders ... + // + + // + // Count Orders ... + int OrdersCount( + datetime start = -1, // Start Date + datetime end = -1 // End Date + ) + { + // + int result = 0; + + // + XOrder orders[]; + GetOrders( + orders, + start, + end); + result = ArraySize(orders); + + // + return result; + } + + // + // Retrieve Orders ... + void GetOrders( + XOrder &result[], // Hold's Result + datetime start = -1, // Start Date + datetime end = -1 // End Date + ) + { + // + CleanBuffer(result); + + // + // Select History if Start and End date provided ... + if (start > -1) + { + // + // Normalize End date ... + if (end == -1) + { + end = TimeCurrent(); + } + + // + bool isSelect = HistorySelect(start, end); + if (!isSelect) + { + return; + } + } + + // + int total = HistoryOrdersTotal(); + if (total <= 0) + { + return; + } + + // + // Loop ... + for (int i = total - 1; i >= 0; i--) + { + // + // Select by Index ... + bool isSelect = mOrderInfo.SelectByIndex(i); + if (!isSelect) + { + continue; + } + + // + // Check Magic ... + ulong magic = mOrderInfo.Magic(); + bool isMagicSame = magic == mMagicNumber; + if (!isMagicSame) + { + continue; + } + + // + // Check Symbol ... + string symbol = mOrderInfo.Symbol(); + bool isSymbolSame = symbol == mSymbol; + if (!isSymbolSame) + { + continue; + } + + // + XOrder order = ToXOrderByIndex(i); + + // + Add( + order, + result); + } + } + + // + // Retrieve Last Order ... + XOrder GetLastOrder() + { + // + XOrder result = {}; + + // + XOrder orders[]; + GetOrders(orders); + int ordersCount = ArraySize(orders); + if (ordersCount <= 0) + { + return result; + } + + // + result = orders[0]; + + // + return result; + } + + // + // END Orders ... + // + + // + // START OnTrade Handlers ... + // + + // + // Handle OnTrade Event ... + void HandleOnTradeEvent( + XOnTradeHandlerResult &result // Hold's Result + ) + { + // + if (mScanStarted) + { + ProcessOnTradeContext(result); + } + else + { + InitOnTradeContext(); + } + } + + // + // END OnTrade Handlers ... + // + + // + // Retrieve Magic Number ... + ulong GetMagicNumber() + { + return mMagicNumber; + } + + // + // all protected features ... +protected: + // + // all private features ... +private: + // + // Specified Unique Tag ... + string mTag; + + // + // which Symbol ... + string mSymbol; + + // + // using deviation, it must be in Point ... + int mSlippage; + + // + // using magic number ... + ulong mMagicNumber; + + // + // Detect Using Virtual TP or SL ... + bool mUseVirtualTPSL; + + // + // Specify Max Allowed Trades + int mMaxAllowedTrades; + + // + // Minimum Free Marging for Open Trades + double mMinAllowedFreeMarginForOpenTrades; + + // + // Minimum Balance for Open Trades + double mMinBallanceForOpenTrades; + + // + // using CTrade instance ... + XSCTrade mTrader; + + // + // Deals Info ... + CDealInfo mDealInfo; + + // + // Order Info ... + COrderInfo mOrderInfo; + + // + // An Instance Of XCAccount Info for Handling Account Related Actions ... + XCAccountInfo mAccountInfo; + + // + // using PositionInfo instance ... + CPositionInfo mPositionInfo; + + // + // Signal Manager ... + XCSignalManager mSignalManager; + + // + // START OnTrade Handlers ... + // + + // + int mDaysForRead; + + // + // set the limits of the trade history on the global scope ... + + // + // // start date for trade history in cache ... + datetime mStartDate; + + // + // end date for trade history in cache ... + datetime mEndDate; + + // + // global OnTrade counters ... + + // + // number of active orders ... + int mOrdersCount; + + // + // number of open positions ... + int mPositionsCount; + + // + // number of deals in the trade history cache ... + int mDealsCount; + + // + // number of orders in the trade history cache ... + int mHistoryOrdersCount; + + // + // flag of counter relevance ... + bool mScanStarted; + + // + // Check Statrt Date In Trade History ... + void CheckStartDateInTradeHistory() + { + // + // initial interval, if we were to start working right now .. + datetime currStart = TimeCurrent() - (mDaysForRead * PeriodSeconds(PERIOD_D1)); + + // + // make sure that the start limit of the trade history has not gone + // more than 1 day over the intended date ... + if (currStart - mStartDate > PeriodSeconds(PERIOD_D1)) + { + // + // correct the start date of history to be loaded in the cache ... + mStartDate = currStart; + + // + // now reload the trade history for the updated interval ... + HistorySelect(mStartDate, mEndDate); + + // + // correct the deal and order counters in history for further comparison + mHistoryOrdersCount = HistoryOrdersTotal(); + mDealsCount = HistoryDealsTotal(); + } + } + + // + // Process On Trade Context ... + void ProcessOnTradeContext( + XOnTradeHandlerResult &result // Hold's Result + ) + { + // + mEndDate = TimeCurrent(); + + // + ResetLastError(); + + // + // download trading history from the specified interval to the program cache ... + bool selected = HistorySelect(mStartDate, mEndDate); + if (!selected) + { + // + LogMessage("Failed to Load OnTrade Context History ..."); + + // + return; + } + + // + // get the current values ... + int currOrders = OrdersTotal(); + int currPositions = PositionsTotal(); + int currDeals = HistoryDealsTotal(); + int currHistoryOrders = HistoryOrdersTotal(); + + // + // Orders ... + // check if the number of active orders has been changed ... + if (currOrders != mOrdersCount) + { + // + // number of active orders has been changed ... + result.hasNewOrder = true; + result.newOrders = currOrders - mOrdersCount; + + // + // update the value ... + mOrdersCount = currOrders; + } + + // + // Positions ... + // changes in the number of open positions ... + if (currPositions != mPositionsCount) + { + // + // number of open positions has been changed ... + result.hasNewPosition = true; + result.newPositions = currPositions - mPositionsCount; + + // + // update the value ... + mPositionsCount = currPositions; + } + + // + // Deals ... + // changes in the number of deals in the trade history cache ... + if (currDeals != mDealsCount) + { + // + // number of deals in the trade history cache has been changed ... + result.hasNewDeal = true; + result.newDeals = currDeals - mDealsCount; + + // + // update the value ... + mDealsCount = currDeals; + } + + // + // History Orders ... + // changes in the number of history orders in the trade history cache ... + if (currHistoryOrders != mHistoryOrdersCount) + { + // + // number of history orders in the trade history cache has been changed ... + result.hasNewHistoryOrder = true; + result.newHistoryOrders = currHistoryOrders - mHistoryOrdersCount; + + // + // update the value ... + mHistoryOrdersCount = currHistoryOrders; + } + + // + // checking if it is necessary to change the limits of the trade history to be requested in cache ... + CheckStartDateInTradeHistory(); + } + + // + // Reset On Trade Scanner Context ... + void ResetOnTradeContext() + { + // + mEndDate = TimeCurrent(); + mStartDate = mEndDate - (mDaysForRead * PeriodSeconds(PERIOD_D1)); + } + + // + // Initial Context Of Trade Scanner ... + void InitOnTradeContext() + { + // + ResetLastError(); + + // + // load history ... + bool selected = HistorySelect(mStartDate, mEndDate); + if (!selected) + { + // + LogMessage("Failed to Load OnTrade Context History ..."); + + // + return; + } + + // + // get the current value ... + mOrdersCount = OrdersTotal(); + mPositionsCount = PositionsTotal(); + mDealsCount = HistoryDealsTotal(); + mHistoryOrdersCount = HistoryOrdersTotal(); + + // + mScanStarted = true; + } + + // + // END OnTrade Handlers ... + // + + // + // START Signal Private ... + // + + // + // Add Or Update Signal ... + void AddOrUpdateSignalInfo( + XSignal &signal // Specified Signal + ) + { + // + bool isExists = mSignalManager.IsExists(signal); + if (isExists) + { + mSignalManager.Remove(signal.ticket); + } + + // + bool isAddOrUpdated = mSignalManager.AddOrUpdate(signal); + if (isAddOrUpdated) + { + // + color longColor = clrAqua; + color shortColor = clrFuchsia; + + // + DrawSignalShape( + signal, + longColor, + shortColor); + } + } + + // + // Retrieve Signal String From Chart Event ... + XSignal RetrieveSignal( + ulong ticket // Specify Position Ticket + ) + { + // + XSignal result = {}; + + // + if (ticket <= 0) + { + return result; + } + + // + result = mSignalManager.Get(ticket); + + // + return result; + } + void RetrieveSignal( + XSignal &signal // Specified Signal + ) + { + + // + XSignal tSignal = mSignalManager.Get(signal.ticket); + + // + // Fill signal by tSignal Data ... + // since tese properties may change in signal manipulation times ... + signal.tp = tSignal.tp; + signal.sl = tSignal.sl; + signal.riskFreeStep = tSignal.riskFreeStep; + signal.riskFreeRate = tSignal.riskFreeRate; + } + + // + // Convert Position to Signal by Index ... + XSignal PositionToSignal(int index) + { + // + XSignal result = {}; + + // + if (!mPositionInfo.SelectByIndex(index)) + { + return result; + } + + // + ulong ticket = mPositionInfo.Ticket(); + result = PositionToSignal(ticket); + + // + return result; + } + + // + // Position To Signal by Ticket ... + XSignal PositionToSignal(ulong ticket) + { + // + XSignal result = {}; + + // + if (!mPositionInfo.SelectByTicket(ticket)) + { + return result; + } + + // + bool isExists = mSignalManager.IsExists(ticket); + if (isExists) + { + result = RetrieveSignal(ticket); + } + + // + // Ticket ... + result.ticket = mPositionInfo.Ticket(); + + // + // ID ... + result.id = mPositionInfo.Identifier(); + + // + // Symbol ... + result.symbol = mPositionInfo.Symbol(); + + // + // Type ... + ENUM_POSITION_TYPE pType = (ENUM_POSITION_TYPE)mPositionInfo.PositionType(); + ENUM_X_SIGNAL_TYPE type = pType == POSITION_TYPE_BUY ? X_SIGNAL_LONG : X_SIGNAL_SHORT; + result.type = type; + + // + // MagicNumber ... + result.magicNumber = mPositionInfo.Magic(); + + // + // Entry/Open Price ... + result.entry = mPositionInfo.PriceOpen(); + + // + // Take Profit ... + result.tp = result.tp <= 0 && mPositionInfo.TakeProfit() > 0 + ? mPositionInfo.TakeProfit() + : result.tp; + + // + // Stop Loss ... + result.sl = result.sl <= 0 && mPositionInfo.StopLoss() > 0 + ? mPositionInfo.StopLoss() + : result.sl; + + // + // Profit ... + result.profit = mPositionInfo.Profit(); + + // + // Time ... + result.time = mPositionInfo.Time(); + + // + // Volume ... + result.volume = mPositionInfo.Volume(); + + // + // Comment ... + result.comment = mPositionInfo.Comment(); + + // + return result; + } + + // + // Converts a Deal to XDeal by Index ... + XDeal ToXDealByIndex(int index) + { + // + XDeal result = {}; + + // + bool isSelect = mDealInfo.SelectByIndex(index); + if (!isSelect) + { + return result; + } + + // + // Read Deal Ticket ... + ulong ticket = mDealInfo.Ticket(); + result = ToXDealByTicket(ticket); + + // + return result; + } + + // + // Converts a Deal to XDeal by Ticket ... + XDeal ToXDealByTicket(ulong ticket) + { + // + XDeal result = {}; + + // + mDealInfo.Ticket(ticket); + + // + result.time = mDealInfo.Time(); + result.swap = mDealInfo.Swap(); + result.magic = mDealInfo.Magic(); + result.order = mDealInfo.Order(); + result.entry = mDealInfo.Entry(); + result.price = mDealInfo.Price(); + result.ticket = mDealInfo.Ticket(); + result.symbol = mDealInfo.Symbol(); + result.type = mDealInfo.DealType(); + result.profit = mDealInfo.Profit(); + result.volume = mDealInfo.Volume(); + result.comment = mDealInfo.Comment(); + result.positionId = mDealInfo.PositionId(); + result.commission = mDealInfo.Commission(); + result.reason = (ENUM_DEAL_REASON)HistoryDealGetInteger( + ticket, + DEAL_REASON); + + // + return result; + } + + // + // Convert an Order to XOrder by Index ... + XOrder ToXOrderByIndex(int index) + { + // + XOrder result = {}; + + // + bool isSelect = mOrderInfo.SelectByIndex(index); + if (!isSelect) + { + return result; + } + + // + ulong ticket = mOrderInfo.Ticket(); + result = ToXOrderByTicket(ticket); + + // + return result; + } + + // + // Convert an Order to XOrder by Ticket ... + XOrder ToXOrderByTicket(ulong ticket) + { + // + XOrder result = {}; + + // + bool isSelect = mOrderInfo.Select(ticket); + if (!isSelect) + { + return result; + } + + // + result.state = mOrderInfo.State(); + result.magic = mOrderInfo.Magic(); + result.ticket = mOrderInfo.Ticket(); + result.symbol = mOrderInfo.Symbol(); + result.type = mOrderInfo.OrderType(); + result.comment = mOrderInfo.Comment(); + result.stopLoss = mOrderInfo.StopLoss(); + result.typeTime = mOrderInfo.TypeTime(); + result.timeDone = mOrderInfo.TimeDone(); + result.timeSetup = mOrderInfo.TimeSetup(); + result.positionId = mOrderInfo.PositionId(); + result.priceOpen = mOrderInfo.PriceOpen(); + result.takeProfit = mOrderInfo.TakeProfit(); + result.typeFilling = mOrderInfo.TypeFilling(); + result.priceCurrent = mOrderInfo.PriceCurrent(); + result.volumeInitial = mOrderInfo.VolumeInitial(); + result.volumeCurrent = mOrderInfo.VolumeCurrent(); + result.timeExpiration = mOrderInfo.TimeExpiration(); + result.priceStopLimit = mOrderInfo.PriceStopLimit(); + result.reason = (ENUM_ORDER_REASON)HistoryOrderGetInteger( + ticket, + ORDER_REASON); + + // + return result; + } + // + // END Signal Private ... + // +}; + +// +// a Class For Guard Account ... +class XCGuard : public XCBase +{ + // + // Public ... +public: + // + // Constructor ... + XCGuard( + int oldAge, // Age for Old Trades + ENUM_X_GUARD_ACTIONS oldGuardAction, // Guard Action for Too Old State + double criticalFactor, // Critical DrawDown Factor based On Balance + ENUM_X_GUARD_ACTIONS criticalAction, // Guard Action for Critical State + double maxFactor, // Max DrawDown Factor based on Balance + ENUM_X_GUARD_ACTIONS maxAction, // Guard Action for Max State + int GuardStopoutFiredAfterTouches, // Guard Stopout if Max State touched + ENUM_X_GUARD_SUPPORT_METHODS supportMethod // How to Support Signals + ) + { + // + mSupportPrefix = "SPT"; + mDirectional = "SPD"; + mInDirectional = "SPIND"; + + // + mOldAge = oldAge; + mOldGuardAction = oldGuardAction; + + // + mMaxFactor = maxFactor; + mMaxAction = maxAction; + mCriticalFactor = criticalFactor; + mCriticalAction = criticalAction; + mGuardStopoutFiredAfterTouches = GuardStopoutFiredAfterTouches; + + // + mSupportMethod = supportMethod; + + // + mAccountInfo = new XCAccountInfo(); + + // + double deposit = mAccountInfo.GetInitialBalance(); + + // + if ( + maxFactor > 0 && + maxFactor < 1) + { + mMaxValue = maxFactor * deposit; + } + + // + if ( + criticalFactor > 0 && + criticalFactor < 1) + { + mCriticalValue = criticalFactor * deposit; + } + + // + Reset(); + ResetMaxDrawDownTouches(); + } + + // + // Deconstructor ... + ~XCGuard() {} + + // + // Reset List ... + void Reset() + { + // + CleanBuffer(mGuardedSignals); + CleanBuffer(mSupportedSignals); + } + + // + // Reset Consecutive Max DrawDown Touches ... + void ResetMaxDrawDownTouches() + { + mOccuredconsecutiveMaxDraDownTouches = 0; + } + + // + // Calculate and Retrieve Critical DrawDown Value ... + double GetCriticalValue() + { + // + double result = mCriticalValue; + if (mCriticalFactor <= 0) + { + return result; + } + + // + double deposit = mAccountInfo.GetInitialBalance(); + double balance = mAccountInfo.GetBalance(); + + // + if (balance > deposit) + { + // + double balanceBasedCriticalDrawDown = mCriticalFactor * balance; + + // + result = MathMax( + mCriticalValue, + balanceBasedCriticalDrawDown); + } + + // + return result; + } + + // + // Calculate and Retrieve Max Allowed DrawDown Value ... + double GetMaxValue() + { + // + double result = mMaxValue; + if (mMaxValue <= 0) + { + return result; + } + + // + double deposit = mAccountInfo.GetInitialBalance(); + double balance = mAccountInfo.GetBalance(); + + // + if (balance > deposit) + { + // + double balanceBasedMaxAllwedDrawDown = mMaxFactor * balance; + + // + result = MathMax( + mMaxValue, + balanceBasedMaxAllwedDrawDown); + } + + // + return result; + } + + // + // Guard Account Protection ... + bool Guard( + XGuardHandlerResult &guardResult, // Hold's Message + string &message, // Hold's Message + XCTrade &trader, // Specified Trader + ENUM_TIMEFRAMES period = NULL // Specified Time Frame for Detecting Signal Ages + ) + { + // + message = ""; + + // + // Clean Result of Guard ... + CleanBuffer(guardResult.olds); + CleanBuffer(guardResult.maxes); + CleanBuffer(guardResult.criticals); + + // + bool result = false; + + // + // So Important is to Guard DrawDowns ... + result = GuardDrawDown( + guardResult, + message, + trader); + if (result) + { + return result; + } + + // + // Then we have to Guard Old Trades ... + result = GuardOlds( + guardResult, + message, + trader); + + // + return result; + } + + // + // Handle Guard Old Trades ... + bool GuardOlds( + XGuardHandlerResult &guardResult, // Hold's Message + string &message, // Hold's Message + XCTrade &trader, // Specified Trader + ENUM_TIMEFRAMES period = NULL // Specified Time Frame for Detecting Signal Ages + ) + { + // + // Cleanup Message ... + message = ""; + + // + // Clean Result of Guard ... + CleanBuffer(guardResult.olds); + + // + bool result = false; + + // + // Validate Args ... + if ( + mOldAge <= 0 || + mOldGuardAction == X_GUARD_DO_NOTHING) + { + return result; + } + + // + // Normalize Args ... + if (period == NULL) + { + period = _Period; + } + + // + // Retrieve Old Trades ... + XSignal oldSignals[]; + trader.GetOldSignals( + oldSignals, + mOldAge, + period); + int oldSignalsCount = ArraySize(oldSignals); + if (oldSignalsCount <= 0) + { + return result; + } + + // + result = DoGuardAction( + guardResult, + message, + trader, + mOldGuardAction, + X_GUARDED_OLD, // Specify Guard Reason + period // Specified Running Time Frame for Signal Age Calculations + ); + + // + return result; + } + + // + // Hnadle Guard DrawDown ... + bool GuardDrawDown( + XGuardHandlerResult &guardResult, // Hold's Message + string &message, // Hold's Message + XCTrade &trader // Specified Trader + ) + { + // + message = ""; + + // + // Clean Result of Guard ... + CleanBuffer(guardResult.maxes); + CleanBuffer(guardResult.criticals); + + // + bool result = false; + + // + // Check State for Guard ... + bool isCriticalGuardEnabled = mCriticalFactor > 0; + bool isMaxGuardEnabled = mMaxFactor > 0; + bool isGuardEnabled = + isMaxGuardEnabled; + + // + if (!isGuardEnabled) + { + return result; + } + + // + double maxValue = GetMaxValue(); + double criticalValue = GetCriticalValue(); + + // + double profitSums = trader.GetSignalsProfit(); + + // + bool isMaxReached = + profitSums < 0 && + isMaxGuardEnabled && + MathAbs(profitSums) >= maxValue; + bool isCriticalReached = + profitSums < 0 && + isCriticalGuardEnabled && + MathAbs(profitSums) >= criticalValue; + + // + if (!isMaxReached && !isCriticalReached) + { + // + // Reset Consecutive Max DrawDown Touches ... + ResetMaxDrawDownTouches(); + + // + return result; + } + + // + // Check For Critical Guard ... + if (isCriticalReached && !isMaxReached) + { + // + result = DoGuardAction( + guardResult, + message, + trader, + mCriticalAction, + X_GUARDED_CRITICAL); + } + else if (isMaxReached) + { + // + result = DoGuardAction( + guardResult, + message, + trader, + mMaxAction, + X_GUARDED_MAX); + + // + // Handle Guard StopOut Action ... + mOccuredconsecutiveMaxDraDownTouches++; + if ( + mMaxAction != X_GUARD_DO_NOTHING && + mMaxAction != X_GUARD_CLOSE_ALL && + mGuardStopoutFiredAfterTouches > 0 && + mOccuredconsecutiveMaxDraDownTouches >= mGuardStopoutFiredAfterTouches) + { + // + XSignal closed[]; + trader.CloseSignals(closed); + int closedCount = ArraySize(closed); + if (closedCount > 0) + { + // + for (int i = 0; i < closedCount; i++) + { + // + XSignal iSignal = closed[i]; + + // + AddItemToBuffer( + iSignal, + guardResult.maxes); + } + + // + message = "Guard StopOut Action Closed (" + (string)closedCount + ") Signals and Release Account ..."; + + // + guardResult.isStopOut = true; + + // + result = true; + } + } + } + + // + return result; + } + + // + // Do Signal Protections and apply Support ... + bool ProtectSignals( + XSignal &mResult[], // Hold's Result + XCTrade &trader, // Specified Trader + int numberOfItemsCheck = 30 // Number of Items to check + ) + { + // + bool result = false; + + // + CleanBuffer(mResult); + + // + // Check Supports Enabled ... + result = IsSupportEnabled(); + if (!result) + { + return result; + } + + // + // Update Supports ... + XSignal signals[]; + trader.GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount > 0) + { + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + bool isExists = IsSupportExists(iSignal.ticket); + if (isExists) + { + UpdateSupport(iSignal); + } + } + } + + // + // Count Supporteds ... + XProtectedSignal supporteds[]; + GetAllSupports(supporteds); + int supportedCount = ArraySize(supporteds); + result = supportedCount > 0; + if (!result) + { + return result; + } + + // + // Loop through ... + for (int i = 0; i < supportedCount; i++) + { + // + XProtectedSignal iP = supporteds[i]; + + // + bool canDoDirectional = CanDoDirectionalSupport( + trader, + iP.ticket, + numberOfItemsCheck); + bool canDoInDirectional = CanDoInDirectionalSupport( + trader, + iP.ticket, + numberOfItemsCheck); + + // + if ( + !canDoDirectional && + !canDoInDirectional) + { + continue; + } + + // + // Do Directional ... + if (canDoDirectional) + { + // + // Generate Propper Signal ... + XSignal sdSignal = GenerateDirectionalSupportSignal( + iP.ticket, + trader); + + // + ENUM_EXECUTION_SIGNAL_RESULT executionResult = trader.ExecuteSignal( + sdSignal, + true, + false); + bool isExecuted = executionResult == X_TRADER_SUCCEED_EXECUTION; + if (isExecuted) + { + // + XSignal eSignal = trader.GetSignal(sdSignal.ticket); + + // + AddItemToBuffer( + eSignal, + mResult); + } + } + // + // Do Indirectional ... + else if (canDoInDirectional) + { + // + // Generate Propper Signal ... + XSignal sindSignal = GenerateDirectionalSupportSignal( + iP.ticket, + trader); + + // + ENUM_EXECUTION_SIGNAL_RESULT executionResult = trader.ExecuteSignal( + sindSignal, + true, + false); + bool isExecuted = executionResult == X_TRADER_SUCCEED_EXECUTION; + if (isExecuted) + { + // + XSignal eSignal = trader.GetSignal(sindSignal.ticket); + + // + AddItemToBuffer( + eSignal, + mResult); + } + } + } + + // + result = ArraySize(mResult) > 0; + + // + return result; + } + + // + // Validate State ... + bool Validate() + { + // + bool result = false; + + // + result = + mMaxFactor > 0 && + (mCriticalFactor > 0 + ? mCriticalFactor < mMaxFactor + : true); + + // + return result; + } + + // + // START Guarded Signals Functions ... + // + + // + // Add new Protecte Signal ... + bool Add( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + bool isExists = IsExists(signal.ticket); + if (isExists) + { + return result; + } + + // + XProtectedSignal item; + + // + datetime time = TimeCurrent(); + + // + item.ticket = signal.ticket; + + // + AddItemToBuffer( + time, + item.time); + + // + AddItemToBuffer( + signal.profit, + item.profit); + + // + AddItemToBuffer( + item, + mGuardedSignals); + + // + return result; + } + + // + // Get All ... + void GetAll( + XProtectedSignal &result[] // Hold's Result + ) + { + // + CopyBuffer( + mGuardedSignals, + result); + } + + // + // Get ... + XProtectedSignal Get( + ulong ticket // Specified Signal Ticket + ) + { + // + XProtectedSignal result; + + // + bool isExists = IsExists(ticket); + if (!isExists) + { + return result; + } + + // + int protectedCounts = ArraySize(mGuardedSignals); + if (protectedCounts <= 0) + { + return result; + } + + // + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mGuardedSignals[i]; + + // + if (iProtected.ticket == ticket) + { + // + result = iProtected; + break; + } + } + + // + return result; + } + + // + // Remove ... + bool Remove( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + result = IsExists(ticket); + if (!result) + { + return result; + } + + // + int protectedCounts = ArraySize(mGuardedSignals); + result = protectedCounts > 0; + if (!result) + { + return result; + } + + // + XProtectedSignal cleared[]; + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mGuardedSignals[i]; + + // + if (iProtected.ticket != ticket) + { + AddItemToBuffer( + iProtected, + cleared); + } + } + + // + // Update Source by Cleared ... + CopyBuffer( + cleared, + mGuardedSignals); + + // + result = true; + + // + return result; + } + + // + // Update ... + bool Update( + ulong ticket, // Specified Signal Ticket + datetime time, // Specified Last Checked time + double profit // Specified Signal Profit + // XProtectedSignal &item // Specified which object to Update + ) + { + // + bool result = false; + + // + int protectedCounts = ArraySize(mGuardedSignals); + result = protectedCounts > 0; + if (!result) + { + return result; + } + + // + result = IsExists(ticket); + if (!result) + { + return result; + } + + // + // Retrieve Struct ... + XProtectedSignal item = Get(ticket); + AddItemToBuffer( + time, + item.time); + AddItemToBuffer( + profit, + item.profit); + + // + result = Remove(ticket); + if (!result) + { + return result; + } + + // + AddItemToBuffer( + item, + mGuardedSignals); + result = true; + + // + return result; + } + bool Update( + XProtectedSignal &item // Specified Protected Item + ) + { + // + bool result = false; + + // + datetime time; + result = GetLastItem( + time, + item.time); + if (!result) + { + return result; + } + + // + double profit; + result = GetLastItem( + profit, + item.profit); + if (!result) + { + return result; + } + + // + result = Update( + item.ticket, time, profit); + + // + return result; + } + bool Update( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + ulong ticket = signal.ticket; + datetime time = TimeCurrent(); + double profit = signal.profit; + + // + result = Update( + ticket, + time, + profit); + + // + return result; + } + + // + // Add Or Update ... + bool AddOrUpdate( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + bool isExists = IsExists(signal.ticket); + if (!isExists) + { + result = Add(signal); + } + else + { + result = Update(signal); + } + + // + return result; + } + + // + // Check Exists ... + bool IsExists( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + // Validate Args ... + if (ticket <= 0) + { + return result; + } + + // + int protectedCounts = ArraySize(mGuardedSignals); + if (protectedCounts <= 0) + { + return result; + } + + // + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mGuardedSignals[i]; + + // + if (iProtected.ticket == ticket) + { + // + result = true; + break; + } + } + + // + return result; + } + + // + // Count Protecteds ... + int Count() + { + // + int result = 0; + + // + result = ArraySize(mGuardedSignals); + + // + return result; + } + + // + // END Guarded Signals Functions ... + // + + // + // START Supported Signals Functions ... + // + + // + // Check can Handle Support Signals or not ... + bool IsSupportEnabled() + { + // + bool result = false; + + // + result = + mSupportMethod != X_SUPPORT_DO_NOTHING; + + // + return result; + } + + // + // Retrieve List Of Supported Signals ... + void GetSupportSignals( + XSignal &result[], // Hold's Result ... + XCTrade &trader // Specified Trader class Instance ... + ) + { + // + CleanBuffer(result); + + // + XSignal signals[]; + trader.GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = -0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + bool isSupport = IsSupport(iSignal.comment); + if (isSupport) + { + AddItemToBuffer( + iSignal, + result); + } + } + } + + // + // Retrieve List Of Specific Signals Supported Signals ... + void GetSignalSupports( + XSignal &result[], // Hold's Result ... + XCTrade &trader, // Specified Trader class Instance ... + ulong ticket // Specified Signal Ticket ... + ) + { + // + CleanBuffer(result); + + // + // Validate Args ... + if (ticket <= 0) + { + return; + } + + // + // Check Signal Exists using Trader ... + XSignal parentSignal = trader.GetSignal(ticket); + bool isValid = + parentSignal.ticket > 0 && + parentSignal.ticket == ticket && + StringLen(parentSignal.comment) > 0; + if (!isValid) + { + return; + } + + // + XSignal supportSignals[]; + GetSupportSignals( + supportSignals, + trader); + int supportSignalsCount = ArraySize(supportSignals); + if (supportSignalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < supportSignalsCount; i++) + { + // + XSignal iSignal = supportSignals[i]; + + // + bool isBelongsToParent = IsBelongsToParent( + ticket, + iSignal.comment); + if (isBelongsToParent) + { + AddItemToBuffer( + iSignal, + result); + } + } + } + + // + // Check Specific Support Conditions for Opening Directional Support ... + bool CanDoDirectionalSupport( + XCTrade &trader, // Specified Trader class Instance ... + ulong ticket, // Specified Signal Ticket ... + int numberOfItemsCheck = 30 // Number of Items to check ... + ) + { + // + bool result = false; + + // + // Check Supports Enabled ... + result = IsSupportEnabled(); + if (!result) + { + return result; + } + + // + // Check Support Method Allows Directional ... + result = + mSupportMethod == X_SUPPORT_FULL || + mSupportMethod == X_SUPPORT_IN_DRAWUP_DIRECTIONAL; + if (!result) + { + return result; + } + + // + // Validate Ticket ... + result = ticket > 0; + if (!result) + { + return result; + } + + // + // Check Supports Count ... + int supportedCount = ArraySize(mSupportedSignals); + result = supportedCount > 0; + if (!result) + { + return result; + } + + // + // Check Ticket Exists in Supports ... + result = IsSupportExists(ticket); + if (!result) + { + return result; + } + + // + // Check signal Doesn't have any Support ... + XSignal supports[]; + GetSignalSupports( + supports, + trader, + ticket); + int supportsCount = ArraySize(supports); + result = supportsCount <= 0; + if (!result) + { + return result; + } + + // + // Retrieve Support Model ... + XProtectedSignal sInfo = GetSupport(ticket); + + // + // Validate Model ... + int sTimesCount = ArraySize(sInfo.time); + int sProfitsCount = ArraySize(sInfo.profit); + result = + sInfo.ticket == ticket && + sTimesCount == sProfitsCount && + sTimesCount >= numberOfItemsCheck && + sProfitsCount >= numberOfItemsCheck; + if (!result) + { + return result; + } + + // + // Validate Signal Age ... + XSignal sSignal = trader.GetSignal(ticket); + int sSignalAge = trader.GetSignalAge(sSignal.time); + result = sSignalAge >= numberOfItemsCheck; + if (!result) + { + return result; + } + + // + // Extrat Profits ... + double lastProfits[]; + for (int i = sProfitsCount - 1; i >= (sProfitsCount - numberOfItemsCheck); i++) + { + // + double iProfit = sInfo.profit[i]; + + // + AddItemToBuffer( + iProfit, + lastProfits); + } + + // + string logMsg = ToString(lastProfits); + LogMessage("" + (string)ticket + " lastProfits: \n" + logMsg); + + // + result = false; + + // + // Now implement Business Logics ... + + // + return result; + } + + // + // Check Specific Support Conditions for Opening InDirectional Support ... + bool CanDoInDirectionalSupport( + XCTrade &trader, // Specified Trader class Instance ... + ulong ticket, // Specified Signal Ticket ... + int numberOfItemsCheck = 30 // Number of Items to check ... + ) + { + // + bool result = false; + + // + // Check Supports Enabled ... + result = IsSupportEnabled(); + if (!result) + { + return result; + } + + // + // Check Support Method Allows Directional ... + result = + mSupportMethod == X_SUPPORT_FULL || + mSupportMethod == X_SUPPORT_IN_DRAWDOWN_INDIRECTIONAL; + if (!result) + { + return result; + } + + // + // Validate Ticket ... + result = ticket > 0; + if (!result) + { + return result; + } + + // + // Check Supports Count ... + int supportedCount = ArraySize(mSupportedSignals); + result = supportedCount > 0; + if (!result) + { + return result; + } + + // + // Check Ticket Exists in Supports ... + result = IsSupportExists(ticket); + if (!result) + { + return result; + } + + // + // Check signal Doesn't have any Support ... + XSignal supports[]; + GetSignalSupports( + supports, + trader, + ticket); + int supportsCount = ArraySize(supports); + result = supportsCount <= 0; + if (!result) + { + return result; + } + + // + // Retrieve Support Model ... + XProtectedSignal sInfo = GetSupport(ticket); + + // + // Validate Model ... + int sTimesCount = ArraySize(sInfo.time); + int sProfitsCount = ArraySize(sInfo.profit); + result = + sInfo.ticket == ticket && + sTimesCount == sProfitsCount && + sTimesCount >= numberOfItemsCheck && + sProfitsCount >= numberOfItemsCheck; + if (!result) + { + return result; + } + + // + // Validate Signal Age ... + XSignal sSignal = trader.GetSignal(ticket); + int sSignalAge = trader.GetSignalAge(sSignal.time); + result = sSignalAge >= numberOfItemsCheck; + if (!result) + { + return result; + } + + // + // Extrat Profits ... + double lastProfits[]; + for (int i = sProfitsCount - 1; i >= (sProfitsCount - numberOfItemsCheck); i++) + { + // + double iProfit = sInfo.profit[i]; + + // + AddItemToBuffer( + iProfit, + lastProfits); + } + + // + string logMsg = ToString(lastProfits); + LogMessage("" + (string)ticket + " lastProfits: \n" + logMsg); + + // + result = false; + + // + // Now implement Business Logics ... + + // + return result; + } + + // + // Generate Directional Support Signal for Parent Signal ... + XSignal GenerateDirectionalSupportSignal( + ulong ticket, // Specified Parent Signal Ticket ... + XCTrade &trader // Specified Trader Class ... + ) + { + // + XSignal result = {}; + + // + // Validate Args ... + if (ticket <= 0) + { + return result; + } + + // + XSignal pSignal = trader.GetSignal(ticket); + bool isValidParent = + pSignal.ticket > 0 && + pSignal.ticket == ticket && + StringLen(pSignal.comment) > 0; + if (!isValidParent) + { + return result; + } + + // + ENUM_X_SIGNAL_TYPE type = pSignal.type; + bool isLong = IsLong(type); + + // + double entry = GetEntry( + pSignal.symbol, + type); + double exit = GetExit( + pSignal.symbol, + type); + + // + double reward = PipsToPrice( + pSignal.symbol, + 6); + double risk = PipsToPrice( + pSignal.symbol, + 1); + + // + double tp = + isLong + ? entry + reward + : entry - reward; + + // + double sl = + isLong + ? exit - risk + : exit + risk; + + // + double rfStep = 2; + double rfRate = 0.5; + + // + double volume = NormalizeVolume( + pSignal.volume / 2, + pSignal.symbol, + 2); + + // + // Generate Signal using Trader Class Instance ... + result = trader.GenerateSignal( + // + type, + tp, + sl, + volume, + rfStep, + rfRate + // + ); + + // + return result; + } + + // + // Generate InDirectional Support Signal for Parent Signal ... + XSignal GenerateInDirectionalSupportSignal( + ulong ticket, // Specified Parent Signal Ticket ... + XCTrade &trader // Specified Trader Class ... + ) + { + // + XSignal result = {}; + + // + // Validate Args ... + if (ticket <= 0) + { + return result; + } + + // + XSignal pSignal = trader.GetSignal(ticket); + bool isValidParent = + pSignal.ticket > 0 && + pSignal.ticket == ticket && + StringLen(pSignal.comment) > 0; + if (!isValidParent) + { + return result; + } + + // + ENUM_X_SIGNAL_TYPE type = trader + .GetIndirectionSignalType(pSignal.type); + bool isLong = IsLong(type); + + // + double entry = GetEntry( + pSignal.symbol, + type); + double exit = GetExit( + pSignal.symbol, + type); + + // + double reward = PipsToPrice( + pSignal.symbol, + 6); + double risk = PipsToPrice( + pSignal.symbol, + 1); + + // + double tp = + isLong + ? entry + reward + : entry - reward; + + // + double sl = + isLong + ? exit - risk + : exit + risk; + + // + double rfStep = 2; + double rfRate = 0.5; + + // + double volume = NormalizeVolume( + pSignal.volume / 2, + pSignal.symbol, + 2); + + // + // Generate Signal using Trader Class Instance ... + result = trader.GenerateSignal( + // + type, + tp, + sl, + volume, + rfStep, + rfRate + // + ); + + // + return result; + } + + // + // Generate Specific Signals Support Signal Comment ... + string GenerateSupportSignalComment( + ulong ticket, // Specified Parent Signal Ticket + ENUM_X_SIGNAL_TYPE type, // Specified Support Signal Type + bool isInDirectional = false // Specified Support Signal Direction + ) + { + // + string result = ""; + + // + if (ticket <= 0) + { + return result; + } + + // + string typeString = GetSignalType(type); + string directionStr = GenerateSupportDirection(isInDirectional); + + // + result = + mSupportPrefix + "(" + (string)ticket + ")_" + + X_SIGNAL_TYPE + "(" + typeString + ")_" + + directionStr; + + // + return result; + } + + // + // Get Support Direction String Representation ... + string GenerateSupportDirection( + bool isInDirectional = false // Specified Support Signal Direction + ) + { + // + string result = ""; + + // + result = + isInDirectional + ? mInDirectional + : mDirectional; + + // + return result; + } + + // + // Check an String Is Directional Or not ... + bool IsDirectionalSupport( + string comment // Specified Comment ... + ) + { + // + bool result = false; + + // + result = IsSupport(comment); + if (!result) + { + return result; + } + + // + int sPos = StringFind( + comment, + mDirectional); + result = sPos >= 0; + + // + return result; + } + + // + // Check an String Is In Directional Or not ... + bool IsInDirectionalSupport( + string comment // Specified Comment ... + ) + { + // + bool result = false; + + // + result = IsSupport(comment); + if (!result) + { + return result; + } + + // + int sPos = StringFind( + comment, + mInDirectional); + result = sPos >= 0; + + // + return result; + } + + // + // Check an String Is Support or not ... + bool IsSupport( + string comment // Specified Comment ... + ) + { + // + bool result = false; + + // + int sPos = StringFind( + comment, + mSupportPrefix); + result = sPos >= 0; + + // + return result; + } + + // + // Extract Parent of Support Signal Ticket from a comment ... + ulong ExtractParentTicket( + string comment // Specified Comment ... + ) + { + // + ulong result = 0; + + // + bool isSupport = IsSupport(comment); + if (!isSupport) + { + return result; + } + + // + // TICKET ... + string ticketStr = ExtractString( + comment, + mSupportPrefix + "(", + ")"); + if (StringLen(ticketStr) > 0) + { + result = (ulong)ticketStr; + } + + // + return result; + } + + // + // Check a Comment belongs to Support Signal or not ... + bool IsBelongsToParent( + ulong ticket, // Specified Parent Signal Ticket + string comment // Specified Support Signal Comment + ) + { + // + bool result = false; + + // + // Validate Arg ... + if (ticket <= 0) + { + return result; + } + + // + result = IsSupport(comment); + if (!result) + { + return result; + } + + // + ulong spTicket = ExtractParentTicket(comment); + result = spTicket == ticket; + + // + return result; + } + + // + // Add new Protecte Signal ... + bool AddSupport( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + bool isExists = IsSupportExists(signal.ticket); + if (isExists) + { + return result; + } + + // + XProtectedSignal item; + + // + datetime time = TimeCurrent(); + + // + item.ticket = signal.ticket; + + // + AddItemToBuffer( + time, + item.time); + + // + AddItemToBuffer( + signal.profit, + item.profit); + + // + AddItemToBuffer( + item, + mSupportedSignals); + + // + return result; + } + + // + // Get All ... + void GetAllSupports( + XProtectedSignal &result[] // Hold's Result + ) + { + // + CopyBuffer( + mSupportedSignals, + result); + } + + // + // Get ... + XProtectedSignal GetSupport( + ulong ticket // Specified Signal Ticket + ) + { + // + XProtectedSignal result; + + // + bool isExists = IsSupportExists(ticket); + if (!isExists) + { + return result; + } + + // + int protectedCounts = ArraySize(mSupportedSignals); + if (protectedCounts <= 0) + { + return result; + } + + // + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mSupportedSignals[i]; + + // + if (iProtected.ticket == ticket) + { + // + result = iProtected; + break; + } + } + + // + return result; + } + + // + // Remove ... + bool RemoveSupport( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + result = IsSupportExists(ticket); + if (!result) + { + return result; + } + + // + int protectedCounts = ArraySize(mSupportedSignals); + result = protectedCounts > 0; + if (!result) + { + return result; + } + + // + XProtectedSignal cleared[]; + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mSupportedSignals[i]; + + // + if (iProtected.ticket != ticket) + { + AddItemToBuffer( + iProtected, + cleared); + } + } + + // + // Update Source by Cleared ... + CopyBuffer( + cleared, + mSupportedSignals); + + // + result = true; + + // + return result; + } + + // + // Update ... + bool UpdateSupport( + ulong ticket, // Specified Signal Ticket + datetime time, // Specified Last Checked time + double profit // Specified Signal Profit + ) + { + // + bool result = false; + + // + int protectedCounts = ArraySize(mSupportedSignals); + result = protectedCounts > 0; + if (!result) + { + return result; + } + + // + result = IsSupportExists(ticket); + if (!result) + { + return result; + } + + // + // Retrieve Struct ... + XProtectedSignal item = GetSupport(ticket); + AddItemToBuffer( + time, + item.time); + AddItemToBuffer( + profit, + item.profit); + + // + result = RemoveSupport(ticket); + if (!result) + { + return result; + } + + // + AddItemToBuffer( + item, + mSupportedSignals); + result = true; + + // + return result; + } + bool UpdateSupport( + XProtectedSignal &item // Specified Protected Item + ) + { + // + bool result = false; + + // + datetime time; + result = GetLastItem( + time, + item.time); + if (!result) + { + return result; + } + + // + double profit; + result = GetLastItem( + profit, + item.profit); + if (!result) + { + return result; + } + + // + result = UpdateSupport( + item.ticket, time, profit); + + // + return result; + } + bool UpdateSupport( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + ulong ticket = signal.ticket; + datetime time = TimeCurrent(); + double profit = signal.profit; + + // + result = UpdateSupport( + ticket, + time, + profit); + + // + return result; + } + + // + // Add Or Update ... + bool AddOrUpdateSupport( + XSignal &signal // Specified Signal + ) + { + // + bool result = false; + + // + bool isExists = IsSupportExists(signal.ticket); + if (!isExists) + { + result = Add(signal); + } + else + { + result = Update(signal); + } + + // + return result; + } + + // + // Check Exists ... + bool IsSupportExists( + ulong ticket // Specified Signal Ticket + ) + { + // + bool result = false; + + // + // Validate Args ... + if (ticket <= 0) + { + return result; + } + + // + int protectedCounts = ArraySize(mSupportedSignals); + if (protectedCounts <= 0) + { + return result; + } + + // + for (int i = 0; i < protectedCounts; i++) + { + // + XProtectedSignal iProtected = mSupportedSignals[i]; + + // + if (iProtected.ticket == ticket) + { + // + result = true; + break; + } + } + + // + return result; + } + + // + // Count Protecteds ... + int CountSupports() + { + // + int result = 0; + + // + result = ArraySize(mSupportedSignals); + + // + return result; + } + + // + // END Suppoprted Signals Functions ... + // + + // + // START Getter/Setter(s) ... + // + + // + int GetOldAge() + { + return mOldAge; + } + + // + bool SetOldAge(int value) + { + // + bool result = false; + + // + result = + value > 0 && + mOldAge != value; + if (!result) + { + return result; + } + + // + mOldAge = value; + + // + return result; + } + + // + ENUM_X_GUARD_ACTIONS GetOldGuardAction() + { + return mOldGuardAction; + } + + // + bool SetOldGuardAction(ENUM_X_GUARD_ACTIONS value) + { + // + bool result = false; + + // + result = value != mOldGuardAction; + if (!result) + { + return result; + } + + // + mOldGuardAction = value; + + // + return result; + } + + // + double GetCriticalFactor() + { + return mCriticalFactor; + } + + // + bool SetCriticalFactor(bool value) + { + // + bool result = false; + + // + result = + value > 0 && + value < 1 && + mCriticalFactor != value; + if (!result) + { + return result; + } + + // + mCriticalFactor = value; + + // + double deposit = mAccountInfo.GetInitialBalance(); + mCriticalValue = deposit * value; + + // + return result; + } + + // + ENUM_X_GUARD_ACTIONS GetCriticalAction() + { + return mCriticalAction; + } + + // + bool SetCriticalAction(ENUM_X_GUARD_ACTIONS value) + { + // + bool result = false; + + // + result = + value != mCriticalAction; + if (!result) + { + return result; + } + + // + mCriticalAction = value; + + // + return result; + } + + // + double GetMaxFactor() + { + return mMaxFactor; + } + + // + bool SetMaxFactor(bool value) + { + // + bool result = false; + + // + result = + value > 0 && + value < 1 && + mMaxFactor != value; + if (!result) + { + return result; + } + + // + mMaxFactor = value; + + // + double deposit = mAccountInfo.GetInitialBalance(); + mMaxValue = deposit * value; + + // + return result; + } + + // + ENUM_X_GUARD_ACTIONS GetMaxAction() + { + return mMaxAction; + } + + // + bool SetMaxAction(ENUM_X_GUARD_ACTIONS value) + { + // + bool result = false; + + // + result = + value != mMaxAction; + if (!result) + { + return result; + } + + // + mMaxAction = value; + + // + return result; + } + + // + ENUM_X_GUARD_SUPPORT_METHODS GetSupportMethod() + { + return mSupportMethod; + } + + // + bool SetSupportMethod(ENUM_X_GUARD_SUPPORT_METHODS value) + { + // + bool result = false; + + // + result = + value != mSupportMethod; + if (!result) + { + return result; + } + + // + mSupportMethod = value; + + // + return result; + } + + // + // END Getter/Setter(s) ... + // + + // + // Generate Signal Guard Attacked Message ... + string GenerateGuardedSignalComment( + XSignal &signal, // Specified Signal + ENUM_X_GUARD_REASONS reason // Specified Guard Reason + ) + { + // + string result = ""; + + // + string reasonMessage = + ( + // + reason == X_GUARDED_OLD + ? "Because of Old Issue" + : reason == X_GUARDED_CRITICAL + ? "Because Of Crtical Drawdown Isuue" + : reason == X_GUARDED_MAX + ? "Because of Max Drawdown Issue" + : "" + // + ) + + " On Profit: " + (string)signal.profit; + + // + result += "Guard Attacked (" + (string)signal.ticket + "), " + reasonMessage + " ..."; + + // + return result; + } + + // + // Protected ... +protected: + // + // Private ... +private: + // + string mSupportPrefix; + string mDirectional; + string mInDirectional; + + // + XProtectedSignal mGuardedSignals[]; + XProtectedSignal mSupportedSignals[]; + + // + int mOldAge; + ENUM_X_GUARD_ACTIONS mOldGuardAction; + + // + // Critical DrawDown Factor based On Balance ... + double mCriticalFactor; + double mCriticalValue; + + // + // Guard Action for Critical State ... + ENUM_X_GUARD_ACTIONS mCriticalAction; + + // + // Max DrawDown Factor based on Balance ... + double mMaxFactor; + double mMaxValue; + // + // Guard Stopout if Max State touched ... + int mOccuredconsecutiveMaxDraDownTouches; + int mGuardStopoutFiredAfterTouches; + + // + // Guard Action for Max State ... + ENUM_X_GUARD_ACTIONS mMaxAction; + + // + // How to Support Signals ... + ENUM_X_GUARD_SUPPORT_METHODS mSupportMethod; + + // + // Account Info Instance ... + XCAccountInfo mAccountInfo; + + // + // Get Volume Multiplier for Specified Guard Action ... + double GetGuardActionVolumeMultiplier( + ENUM_X_GUARD_ACTIONS action = X_GUARD_DO_NOTHING // Specified Action + ) + { + // + // Partial Close Max In Drawdown Trade ... + double result = 0.0; + if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1) + { + result = 0.01; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_2) + { + result = 0.02; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_3) + { + result = 0.03; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5) + { + result = 0.05; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10) + { + result = 0.10; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_15) + { + result = 0.15; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_20) + { + result = 0.20; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_25) + { + result = 0.25; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_30) + { + result = 0.30; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_40) + { + result = 0.40; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_50) + { + result = 0.50; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_60) + { + result = 0.60; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_70) + { + result = 0.70; + } + else if (action == X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_75) + { + result = 0.75; + } + + // + return result; + } + + // + // Do Specified Guard Action ... + bool DoGuardAction( + XGuardHandlerResult &guardResult, // Hold's Result ... + string &message, // Hold's Message ... + XCTrade &trader, // Specified Trader Class ... + ENUM_X_GUARD_ACTIONS action, // Specified Which Action to Do ... + ENUM_X_GUARD_REASONS reason, // Specified Guard Reason ... + ENUM_TIMEFRAMES period = NULL // Specified Time Frame for Detecting Signal Ages ... + ) + { + // + bool result = false; + + // + message = ""; + + // + string reasonString = + reason == X_GUARDED_OLD + ? "Because of Age Issue" + : "Because of DD " + ( + // + reason == X_GUARDED_CRITICAL ? "Critical" : "Max" + // + ) + + " Issue"; + + // + // Validate Args ... + if (action == X_GUARD_DO_NOTHING) + { + // + message = "Max Allowed Drawdown Reached, but nothing Happens ..."; + + // + return result; + } + + // + // Normalize Period ... + if (period == NULL) + { + period = _Period; + } + + // + // Close All Signals ... + XSignal closed[]; + XSignal maxInDDSignal; + + // + // Handle Perform Guard Action ... + switch (action) + { + // + // Close All ... + case X_GUARD_CLOSE_ALL: + { + // + trader.CloseSignals(closed); + int closedCount = ArraySize(closed); + result = closedCount > 0; + if (!result) + { + break; + } + + // + message = "Closed (" + (string)closedCount + ") Trades by Guard, " + reasonString + " ..."; + } + break; + + // + case X_GUARD_CLOSE_MAX_IN_DD: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_2: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_3: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_15: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_20: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_25: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_30: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_40: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_50: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_60: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_70: + case X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_75: + { + // + // Retrieve Max In Drawdown Trade ... + maxInDDSignal = trader.GetMaxInDrawdownSignal(); + bool isValid = IsValid(maxInDDSignal, trader.GetMagicNumber()) && maxInDDSignal.ticket > 0; + if (!isValid) + { + break; + } + + // + // Close Max In Drawdown Trade ... + if (action == X_GUARD_CLOSE_MAX_IN_DD) + { + // + string comment = "Signal (" + (string)maxInDDSignal.ticket + ") Closed by Guard ..."; + result = trader.Close( + maxInDDSignal.ticket, + comment); + if (result) + { + message = comment; + } + + // + break; + } + + // + int signalAge = 0; + bool canGuard = true; + bool isGuardedBefore = false; + + // + // Do Some Additional Verifications if Guard for Olds Trades ... + if (reason == X_GUARDED_OLD) + { + // + // Retrieve Signal Age ... + signalAge = trader.GetSignalAge( + maxInDDSignal, + period); + + // + // Check Guarded Before Or Not ... + isGuardedBefore = IsExists(maxInDDSignal.ticket); + if (isGuardedBefore) + { + // + // Now We Have to Check Signal Age growse required times to apply Guard Action again ... + // First Calculate Guard Grow Step ... + int ageGrowStep = mOldAge / 10; + + // + XProtectedSignal guardItem = Get(maxInDDSignal.ticket); + datetime lastGuardTime = 0; + if (GetLastItem(lastGuardTime, guardItem.time)) + { + // + int lastGuardIndex = iBarShift( + maxInDDSignal.symbol, + period, + lastGuardTime); + + // + canGuard = + MathAbs(lastGuardIndex) >= ageGrowStep; + } + } + else + { + // + // Check Signal age ... + canGuard = signalAge >= mOldAge; + } + } + + // + // Prevent Moving Forward ... + if (!canGuard) + { + // + result = false; + break; + } + + // + // Partial Close Max In Drawdown Trade ... + double volumeRate = GetGuardActionVolumeMultiplier(action); + + // + double volume = NormalizeVolume( + maxInDDSignal.volume * volumeRate, + maxInDDSignal.symbol); + + // + string commentPrefix = "Signal (" + (string)maxInDDSignal.ticket + ") Partial Closed (" + (string)volumeRate + ") by Guard"; + string comment = commentPrefix + " ..."; + + // + result = trader.ClosePartial( + maxInDDSignal.ticket, + volume, + comment); + if (result) + { + // + reasonString = + reasonString + + (reason == X_GUARDED_OLD + ? " (" + (string)signalAge + ")" + : " (" + (string)maxInDDSignal.profit + ")"); + + // + // Update Guarded Signals ... + if (isGuardedBefore) + { + // + XSignal tSignal = trader.GetSignal(maxInDDSignal.ticket); + + // + if (tSignal.ticket > 0 && tSignal.volume > 0) + { + // + // Update In Guardeds ... + Update(tSignal); + } + else + { + // + // Remove From Guardeds ... + Remove(tSignal.ticket); + } + } + else if (reason == X_GUARDED_OLD) + { + // + // Added to Guardeds ... + Add(maxInDDSignal); + } + + // + message = commentPrefix + reasonString + " ..."; + } + } + break; + + // + // Nothing ... + // Default ... + default: + message = "Max Allowed Drawdown Reached ..."; + break; + } + + // + result = StringLen(message) > 0; + if (!result) + { + return result; + } + + // + if (result) + { + // + if (reason == X_GUARDED_OLD) + { + // + int closedCount = ArraySize(closed); + if (closedCount > 0) + { + // + for (int i = 0; i < closedCount; i++) + { + AddItemToBuffer( + closed[i], + guardResult.olds); + } + } + + // + if (maxInDDSignal.ticket > 0) + { + AddItemToBuffer( + maxInDDSignal, + guardResult.olds); + } + } + else if (reason == X_GUARDED_CRITICAL) + { + // + int closedCount = ArraySize(closed); + if (closedCount > 0) + { + // + for (int i = 0; i < closedCount; i++) + { + AddItemToBuffer( + closed[i], + guardResult.criticals); + } + } + + // + if (maxInDDSignal.ticket > 0) + { + AddItemToBuffer( + maxInDDSignal, + guardResult.criticals); + } + } + else if (reason == X_GUARDED_MAX) + { + // + int closedCount = ArraySize(closed); + if (closedCount > 0) + { + // + for (int i = 0; i < closedCount; i++) + { + AddItemToBuffer( + closed[i], + guardResult.maxes); + } + } + + // + if (maxInDDSignal.ticket > 0) + { + AddItemToBuffer( + maxInDDSignal, + guardResult.maxes); + } + } + } + + // + return result; + } +}; + +// +// END Global Definitions: Variables, Properties and etc ... +// diff --git a/Projects/XUSCHF5/Classes/x-saherelm.nn.lib.mq5 b/Projects/XUSCHF5/Classes/x-saherelm.nn.lib.mq5 new file mode 100644 index 00000000..8fa40f53 --- /dev/null +++ b/Projects/XUSCHF5/Classes/x-saherelm.nn.lib.mq5 @@ -0,0 +1,258 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 NN Class Library +// ---------------------------------------- +// Name: XNNClass +// Description: provides all classes for implementing +// Neural Network ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Global Definitions: Variables, Properties and etc ... +// +class XCNNBase +{ + // + // Public Definitions ... +public: + // + // Constructor ... + void XCNNBase( + int nodes = 10, // Number of Input Nodes + double starterWeight = 0.5, // start weight for each input + double coEfficient = 0.1, // COEfficient Multiplier + double upperRange = 1, // Upper Normal Range Value + double lowerRange = -1, // Lower Normal Range Value + double learningRates = 0.1 // Back Propagation Learning Rate + ) { + // + mNodes = nodes; + mUpperRange = upperRange; + mLowerRange = lowerRange; + mCoEfficient = coEfficient; + mLearningRates = learningRates; + mStarterWeight = starterWeight; + + // + ReConstructWeights(); + } + + // + // Deconstructor ... + void ~XCNNBase() {} + + // + // Protected Definitions ... + void NormalizeInputs(double &inputs[], double &result[]) + { + // + ArrayFree(result); + ArrayResize(result, 1); + + // + // Validate inputs ... + if (ArraySize(inputs) != mNodes) + { + return; + } + + // + // Prepare Result ... + ArrayResize(result, mNodes); + + // + // Calculating min and max range value ... + double minRangeValue = inputs[ArrayMinimum(inputs)]; + double maxRangeValue = inputs[ArrayMaximum(inputs)]; + + // + // Loop through Inputs nd Normalize them ... + for (int i = 0; i < mNodes; i++) + { + // + double normalValue = (((inputs[i] - minRangeValue) * (mUpperRange - mLowerRange)) / (maxRangeValue - minRangeValue)) + mLowerRange; + result[i] = normalValue; + } + } + + // + // Hyperbolic Tangent Activation Function ... + double TanHActivationFunction(double weightedInputs) + { + // + double result = (exp(weightedInputs) - exp(-weightedInputs)) / (exp(weightedInputs) + exp(-weightedInputs)); + return result; + } + + // + // Calculate Weighted Inputs ... + double CalculateWeightedInputs( + double &inputs[], + bool applyCOEfficient = true) + { + // + double result = 0; + + // + // Validate Inputs ... + if (ArraySize(inputs) != mNodes) + { + // + result = -1; + return result; + } + + // + for (int i = 0; i < mNodes; i++) + { + result += inputs[i] * mWeights[i]; + } + + // + // Multiply if required ... + if (applyCOEfficient) + { + result *= mCoEfficient; + } + + // + return result; + } + + // + // Calculate Hidden Layers ... + virtual double CalculateHiddenLayer(double &inputs[]) + { + // + // this is Default Activation Function which used ... + // you can override this by writing your own ... + double totalWeightedInputs = CalculateWeightedInputs(inputs); + double result = TanHActivationFunction(totalWeightedInputs); + + // + return result; + } + + // + // Calculate Output Layers ... + double CalculateOutputLayer(double &inputs[]) + { + // + double result = -1; + + // + // Validate Inputs ... + if (ArraySize(inputs) != mNodes) { + return result; + } + + // + double normalizedInputs[]; + NormalizeInputs(inputs, normalizedInputs); + if (ArraySize(normalizedInputs) != mNodes) { + return result; + } + + // + double hiddenLayerResult = CalculateHiddenLayer(normalizedInputs); + + // + result = 1 * hiddenLayerResult; + + // + return result; + } + + // + // Basck Propaggation Learning ... + void BackPropagation( + double &inputs[], + double &outputs, + double targetOutput + ) { + // + // Validate Inputs ... + if (ArraySize(inputs) != mNodes) { + return; + } + + // + double normalizedInputs[]; + NormalizeInputs(inputs, normalizedInputs); + if (ArraySize(normalizedInputs) != mNodes) { + return; + } + + // + double error = targetOutput - outputs; + double derivative = 1 - MathPow(outputs, 2); + + // + for (int i = 0; i < mNodes; i++) { + // + double gradient = error * derivative * inputs[i]; + mWeights[i] = mLearningRates * gradient; + } + } + +protected: + // + // Private Definitions ... +private: + // + // Number of Input Nodes ... + int mNodes; + + // + // Specify Upper range of Normal Values ... + double mUpperRange; + + // + // Specify Lower range of Normal Values ... + double mLowerRange; + + // + // Starter Weight for each input node ... + double mStarterWeight; + + // + // double Input Node Weights ... + double mWeights[]; + + // + // CoEfficient is a multiplyer for weighted inputs ... + double mCoEfficient; + + // + // Back Propagation Learning Rates ... + double mLearningRates; + + // + // ReConstruct Weights ... + void ReConstructWeights() { + // + ArrayFree(mWeights); + ArrayResize(mWeights, mNodes); + + // + for (int i = 0; i< mNodes; i++) { + mWeights[i] = mStarterWeight; + } + } +} +// +// END Global Definitions: Variables, Properties and etc ... +// diff --git a/Projects/XUSCHF5/Classes/x-saherelm.provider.lib.mq5 b/Projects/XUSCHF5/Classes/x-saherelm.provider.lib.mq5 new file mode 100644 index 00000000..765544c7 --- /dev/null +++ b/Projects/XUSCHF5/Classes/x-saherelm.provider.lib.mq5 @@ -0,0 +1,4430 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XProvider +// Description: provides all indicators based provider classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Define Enums ... +// + +// +enum ENUM_X_SIGNAL_PROVIDERS +{ + // + // XSP Expert Support Mechanism ... + XSP, + // + // XTD ... + XTD, + // + // XTAM ... + XTAM, + // + // XSI ... + XSI, + // + // XTSFI ... + XTSFI, + // + // XOBDLH ... + XOBDLH, + // + // XCHMACC ... + XCHMACC, + // + // XCHMACMN ... + XCHMAMN, + // + // XCHMACMX ... + XCHMAMX, +}; + +// +// Represent Market Conditions ... +struct XMarketConditions +{ + // + // XTM ... + bool isXTMPeak; + bool isXTMVale; + bool isXTMBullish; + bool isXTMBearish; + bool isXTMNeutural; + bool isXTMEndBullish; + bool isXTMEndBearish; + bool isXTMStartBullish; + bool isXTMStartBearish; + bool isXTMEndBullishByNeutural; + bool isXTMEndBearishByNeutural; + bool isXTMStartBullishAfterNeutural; + bool isXTMStartBearishAfterNeutural; + + // + // XAMA ... + bool isXAMAPeak; + bool isXAMAVale; + bool isXAMABullish; + bool isXAMABearish; + bool isXAMANeutural; + bool isXAMAEndBullish; + bool isXAMAEndBearish; + bool isXAMAStartBullish; + bool isXAMAStartBearish; + bool isXAMAEndBullishByNeutural; + bool isXAMAEndBearishByNeutural; + bool isXAMAStartBullishAfterNeutural; + bool isXAMAStartBearishAfterNeutural; + + // + // XLH ... + bool isXLHHHIncreased; + bool isXLHHHDecreased; + bool isXLHLLIncreased; + bool isXLHLLDecreased; + bool isXLHLowAttachedLL; + bool isXLHHighAttachedHH; + bool isXLHHHSameInLength; + bool isXLHLLSameInLength; + bool isXLHPriceOverSignal; + bool isXLHPriceUnderSignal; + bool isXLHPriceInSignalRange; + bool isXLHPriceCrossedOverSignal; + bool isXLHPriceCrossedUnderSignal; + + // + // XTD ... + bool isXTDSignalPeak; + bool isXTDSignalVale; + bool isXTDBullishPeak; + bool isXTDBullishVale; + bool isXTDBearishPeak; + bool isXTDBearishVale; + bool isXTDBullOverBear; + bool isXTDBullUnderBear; + bool isXTDSignalOverBear; + bool isXTDSignalUnderBear; + bool isXTDBullCrossedOverBear; + bool isXTDBullCrossedUnderBear; + bool isXTDSignalCrossedOverBear; + bool isXTDSignalCrossedUnderBear; + + // + // XFI ... + bool isXFIPeak; + bool isXFIVale; + bool isXFICrossedOverZero; + bool isXFIOverZero; + bool isXFICrossedUnderZero; + bool isXFIUnderZero; + + // + // XTS ... + bool isXTSAllSame; + bool isXTSCurrentMin; + bool isXTSCurrentMax; + bool isXTSCurrentOverFarest; + bool isXTSCurrentOverNearest; + bool isXTSCurrentOverMediest; + bool isXTSCurrentUnderFarest; + bool isXTSCurrentUnderNearest; + bool isXTSCurrentUnderMediest; + bool isXTSCurrentCrossedOverFarest; + bool isXTSCurrentCrossedOverNearest; + bool isXTSCurrentCrossedOverMediest; + bool isXTSCurrentCrossedUnderFarest; + bool isXTSCurrentCrossedUnderNearest; + bool isXTSCurrentCrossedUnderMediest; + + // + // XRSI ... + bool isXRSIPeak; + bool isXRSIVale; + bool isXRSICrossedOverLongExit; + bool isXRSICrossedOverLongEntry; + bool isXRSICrossedUnderShortExit; + bool isXRSICrossedUnderShortEntry; + + // + // XOBD ... + bool isXOBDSwingLow; + bool isXOBDSwingHigh; + + // + // XCHLH ... + // + bool isXCHLHSameHHs; + bool isXCHLHSameLLs; + // + bool isXCHLHSCMCHHSame; + bool isXCHLHSCMCLLSame; + // + bool isXCHLHSCLCHHSame; + bool isXCHLHSCLCLLSame; + // + bool isXCHLHMCLCHHSame; + bool isXCHLHMCLCLLSame; + // + bool isXCHLHMCOnTopOfLC; + bool isXCHLHMCInBottomOfLC; + + // + // XCHMA ... + // + bool isXCHMASCOverMax; + bool isXCHMASCOverMin; + bool isXCHMASCUnderMax; + bool isXCHMASCUnderMin; + // + bool isXCHMASCCrossedOverMax; + bool isXCHMASCCrossedUnderMax; + bool isXCHMASCCrossedOverMin; + bool isXCHMASCCrossedUnderMin; + // + bool isXCHMASCPeak; + bool isXCHMASCVale; + bool isXCHMASCTrendsUp; + bool isXCHMASCTrendsDown; + bool isXCHMASCFastOverSlow; + bool isXCHMASCFastUnderSlow; + bool isXCHMASCFastCrossedOverSlow; + bool isXCHMASCFastCrossedUnderSlow; + // + bool isXCHMAMCPeak; + bool isXCHMAMCVale; + bool isXCHMAMCTrendsUp; + bool isXCHMAMCTrendsDown; + bool isXCHMAMCFastOverSlow; + bool isXCHMAMCFastUnderSlow; + bool isXCHMAMCFastCrossedOverSlow; + bool isXCHMAMCFastCrossedUnderSlow; + // + bool isXCHMALCPeak; + bool isXCHMALCVale; + bool isXCHMALCTrendsUp; + bool isXCHMALCTrendsDown; + bool isXCHMALCFastOverSlow; + bool isXCHMALCFastUnderSlow; + bool isXCHMALCFastCrossedOverSlow; + bool isXCHMALCFastCrossedUnderSlow; +}; + +// +// END Define Enums ... +// + +// +// START Includes Requirements ... +// + +// +// Includes Classes ... +#include "x-saherelm.class.lib.mq5" + +// +// Includes all Indicator's Helpers ... +#include "../Helpers/x-saherelm.xlh.indicator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xtm.indicator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xama.indicator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xobd.indicator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xts.oscillator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5" +#include "../Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5" + +// +// END Includes Requirements ... +// + +// +class XCPriver : public XCBase +{ + // + // Public ... +public: + // + // Constructor ... + XCPriver( + // + // Common Requirements ... + string xSymbol, // Which Symbol is Used + ENUM_TIMEFRAMES xPeriod, // Which Period is Used + // + // Signallers Requirements ... + // + // XTD ... + bool xTDEnableSignaller, // Enable Signaller + bool xTDAllowLongSignals, // Allow Long Signals + bool xTDAllowShortSignals, // Allow Short Signals + // + // XTAM ... + bool xTAMEnableSignaller, // Enable Signaller + bool xTAMAllowLongSignals, // Allow Long Signals + bool xTAMAllowShortSignals, // Allow Short Signals + // + // XSI ... + bool xSIEnableSignaller, // Enable Signaller + bool xSIAllowLongSignals, // Allow Long Signals + bool xSIAllowShortSignals, // Allow Short Signals + // + // XTSFI ... + bool XTSFIEnableSignaller, // Enable Signaller + bool XTSFIAllowLongSignals, // Allow Long Signals + bool XTSFIAllowShortSignals, // Allow Short Signals + // + // XOBDLH ... + bool xOBDLHEnableSignaller, // Enable Signaller + bool xOBDLHAllowLongSignals, // Allow Long Signals + bool xOBDLHAllowShortSignals, // Allow Short Signals + // + // XCHMACC ... + bool xCHMACCEnableSignaller, // Enable Signaller + bool xCHMACCAllowLongSignals, // Allow Long Signals + bool xCHMACCAllowShortSignals, // Allow Short Signals + // + // XCHMAMX ... + bool xCHMACMXEnableSignaller, // Enable Signaller + bool xCHMACMXAllowLongSignals, // Allow Long Signals + bool xCHMACMXAllowShortSignals, // Allow Short Signals + // + // XCHMAMN ... + bool xCHMACMNEnableSignaller, // Enable Signaller + bool xCHMACMNAllowLongSignals, // Allow Long Signals + bool xCHMACMNAllowShortSignals // Allow Short Signals + // + ) + { + // + // XTD ... + mXTDEnableSignaller = xTDEnableSignaller; + mXTDAllowLongSignals = xTDAllowLongSignals; + mXTDAllowShortSignals = xTDAllowShortSignals; + + // + // XTAM ... + mXTAMEnableSignaller = xTAMEnableSignaller; + mXTAMAllowLongSignals = xTAMAllowLongSignals; + mXTAMAllowShortSignals = xTAMAllowShortSignals; + + // + // XSI ... + mXSIEnableSignaller = xSIEnableSignaller; + mXSIAllowLongSignals = xSIAllowLongSignals; + mXSIAllowShortSignals = xSIAllowShortSignals; + + // + // XTSFI ... + mXTSFIEnableSignaller = XTSFIEnableSignaller; + mXTSFIAllowLongSignals = XTSFIAllowLongSignals; + mXTSFIAllowShortSignals = XTSFIAllowShortSignals; + + // + // XOBDLH ... + mXOBDLHEnableSignaller = xOBDLHEnableSignaller; + mXOBDLHAllowLongSignals = xOBDLHAllowLongSignals; + mXOBDLHAllowShortSignals = xOBDLHAllowShortSignals; + + // + // XCHMACC ... + mXCHMACCEnableSignaller = xCHMACCEnableSignaller; + mXCHMACCAllowLongSignals = xCHMACCAllowLongSignals; + mXCHMACCAllowShortSignals = xCHMACCAllowShortSignals; + + // + // XCHMAMX ... + mXCHMAMXEnableSignaller = xCHMACMXEnableSignaller; + mXCHMAMXAllowLongSignals = xCHMACMXAllowLongSignals; + mXCHMAMXAllowShortSignals = xCHMACMXAllowShortSignals; + + // + // XCHMAMN ... + mXCHMAMNEnableSignaller = xCHMACMNEnableSignaller; + mXCHMAMNAllowLongSignals = xCHMACMNAllowLongSignals; + mXCHMAMNAllowShortSignals = xCHMACMNAllowShortSignals; + } + + // + // Deconstructor ... + ~XCPriver() {} + + // + // START Common Functions ... + // + + // + // Read All Globally Required Conditions ... + void ReadConditions() + { + // + ClearConditions(); + + // + mXConditions = GenerateMarketConditions(1); + } + + // + // Cleanup Conditions ... + void ClearConditions() + { + // + XMarketConditions mConditions = {}; + + // + mXConditions = mConditions; + } + + // + // Generate Merket Conditions for Specified Bar Index ... + XMarketConditions GenerateMarketConditions( + int bar_index = 1 // Specified Bar Index ... + ) + { + // + XMarketConditions mConditions = {}; + + // + // XTM ... + mConditions.isXTMPeak = XTMIsPeak(bar_index); + mConditions.isXTMVale = XTMIsVale(bar_index); + mConditions.isXTMBullish = XTMIsBullish(bar_index); + mConditions.isXTMBearish = XTMIsBearish(bar_index); + mConditions.isXTMNeutural = XTMIsNeutural(bar_index); + mConditions.isXTMEndBullish = XTMIsEndBullish(bar_index); + mConditions.isXTMEndBearish = XTMIsEndBearish(bar_index); + mConditions.isXTMStartBullish = XTMIsStartBullish(bar_index); + mConditions.isXTMStartBearish = XTMIsStartBearish(bar_index); + mConditions.isXTMEndBullishByNeutural = XTMIsEndBullishByNeutural(bar_index); + mConditions.isXTMEndBearishByNeutural = XTMIsEndBearishByNeutural(bar_index); + mConditions.isXTMStartBullishAfterNeutural = XTMIsStartBullishAfterNeutural(bar_index); + mConditions.isXTMStartBearishAfterNeutural = XTMIsStartBearishAfterNeutural(bar_index); + + // + // XAMA ... + mConditions.isXAMAPeak = XAMAIsPeak(bar_index); + mConditions.isXAMAVale = XAMAIsVale(bar_index); + mConditions.isXAMABullish = XAMAIsBullish(bar_index); + mConditions.isXAMABearish = XAMAIsBearish(bar_index); + mConditions.isXAMANeutural = XAMAIsNeutural(bar_index); + mConditions.isXAMAEndBullish = XAMAIsEndBullish(bar_index); + mConditions.isXAMAEndBearish = XAMAIsEndBearish(bar_index); + mConditions.isXAMAStartBullish = XAMAIsStartBullish(bar_index); + mConditions.isXAMAStartBearish = XAMAIsStartBearish(bar_index); + mConditions.isXAMAEndBullishByNeutural = XAMAIsEndBullishByNeutural(bar_index); + mConditions.isXAMAEndBearishByNeutural = XAMAIsEndBearishByNeutural(bar_index); + mConditions.isXAMAStartBullishAfterNeutural = XAMAIsStartBullishAfterNeutural(bar_index); + mConditions.isXAMAStartBearishAfterNeutural = XAMAIsStartBearishAfterNeutural(bar_index); + + // + // XLH ... + mConditions.isXLHHHIncreased = XLHIsHHIncreased(bar_index); + mConditions.isXLHHHDecreased = XLHIsHHDecreased(bar_index); + mConditions.isXLHLLIncreased = XLHIsLLIncreased(bar_index); + mConditions.isXLHLLDecreased = XLHIsLLDecreased(bar_index); + mConditions.isXLHLowAttachedLL = XLHIsLowAttachedLL(bar_index); + mConditions.isXLHHighAttachedHH = XLHIsHighAttachedHH(bar_index); + mConditions.isXLHHHSameInLength = XLHIsHHSameInLength(bar_index); + mConditions.isXLHLLSameInLength = XLHIsLLSameInLength(bar_index); + mConditions.isXLHPriceOverSignal = XLHIsPriceOverSignal(bar_index); + mConditions.isXLHPriceUnderSignal = XLHIsPriceUnderSignal(bar_index); + mConditions.isXLHPriceInSignalRange = XLHIsPriceInSignalRange(bar_index); + mConditions.isXLHPriceCrossedOverSignal = XLHIsPriceCrossedOverSignal(bar_index); + mConditions.isXLHPriceCrossedUnderSignal = XLHIsPriceCrossedUnderSignal(bar_index); + + // + // XTD ... + mConditions.isXTDSignalPeak = XTDIsSignalPeak(bar_index); + mConditions.isXTDSignalVale = XTDIsSignalVale(bar_index); + mConditions.isXTDBullishPeak = XTDIsBullishPeak(bar_index); + mConditions.isXTDBullishVale = XTDIsBullishVale(bar_index); + mConditions.isXTDBearishPeak = XTDIsBearishPeak(bar_index); + mConditions.isXTDBearishVale = XTDIsBearishVale(bar_index); + mConditions.isXTDBullOverBear = XTDIsBullOverBear(bar_index); + mConditions.isXTDBullUnderBear = XTDIsBullUnderBear(bar_index); + mConditions.isXTDSignalOverBear = XTDIsSignalOverBear(bar_index); + mConditions.isXTDSignalUnderBear = XTDIsSignalUnderBear(bar_index); + mConditions.isXTDBullCrossedOverBear = XTDIsBullCrossedOverBear(bar_index); + mConditions.isXTDBullCrossedUnderBear = XTDIsBullCrossedUnderBear(bar_index); + mConditions.isXTDSignalCrossedOverBear = XTDIsSignalCrossedOverBear(bar_index); + mConditions.isXTDSignalCrossedUnderBear = XTDIsSignalCrossedUnderBear(bar_index); + + // + // XFI ... + mConditions.isXFIPeak = XFIIsPeak(bar_index); + mConditions.isXFIVale = XFIIsVale(bar_index); + mConditions.isXFIOverZero = XFIIsOverZero(bar_index); + mConditions.isXFIUnderZero = XFIIsUnderZero(bar_index); + mConditions.isXFICrossedOverZero = XFIIsCrossedOverZero(bar_index); + mConditions.isXFICrossedUnderZero = XFIIsCrossedUnderZero(bar_index); + + // + // XTS ... + mConditions.isXTSAllSame = XTSIsAllSame(bar_index); + mConditions.isXTSCurrentMin = XTSIsCurrentMin(bar_index); + mConditions.isXTSCurrentMax = XTSIsCurrentMax(bar_index); + mConditions.isXTSCurrentOverFarest = XTSIsCurrentOverFarest(bar_index); + mConditions.isXTSCurrentOverNearest = XTSIsCurrentOverNearest(bar_index); + mConditions.isXTSCurrentOverMediest = XTSIsCurrentOverMediest(bar_index); + mConditions.isXTSCurrentUnderFarest = XTSIsCurrentUnderFarest(bar_index); + mConditions.isXTSCurrentUnderNearest = XTSIsCurrentUnderNearest(bar_index); + mConditions.isXTSCurrentUnderMediest = XTSIsCurrentUnderMediest(bar_index); + mConditions.isXTSCurrentCrossedOverFarest = XTSIsCurrentCrossedOverFarest(bar_index); + mConditions.isXTSCurrentCrossedOverNearest = XTSIsCurrentCrossedOverNearest(bar_index); + mConditions.isXTSCurrentCrossedOverMediest = XTSIsCurrentCrossedOverMediest(bar_index); + mConditions.isXTSCurrentCrossedUnderFarest = XTSIsCurrentCrossedUnderFarest(bar_index); + mConditions.isXTSCurrentCrossedUnderNearest = XTSIsCurrentCrossedUnderNearest(bar_index); + mConditions.isXTSCurrentCrossedUnderMediest = XTSIsCurrentCrossedUnderMediest(bar_index); + + // + // XRSI ... + mConditions.isXRSIPeak = XRSIIsPeak(bar_index); + mConditions.isXRSIVale = XRSIIsVale(bar_index); + mConditions.isXRSICrossedOverLongExit = XRSIIsCrossedOverLongExit(bar_index); + mConditions.isXRSICrossedOverLongEntry = XRSIIsCrossedOverLongEntry(bar_index); + mConditions.isXRSICrossedUnderShortExit = XRSIIsCrossedUnderShortExit(bar_index); + mConditions.isXRSICrossedUnderShortEntry = XRSIIsCrossedUnderShortEntry(bar_index); + + // + // XOBD ... + mConditions.isXOBDSwingLow = XOBDIsSwingLow(bar_index); + mConditions.isXOBDSwingHigh = XOBDIsSwingHigh(bar_index); + + // + // XCHLH ... + // + mConditions.isXCHLHSameHHs = XCHLHIsSameHHs(bar_index); + mConditions.isXCHLHSameLLs = XCHLHIsSameLLs(bar_index); + // + mConditions.isXCHLHSCMCHHSame = XCHLHIsMCSCHasSameHH(bar_index); + mConditions.isXCHLHSCMCLLSame = XCHLHIsMCSCHasSameLL(bar_index); + // + mConditions.isXCHLHSCLCHHSame = XCHLHIsLCSCHasSameHH(bar_index); + mConditions.isXCHLHSCLCLLSame = XCHLHIsLCSCHasSameLL(bar_index); + // + mConditions.isXCHLHMCLCHHSame = XCHLHIsLCMCHasSameHH(bar_index); + mConditions.isXCHLHMCLCLLSame = XCHLHIsLCMCHasSameLL(bar_index); + // + mConditions.isXCHLHMCOnTopOfLC = XCHLHIsMCOnTopOfLC(bar_index); + mConditions.isXCHLHMCInBottomOfLC = XCHLHIsMCInBottomOfLC(bar_index); + + // + // XCHMA ... + // + mConditions.isXCHMASCOverMax = XCHMAIsSCOverMax(bar_index); + mConditions.isXCHMASCOverMin = XCHMAIsSCOverMin(bar_index); + mConditions.isXCHMASCUnderMax = XCHMAIsSCUnderMax(bar_index); + mConditions.isXCHMASCUnderMin = XCHMAIsSCUnderMin(bar_index); + // + mConditions.isXCHMASCCrossedOverMax = XCHMAIsSCCrossedOverMax(bar_index); + mConditions.isXCHMASCCrossedUnderMax = XCHMAIsSCCrossedUnderMax(bar_index); + mConditions.isXCHMASCCrossedOverMin = XCHMAIsSCCrossedOverMin(bar_index); + mConditions.isXCHMASCCrossedUnderMin = XCHMAIsSCCrossedUnderMin(bar_index); + // + mConditions.isXCHMASCPeak = XCHMAIsSCPeak(bar_index); + mConditions.isXCHMASCVale = XCHMAIsSCVale(bar_index); + mConditions.isXCHMASCTrendsUp = XCHMAIsSCTrendsUp(bar_index); + mConditions.isXCHMASCTrendsDown = XCHMAIsSCTrendsDown(bar_index); + mConditions.isXCHMASCFastOverSlow = XCHMAIsSCFastOverSlow(bar_index); + mConditions.isXCHMASCFastUnderSlow = XCHMAIsSCFastUnderSlow(bar_index); + mConditions.isXCHMASCFastCrossedOverSlow = XCHMAIsSCFastCrossedOverSlow(bar_index); + mConditions.isXCHMASCFastCrossedUnderSlow = XCHMAIsSCFastCrossedUnderSlow(bar_index); + // + mConditions.isXCHMAMCPeak = XCHMAIsMCPeak(bar_index); + mConditions.isXCHMAMCVale = XCHMAIsMCVale(bar_index); + mConditions.isXCHMAMCTrendsUp = XCHMAIsMCTrendsUp(bar_index); + mConditions.isXCHMAMCTrendsDown = XCHMAIsMCTrendsDown(bar_index); + mConditions.isXCHMAMCFastOverSlow = XCHMAIsMCFastOverSlow(bar_index); + mConditions.isXCHMAMCFastUnderSlow = XCHMAIsMCFastUnderSlow(bar_index); + mConditions.isXCHMAMCFastCrossedOverSlow = XCHMAIsMCFastCrossedOverSlow(bar_index); + mConditions.isXCHMAMCFastCrossedUnderSlow = XCHMAIsMCFastCrossedUnderSlow(bar_index); + // + mConditions.isXCHMALCPeak = XCHMAIsLCPeak(bar_index); + mConditions.isXCHMALCVale = XCHMAIsLCVale(bar_index); + mConditions.isXCHMALCTrendsUp = XCHMAIsLCTrendsUp(bar_index); + mConditions.isXCHMALCTrendsDown = XCHMAIsLCTrendsDown(bar_index); + mConditions.isXCHMALCFastOverSlow = XCHMAIsLCFastOverSlow(bar_index); + mConditions.isXCHMALCFastUnderSlow = XCHMAIsLCFastUnderSlow(bar_index); + mConditions.isXCHMALCFastCrossedOverSlow = XCHMAIsLCFastCrossedOverSlow(bar_index); + mConditions.isXCHMALCFastCrossedUnderSlow = XCHMAIsLCFastCrossedUnderSlow(bar_index); + + // + return mConditions; + } + + // + // Access Last Readed Market Conditions ... + XMarketConditions GetLastMarketCondition() + { + // + XMarketConditions result = {}; + + // + result = mXConditions; + + // + return result; + } + + // + // Check Market Conditions is Ready for Long Signals or not ... + bool IsReadyForLong( + bool checkXCHMAMin = true, // Force Check XCHMA Min State + bool checkXCHMAMax = true, // Force Check XCHMA Max State + bool checkXCHMACycles = true, // Force Check XCHMA Cycles State + bool checkXCHMAPeaks = true, // Force Check XCHMA Peaks State + bool checkXCHMATrendPowers = true, // Force Check XCHMA Trend Powers + bool checkXOBD = true, // Force Check XOBD State + bool checkXTS = true // Force Check XTS State + ) + { + // + bool result = true; + + // + if (checkXCHMAMin) + { + // + result = + // + // XCHMA MIN ... + !( + // + (mXConditions.isXCHMASCOverMin || + mXConditions.isXCHMASCCrossedOverMin) && + (mXConditions.isXCHMASCUnderMin || + mXConditions.isXCHMASCCrossedUnderMin) + // + ); + } + + // + if (checkXCHMAMax && result) + { + // + result = + // + // XCHMA MAX ... + !( + // + (mXConditions.isXCHMASCOverMax || + mXConditions.isXCHMASCCrossedOverMax) && + (mXConditions.isXCHMASCUnderMax || + mXConditions.isXCHMASCCrossedUnderMax) + // + ) + // + ; + } + + // + if (checkXCHMACycles && result) + { + // + result = + // + // Check XCHMA Trend Bullish ... + ( + // + // All Cycles Bullish ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastOverSlow || + mXConditions.isXCHMASCFastCrossedOverSlow) + // + && + // + // MC ... + (mXConditions.isXCHMAMCFastOverSlow || + mXConditions.isXCHMAMCFastCrossedOverSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastOverSlow || + mXConditions.isXCHMALCFastCrossedOverSlow) + // + ) + // + || + // + // Two Cycle Fully Bullish ... + ( + // + // SC and MC ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastOverSlow || + mXConditions.isXCHMASCFastCrossedOverSlow) + // + && + // + // MC ... + (mXConditions.isXCHMAMCFastOverSlow || + mXConditions.isXCHMAMCFastCrossedOverSlow) + // + ) + // + || + // + // SC and LC ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastOverSlow || + mXConditions.isXCHMASCFastCrossedOverSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastOverSlow || + mXConditions.isXCHMALCFastCrossedOverSlow) + // + ) + // + || + // + // MC and LC ... + ( + // + // MC ... + (mXConditions.isXCHMAMCFastOverSlow || + mXConditions.isXCHMAMCFastCrossedOverSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastOverSlow || + mXConditions.isXCHMALCFastCrossedOverSlow) + // + ) + // + ) + // + ) + // + ; + } + + // + if (checkXCHMAPeaks && result) + { + // + result = + // + // XCHMA Check Peaks ... + !( + // + // All Cycles Peak ... + (mXConditions.isXCHMASCPeak && + mXConditions.isXCHMAMCPeak && + mXConditions.isXCHMALCPeak) + // + || + // + ( + // + // SC MC ... + (mXConditions.isXCHMASCPeak && + mXConditions.isXCHMAMCPeak) + // + || + // + // SC LC ... + (mXConditions.isXCHMASCPeak && + mXConditions.isXCHMALCPeak) + // + || + // + // MC LC ... + (mXConditions.isXCHMAMCPeak && + mXConditions.isXCHMALCPeak) + // + ) + // + ) + // + ; + } + + // + if (checkXCHMATrendPowers && result) + { + // + result = + // + // XCHMA Check Trends Power ... + !( + // + // All Trends Down ... + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMAMCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + || + // + // Twisted pairs ... + ( + // + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMAMCTrendsDown) + // + || + // + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + || + // + (mXConditions.isXCHMAMCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + ) + // + ) + // + ; + } + + // + if (checkXOBD && result) + { + // + result = + // + // XOBD Check Swings ... + !mXConditions.isXOBDSwingLow + // + ; + } + + // + if (checkXTS && result) + { + result = + // + // XTS Check ... + !( + // + mXConditions.isXTSCurrentMin && + // + ( + // + // All Under ... + ( + (mXConditions.isXTSCurrentUnderNearest || + mXConditions.isXTSCurrentCrossedUnderNearest) && + (mXConditions.isXTSCurrentUnderMediest || + mXConditions.isXTSCurrentCrossedUnderMediest) && + (mXConditions.isXTSCurrentUnderFarest || + mXConditions.isXTSCurrentCrossedUnderFarest)) + // + || + // + // Pairs ... + ( + // + ((mXConditions.isXTSCurrentUnderNearest || + mXConditions.isXTSCurrentCrossedUnderNearest) && + (mXConditions.isXTSCurrentUnderMediest || + mXConditions.isXTSCurrentCrossedUnderMediest)) + // + || + // + ((mXConditions.isXTSCurrentUnderNearest || + mXConditions.isXTSCurrentCrossedUnderNearest) && + (mXConditions.isXTSCurrentUnderFarest || + mXConditions.isXTSCurrentCrossedUnderFarest)) + // + || + // + ((mXConditions.isXTSCurrentUnderMediest || + mXConditions.isXTSCurrentCrossedUnderMediest) && + (mXConditions.isXTSCurrentUnderFarest || + mXConditions.isXTSCurrentCrossedUnderFarest)) + // + ) + // + ) + // + ) + // + ; + } + + // + return result; + } + + // + // Check Market Conditions is Ready for Short Signals or not ... + bool IsReadyForShort( + bool checkXCHMAMin = true, // Force Check XCHMA Min State + bool checkXCHMAMax = true, // Force Check XCHMA Max State + bool checkXCHMACycles = true, // Force Check XCHMA Cycles State + bool checkXCHMAVales = true, // Force Check XCHMA Vales State + bool checkXCHMATrendPowers = true, // Force Check XCHMA Trend Powers + bool checkXOBD = true, // Force Check XOBD State + bool checkXTS = true // Force Check XTS State + ) + { + // + bool result = true; + + // + if (checkXCHMAMin) + { + // + result = + // + // XCHMA MIN ... + !( + // + (mXConditions.isXCHMASCOverMin || + mXConditions.isXCHMASCCrossedOverMin) && + (mXConditions.isXCHMASCUnderMin || + mXConditions.isXCHMASCCrossedUnderMin) + // + ); + } + + // + if (checkXCHMAMax && result) + { + // + result = + // + // XCHMA MAX ... + !( + // + (mXConditions.isXCHMASCOverMax || + mXConditions.isXCHMASCCrossedOverMax) && + (mXConditions.isXCHMASCUnderMax || + mXConditions.isXCHMASCCrossedUnderMax) + // + ) + // + ; + } + + // + if (checkXCHMACycles && result) + { + // + result = + // + // Check XCHMA Trend Bullish ... + ( + // + // All Cycles Bullish ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastUnderSlow || + mXConditions.isXCHMASCFastCrossedUnderSlow) + // + && + // + // MC ... + (mXConditions.isXCHMAMCFastUnderSlow || + mXConditions.isXCHMAMCFastCrossedUnderSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastUnderSlow || + mXConditions.isXCHMALCFastCrossedUnderSlow) + // + ) + // + || + // + // Two Cycle Fully Bullish ... + ( + // + // SC and MC ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastUnderSlow || + mXConditions.isXCHMASCFastCrossedOverSlow) + // + && + // + // MC ... + (mXConditions.isXCHMAMCFastUnderSlow || + mXConditions.isXCHMAMCFastCrossedOverSlow) + // + ) + // + || + // + // SC and LC ... + ( + // + // SC ... + (mXConditions.isXCHMASCFastUnderSlow || + mXConditions.isXCHMASCFastCrossedUnderSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastUnderSlow || + mXConditions.isXCHMALCFastCrossedUnderSlow) + // + ) + // + || + // + // MC and LC ... + ( + // + // MC ... + (mXConditions.isXCHMAMCFastUnderSlow || + mXConditions.isXCHMAMCFastCrossedOverSlow) + // + && + // + // LC ... + (mXConditions.isXCHMALCFastUnderSlow || + mXConditions.isXCHMALCFastCrossedOverSlow) + // + ) + // + ) + // + ) + // + ; + } + + // + if (checkXCHMAVales && result) + { + // + result = + // + // XCHMA Check Vales ... + !( + // + // All Cycles Vale ... + (mXConditions.isXCHMASCVale && + mXConditions.isXCHMAMCVale && + mXConditions.isXCHMALCVale) + // + || + // + ( + // + // SC MC ... + (mXConditions.isXCHMASCVale && + mXConditions.isXCHMAMCVale) + // + || + // + // SC LC ... + (mXConditions.isXCHMASCVale && + mXConditions.isXCHMALCVale) + // + || + // + // MC LC ... + (mXConditions.isXCHMAMCVale && + mXConditions.isXCHMALCVale) + // + ) + // + ) + // + ; + } + + // + if (checkXCHMATrendPowers && result) + { + // + result = + // + // XCHMA Check Trends Power ... + !( + // + // All Trends Down ... + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMAMCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + || + // + // Twisted pairs ... + ( + // + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMAMCTrendsDown) + // + || + // + (mXConditions.isXCHMASCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + || + // + (mXConditions.isXCHMAMCTrendsDown && + mXConditions.isXCHMALCTrendsDown) + // + ) + // + ) + // + ; + } + + // + if (checkXOBD && result) + { + // + result = + // + // XOBD Check Swings ... + !mXConditions.isXOBDSwingHigh + // + ; + } + + // + if (checkXTS && result) + { + // + result = + // + // XTS Check ... + !( + // + mXConditions.isXTSCurrentMax && + // + ( + // + // All Over ... + ( + (mXConditions.isXTSCurrentOverNearest || + mXConditions.isXTSCurrentCrossedOverNearest) && + (mXConditions.isXTSCurrentOverMediest || + mXConditions.isXTSCurrentCrossedOverMediest) && + (mXConditions.isXTSCurrentOverFarest || + mXConditions.isXTSCurrentCrossedOverFarest)) + // + || + // + // Pairs ... + ( + // + ((mXConditions.isXTSCurrentOverNearest || + mXConditions.isXTSCurrentCrossedOverNearest) && + (mXConditions.isXTSCurrentOverMediest || + mXConditions.isXTSCurrentCrossedOverMediest)) + // + || + // + ((mXConditions.isXTSCurrentOverNearest || + mXConditions.isXTSCurrentCrossedOverNearest) && + (mXConditions.isXTSCurrentOverFarest || + mXConditions.isXTSCurrentCrossedOverFarest)) + // + || + // + ((mXConditions.isXTSCurrentOverMediest || + mXConditions.isXTSCurrentCrossedOverMediest) && + (mXConditions.isXTSCurrentOverFarest || + mXConditions.isXTSCurrentCrossedOverFarest)) + // + ) + // + ) + // + ) + // + ; + } + + // + return result; + } + + // + // Converts Market Conditions to Specific String Representation ... + string GenerateConditionsString( + XMarketConditions &condition, // Specify Conditiond + string separator = "\n", // Specify Separator + bool ignoreFalses = true // Ignore False Conditions + ) + { + // + XMarketConditions mConditions = {}; + + // + mConditions = condition; + + // + string result = "\n"; + + // + // XOBD ... + result += + "| XOBD |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXOBDSwingLow)) + { + result += "isXOBDSwingLow: " + (string)mConditions.isXOBDSwingLow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXOBDSwingHigh)) + { + result += "isXOBDSwingHigh: " + (string)mConditions.isXOBDSwingHigh + separator; + } + + // + // Separator ... + result += separator; + + // + // XTM ... + result += + "| XTM |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMPeak)) + { + result += "isXTMPeak: " + (string)mConditions.isXTMPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMVale)) + { + result += "isXTMVale: " + (string)mConditions.isXTMVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMStartBullish)) + { + result += "isXTMStartBullish: " + (string)mConditions.isXTMStartBullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMStartBullishAfterNeutural)) + { + result += "isXTMStartBullishAfterNeutural: " + (string)mConditions.isXTMStartBullishAfterNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMBullish)) + { + result += "isXTMBullish: " + (string)mConditions.isXTMBullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMEndBullish)) + { + result += "isXTMEndBullish: " + (string)mConditions.isXTMEndBullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMEndBullishByNeutural)) + { + result += "isXTMEndBullishByNeutural: " + (string)mConditions.isXTMEndBullishByNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMStartBearish)) + { + result += "isXTMStartBearish: " + (string)mConditions.isXTMStartBearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMStartBearishAfterNeutural)) + { + result += "isXTMStartBearishAfterNeutural: " + (string)mConditions.isXTMStartBearishAfterNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMBearish)) + { + result += "isXTMBearish: " + (string)mConditions.isXTMBearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMEndBearish)) + { + result += "isXTMEndBearish: " + (string)mConditions.isXTMEndBearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMEndBearishByNeutural)) + { + result += "isXTMEndBearishByNeutural: " + (string)mConditions.isXTMEndBearishByNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTMNeutural)) + { + result += "isXTMNeutural: " + (string)mConditions.isXTMNeutural + separator; + } + + // + // Separator ... + result += separator; + + // + // XAMA ... + result += + "| XAMA |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAPeak)) + { + result += "isXAMAPeak: " + (string)mConditions.isXAMAPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAVale)) + { + result += "isXAMAVale: " + (string)mConditions.isXAMAVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAStartBullish)) + { + result += "isXAMAStartBullish: " + (string)mConditions.isXAMAStartBullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAStartBullishAfterNeutural)) + { + result += "isXAMAStartBullishAfterNeutural: " + (string)mConditions.isXAMAStartBullishAfterNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMABullish)) + { + result += "isXAMABullish: " + (string)mConditions.isXAMABullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAEndBullish)) + { + result += "isXAMAEndBullish: " + (string)mConditions.isXAMAEndBullish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAEndBullishByNeutural)) + { + result += "isXAMAEndBullishByNeutural: " + (string)mConditions.isXAMAEndBullishByNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAStartBearish)) + { + result += "isXAMAStartBearish: " + (string)mConditions.isXAMAStartBearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAStartBearishAfterNeutural)) + { + result += "isXAMAStartBearishAfterNeutural: " + (string)mConditions.isXAMAStartBearishAfterNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMABearish)) + { + result += "isXAMABearish: " + (string)mConditions.isXAMABearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAEndBearish)) + { + result += "isXAMAEndBearish: " + (string)mConditions.isXAMAEndBearish + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMAEndBearishByNeutural)) + { + result += "isXAMAEndBearishByNeutural: " + (string)mConditions.isXAMAEndBearishByNeutural + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXAMANeutural)) + { + result += "isXAMANeutural: " + (string)mConditions.isXAMANeutural + separator; + } + + // + // Separator ... + result += separator; + + // + // XTD ... + result += + "| XTD |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalPeak)) + { + result += "isXTDSignalPeak: " + (string)mConditions.isXTDSignalPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalVale)) + { + result += "isXTDSignalVale: " + (string)mConditions.isXTDSignalVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullishPeak)) + { + result += "isXTDBullishPeak: " + (string)mConditions.isXTDBullishPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullishVale)) + { + result += "isXTDBullishVale: " + (string)mConditions.isXTDBullishVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBearishPeak)) + { + result += "isXTDBearishPeak: " + (string)mConditions.isXTDBearishPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBearishVale)) + { + result += "isXTDBearishVale: " + (string)mConditions.isXTDBearishVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullOverBear)) + { + result += "isXTDBullOverBear: " + (string)mConditions.isXTDBullOverBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullUnderBear)) + { + result += "isXTDBullUnderBear: " + (string)mConditions.isXTDBullUnderBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalOverBear)) + { + result += "isXTDSignalOverBear: " + (string)mConditions.isXTDSignalOverBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalUnderBear)) + { + result += "isXTDSignalUnderBear: " + (string)mConditions.isXTDSignalUnderBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullCrossedOverBear)) + { + result += "isXTDBullCrossedOverBear: " + (string)mConditions.isXTDBullCrossedOverBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDBullCrossedUnderBear)) + { + result += "isXTDBullCrossedUnderBear: " + (string)mConditions.isXTDBullCrossedUnderBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalCrossedOverBear)) + { + result += "isXTDSignalCrossedOverBear: " + (string)mConditions.isXTDSignalCrossedOverBear + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTDSignalCrossedUnderBear)) + { + result += "isXTDSignalCrossedUnderBear: " + (string)mConditions.isXTDSignalCrossedUnderBear + separator; + } + + // + // Separator ... + result += separator; + + // + // XFI ... + result += + "| XFI |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFIPeak)) + { + result += "isXFIPeak: " + (string)mConditions.isXFIPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFIVale)) + { + result += "isXFIVale: " + (string)mConditions.isXFIVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFIOverZero)) + { + result += "isXFIOverZero: " + (string)mConditions.isXFIOverZero + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFIUnderZero)) + { + result += "isXFIUnderZero: " + (string)mConditions.isXFIUnderZero + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFICrossedOverZero)) + { + result += "isXFICrossedOverZero: " + (string)mConditions.isXFICrossedOverZero + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXFICrossedUnderZero)) + { + result += "isXFICrossedUnderZero: " + (string)mConditions.isXFICrossedUnderZero + separator; + } + + // + // Separator ... + result += separator; + + // + // XTS ... + result += + "| XTS |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSAllSame)) + { + result += "isXTSAllSame: " + (string)mConditions.isXTSAllSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentMin)) + { + result += "isXTSCurrentMin: " + (string)mConditions.isXTSCurrentMin + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentMax)) + { + result += "isXTSCurrentMax: " + (string)mConditions.isXTSCurrentMax + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentOverFarest)) + { + result += "isXTSCurrentOverFarest: " + (string)mConditions.isXTSCurrentOverFarest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentOverNearest)) + { + result += "isXTSCurrentOverNearest: " + (string)mConditions.isXTSCurrentOverNearest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentOverMediest)) + { + result += "isXTSCurrentOverMediest: " + (string)mConditions.isXTSCurrentOverMediest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentUnderFarest)) + { + result += "isXTSCurrentUnderFarest: " + (string)mConditions.isXTSCurrentUnderFarest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentUnderNearest)) + { + result += "isXTSCurrentUnderNearest: " + (string)mConditions.isXTSCurrentUnderNearest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentUnderMediest)) + { + result += "isXTSCurrentUnderMediest: " + (string)mConditions.isXTSCurrentUnderMediest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedOverFarest)) + { + result += "isXTSCurrentCrossedOverFarest: " + (string)mConditions.isXTSCurrentCrossedOverFarest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedOverNearest)) + { + result += "isXTSCurrentCrossedOverNearest: " + (string)mConditions.isXTSCurrentCrossedOverNearest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedOverMediest)) + { + result += "isXTSCurrentCrossedOverMediest: " + (string)mConditions.isXTSCurrentCrossedOverMediest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedUnderFarest)) + { + result += "isXTSCurrentCrossedUnderFarest: " + (string)mConditions.isXTSCurrentCrossedUnderFarest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedUnderNearest)) + { + result += "isXTSCurrentCrossedUnderNearest: " + (string)mConditions.isXTSCurrentCrossedUnderNearest + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXTSCurrentCrossedUnderMediest)) + { + result += "isXTSCurrentCrossedUnderMediest: " + (string)mConditions.isXTSCurrentCrossedUnderMediest + separator; + } + + // + // Separator ... + result += separator; + + // + // XLH ... + result += + "| XLH |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHHHIncreased)) + { + result += "isXLHHHIncreased: " + (string)mConditions.isXLHHHIncreased + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHHHDecreased)) + { + result += "isXLHHHDecreased: " + (string)mConditions.isXLHHHDecreased + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHLLIncreased)) + { + result += "isXLHLLIncreased: " + (string)mConditions.isXLHLLIncreased + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHLLDecreased)) + { + result += "isXLHLLDecreased: " + (string)mConditions.isXLHLLDecreased + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHHighAttachedHH)) + { + result += "isXLHHighAttachedHH: " + (string)mConditions.isXLHHighAttachedHH + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHLowAttachedLL)) + { + result += "isXLHLowAttachedLL: " + (string)mConditions.isXLHLowAttachedLL + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHHHSameInLength)) + { + result += "isXLHHHSameInLength: " + (string)mConditions.isXLHHHSameInLength + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHLLSameInLength)) + { + result += "isXLHLLSameInLength: " + (string)mConditions.isXLHLLSameInLength + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHPriceCrossedOverSignal)) + { + result += "isXLHPriceCrossedOverSignal: " + (string)mConditions.isXLHPriceCrossedOverSignal + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHPriceOverSignal)) + { + result += "isXLHPriceOverSignal: " + (string)mConditions.isXLHPriceOverSignal + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHPriceCrossedUnderSignal)) + { + result += "isXLHPriceCrossedUnderSignal: " + (string)mConditions.isXLHPriceCrossedUnderSignal + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHPriceUnderSignal)) + { + result += "isXLHPriceUnderSignal: " + (string)mConditions.isXLHPriceUnderSignal + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXLHPriceInSignalRange)) + { + result += "isXLHPriceInSignalRange: " + (string)mConditions.isXLHPriceInSignalRange + separator; + } + + // + // Separator ... + result += separator; + + // + // XRSI ... + result += + "| XRSI |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSIPeak)) + { + result += "isXRSIPeak: " + (string)mConditions.isXRSIPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSIVale)) + { + result += "isXRSIVale: " + (string)mConditions.isXRSIVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSICrossedOverLongExit)) + { + result += "isXRSICrossedOverLongExit: " + (string)mConditions.isXRSICrossedOverLongExit + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSICrossedOverLongEntry)) + { + result += "isXRSICrossedOverLongEntry: " + (string)mConditions.isXRSICrossedOverLongEntry + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSICrossedUnderShortExit)) + { + result += "isXRSICrossedUnderShortExit: " + (string)mConditions.isXRSICrossedUnderShortExit + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXRSICrossedUnderShortEntry)) + { + result += "isXRSICrossedUnderShortEntry: " + (string)mConditions.isXRSICrossedUnderShortEntry + separator; + } + + // + // Separator ... + result += separator; + + // + // XCHLH ... + result += + "| XCHLH |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSameHHs)) + { + result += "isXCHLHSameHHs: " + (string)mConditions.isXCHLHSameHHs + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSameLLs)) + { + result += "isXCHLHSameLLs: " + (string)mConditions.isXCHLHSameLLs + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSCMCHHSame)) + { + result += "isXCHLHSCMCHHSame: " + (string)mConditions.isXCHLHSCMCHHSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSCMCLLSame)) + { + result += "isXCHLHSCMCLLSame: " + (string)mConditions.isXCHLHSCMCLLSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSCLCHHSame)) + { + result += "isXCHLHSCLCHHSame: " + (string)mConditions.isXCHLHSCLCHHSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHSCLCLLSame)) + { + result += "isXCHLHSCLCLLSame: " + (string)mConditions.isXCHLHSCLCLLSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHMCLCHHSame)) + { + result += "isXCHLHMCLCHHSame: " + (string)mConditions.isXCHLHMCLCHHSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHMCLCLLSame)) + { + result += "isXCHLHMCLCLLSame: " + (string)mConditions.isXCHLHMCLCLLSame + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHMCOnTopOfLC)) + { + result += "isXCHLHMCOnTopOfLC: " + (string)mConditions.isXCHLHMCOnTopOfLC + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHLHMCInBottomOfLC)) + { + result += "isXCHLHMCInBottomOfLC: " + (string)mConditions.isXCHLHMCInBottomOfLC + separator; + } + + // + // Separator ... + result += separator; + + // + // XCHMA ... + result += + "| XCHMA |" + separator; + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCOverMax)) + { + result += "isXCHMASCOverMax: " + (string)mConditions.isXCHMASCOverMax + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCOverMin)) + { + result += "isXCHMASCOverMin: " + (string)mConditions.isXCHMASCOverMin + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCUnderMax)) + { + result += "isXCHMASCUnderMax: " + (string)mConditions.isXCHMASCUnderMax + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCUnderMin)) + { + result += "isXCHMASCUnderMin: " + (string)mConditions.isXCHMASCUnderMin + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCCrossedOverMax)) + { + result += "isXCHMASCCrossedOverMax: " + (string)mConditions.isXCHMASCCrossedOverMax + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCCrossedUnderMax)) + { + result += "isXCHMASCCrossedUnderMax: " + (string)mConditions.isXCHMASCCrossedUnderMax + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCCrossedOverMin)) + { + result += "isXCHMASCCrossedOverMin: " + (string)mConditions.isXCHMASCCrossedOverMin + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCCrossedUnderMin)) + { + result += "isXCHMASCCrossedUnderMin: " + (string)mConditions.isXCHMASCCrossedUnderMin + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCPeak)) + { + result += "isXCHMASCPeak: " + (string)mConditions.isXCHMASCPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCVale)) + { + result += "isXCHMASCVale: " + (string)mConditions.isXCHMASCVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCTrendsUp)) + { + result += "isXCHMASCTrendsUp: " + (string)mConditions.isXCHMASCTrendsUp + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCTrendsDown)) + { + result += "isXCHMASCTrendsDown: " + (string)mConditions.isXCHMASCTrendsDown + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCFastOverSlow)) + { + result += "isXCHMASCFastOverSlow: " + (string)mConditions.isXCHMASCFastOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCFastUnderSlow)) + { + result += "isXCHMASCFastUnderSlow: " + (string)mConditions.isXCHMASCFastUnderSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCFastCrossedOverSlow)) + { + result += "isXCHMASCFastCrossedOverSlow: " + (string)mConditions.isXCHMASCFastCrossedOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMASCFastCrossedUnderSlow)) + { + result += "isXCHMASCFastCrossedUnderSlow: " + (string)mConditions.isXCHMASCFastCrossedUnderSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCPeak)) + { + result += "isXCHMAMCPeak: " + (string)mConditions.isXCHMAMCPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCVale)) + { + result += "isXCHMAMCVale: " + (string)mConditions.isXCHMAMCVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCTrendsUp)) + { + result += "isXCHMAMCTrendsUp: " + (string)mConditions.isXCHMAMCTrendsUp + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCTrendsDown)) + { + result += "isXCHMAMCTrendsDown: " + (string)mConditions.isXCHMAMCTrendsDown + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCFastOverSlow)) + { + result += "isXCHMAMCFastOverSlow: " + (string)mConditions.isXCHMAMCFastOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCFastUnderSlow)) + { + result += "isXCHMAMCFastUnderSlow: " + (string)mConditions.isXCHMAMCFastUnderSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCFastCrossedOverSlow)) + { + result += "isXCHMAMCFastCrossedOverSlow: " + (string)mConditions.isXCHMAMCFastCrossedOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMAMCFastCrossedUnderSlow)) + { + result += "isXCHMAMCFastCrossedUnderSlow: " + (string)mConditions.isXCHMAMCFastCrossedUnderSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCPeak)) + { + result += "isXCHMALCPeak: " + (string)mConditions.isXCHMALCPeak + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCVale)) + { + result += "isXCHMALCVale: " + (string)mConditions.isXCHMALCVale + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCTrendsUp)) + { + result += "isXCHMALCTrendsUp: " + (string)mConditions.isXCHMALCTrendsUp + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCTrendsDown)) + { + result += "isXCHMALCTrendsDown: " + (string)mConditions.isXCHMALCTrendsDown + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCFastOverSlow)) + { + result += "isXCHMALCFastOverSlow: " + (string)mConditions.isXCHMALCFastOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCFastUnderSlow)) + { + result += "isXCHMALCFastUnderSlow: " + (string)mConditions.isXCHMALCFastUnderSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCFastCrossedOverSlow)) + { + result += "isXCHMALCFastCrossedOverSlow: " + (string)mConditions.isXCHMALCFastCrossedOverSlow + separator; + } + + // + if ( + !ignoreFalses || + (ignoreFalses && mConditions.isXCHMALCFastCrossedUnderSlow)) + { + result += "isXCHMALCFastCrossedUnderSlow: " + (string)mConditions.isXCHMALCFastCrossedUnderSlow + separator; + } + + // + // Separator ... + result += separator; + + // + return result; + } + + // + // END Common Functions ... + // + + // + // START Actions Based On Signallers ... + // + + // + // START XTD Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXTDignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXTDEnableSignaller) + { + return result; + } + + // + result = true; + mXTDEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXTDSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXTDEnableSignaller) + { + return result; + } + + // + result = true; + mXTDEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXTDLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + mXTDAllowLongSignals) + { + return result; + } + + // + result = true; + mXTDAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXTDLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + !mXTDAllowLongSignals) + { + return result; + } + + // + result = true; + mXTDAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXTDShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + mXTDAllowShortSignals) + { + return result; + } + + // + result = true; + mXTDAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXTDShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + !mXTDAllowShortSignals) + { + return result; + } + + // + result = true; + mXTDAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XTDHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + !mXTDAllowLongSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXTDSignalCrossedOverBear + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong() + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XTDHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTDEnableSignaller || + !mXTDAllowShortSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXTDSignalCrossedUnderBear + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort() + // + ) + // + ; + + // + return result; + } + + // + // END XTD Signaller ... + // + + // + // START XTAM Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXTAMignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXTAMEnableSignaller) + { + return result; + } + + // + result = true; + mXTAMEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXTAMSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXTAMEnableSignaller) + { + return result; + } + + // + result = true; + mXTAMEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXTAMLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + mXTAMAllowLongSignals) + { + return result; + } + + // + result = true; + mXTAMAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXTAMLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + !mXTAMAllowLongSignals) + { + return result; + } + + // + result = true; + mXTAMAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXTAMShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + mXTAMAllowShortSignals) + { + return result; + } + + // + result = true; + mXTAMAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXTAMShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + !mXTAMAllowShortSignals) + { + return result; + } + + // + result = true; + mXTAMAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XTAMHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + !mXTAMAllowLongSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + (xAMAMaBuffer[1] > xTMMaBuffer[1] && + xAMAMaBuffer[2] > xTMMaBuffer[2]) + // + && + // + !(xAMAMaBuffer[2] > xTMMaBuffer[2] && + xAMAMaBuffer[3] > xTMMaBuffer[3]) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong() + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XTAMHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTAMEnableSignaller || + !mXTAMAllowShortSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + (xAMAMaBuffer[1] < xTMMaBuffer[1] && + xAMAMaBuffer[2] < xTMMaBuffer[2]) + // + && + // + !(xAMAMaBuffer[2] < xTMMaBuffer[2] && + xAMAMaBuffer[3] < xTMMaBuffer[3]) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort() + // + ) + // + ; + + // + return result; + } + + // + // END XTAM Signaller ... + // + + // + // START XSI Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXSIignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXSIEnableSignaller) + { + return result; + } + + // + result = true; + mXSIEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXSISignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXSIEnableSignaller) + { + return result; + } + + // + result = true; + mXSIEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXSILongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + mXSIAllowLongSignals) + { + return result; + } + + // + result = true; + mXSIAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXSILongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + !mXSIAllowLongSignals) + { + return result; + } + + // + result = true; + mXSIAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXSIShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + mXSIAllowShortSignals) + { + return result; + } + + // + result = true; + mXSIAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXSIShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + !mXSIAllowShortSignals) + { + return result; + } + + // + result = true; + mXSIAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XSIHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + !mXSIAllowLongSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXRSICrossedOverLongEntry && + xRSIBuffer[3] < xRSILongEntryValue + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong( + true, // XCHMA Min + true, // XCHMA Max + true, // XCHMA Cycles + true, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XSIHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXSIEnableSignaller || + !mXSIAllowShortSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXRSICrossedUnderShortEntry && + xRSIBuffer[3] > xRSIShortEntryValue + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort( + true, // XCHMA Min + true, // XCHMA Max + true, // XCHMA Cycles + true, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // END XSI Signaller ... + // + + // + // START XTSFI Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXTSFIignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXTSFIEnableSignaller) + { + return result; + } + + // + result = true; + mXTSFIEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXTSFISignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXTSFIEnableSignaller) + { + return result; + } + + // + result = true; + mXTSFIEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXTSFILongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + mXTSFIAllowLongSignals) + { + return result; + } + + // + result = true; + mXTSFIAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXTSFILongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + !mXTSFIAllowLongSignals) + { + return result; + } + + // + result = true; + mXTSFIAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXTSFIShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + mXTSFIAllowShortSignals) + { + return result; + } + + // + result = true; + mXTSFIAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXTSFIShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + !mXTSFIAllowShortSignals) + { + return result; + } + + // + result = true; + mXTSFIAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XTSFIHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + !mXTSFIAllowLongSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + XTSGetMinValue(1) == xTSFarestBuffer[1] && + (mXConditions.isXTSCurrentOverFarest || + mXConditions.isXTSCurrentCrossedOverFarest) && + (xTSCurrentBuffer[1] < xTSNearestBuffer[1] || + xTSCurrentBuffer[1] < xTSMediestBuffer[1]) && + !(mXConditions.isXTSCurrentUnderNearest || + mXConditions.isXTSCurrentCrossedUnderNearest) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong() + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XTSFIHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXTSFIEnableSignaller || + !mXTSFIAllowShortSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + XTSGetMaxValue(1) == xTSFarestBuffer[1] && + (mXConditions.isXTSCurrentUnderFarest || + mXConditions.isXTSCurrentCrossedUnderFarest) && + (xTSCurrentBuffer[1] > xTSNearestBuffer[1] || + xTSCurrentBuffer[1] > xTSMediestBuffer[1]) && + !(mXConditions.isXTSCurrentOverNearest || + mXConditions.isXTSCurrentCrossedOverNearest) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort() + // + ) + // + ; + + // + return result; + } + + // + // END XTSFI Signaller ... + // + + // + // START XOBDLH Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXOBDLHignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXOBDLHEnableSignaller) + { + return result; + } + + // + result = true; + mXOBDLHEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXOBDLHSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXOBDLHEnableSignaller) + { + return result; + } + + // + result = true; + mXOBDLHEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXOBDLHLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + mXOBDLHAllowLongSignals) + { + return result; + } + + // + result = true; + mXOBDLHAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXOBDLHLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + !mXOBDLHAllowLongSignals) + { + return result; + } + + // + result = true; + mXOBDLHAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXOBDLHShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + mXOBDLHAllowShortSignals) + { + return result; + } + + // + result = true; + mXOBDLHAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXOBDLHShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + !mXOBDLHAllowShortSignals) + { + return result; + } + + // + result = true; + mXOBDLHAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XOBDLHHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + !mXOBDLHAllowLongSignals) + { + return result; + } + + // + XMarketConditions xConditions2 = GenerateMarketConditions(2); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + xConditions2.isXOBDSwingLow && + xConditions2.isXLHLowAttachedLL && + xLHLLBuffer[1] >= xLHLLBuffer[2] + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + false, // XOBD + false // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XOBDLHHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXOBDLHEnableSignaller || + !mXOBDLHAllowShortSignals) + { + return result; + } + + // + XMarketConditions xConditions2 = GenerateMarketConditions(2); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + xConditions2.isXOBDSwingHigh && + xConditions2.isXLHHighAttachedHH && + xLHHHBuffer[1] <= xLHHHBuffer[2] + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + false, // XOBD + false // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // END XOBDLH Signaller ... + // + + // + // START XCHMACC Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXCHMACCignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXCHMACCEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMACCEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXCHMACCSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXCHMACCEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMACCEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXCHMACCLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + mXCHMACCAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMACCAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXCHMACCLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + !mXCHMACCAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMACCAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXCHMACCShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + mXCHMACCAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMACCAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXCHMACCShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + !mXCHMACCAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMACCAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XCHMACCHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + !mXCHMACCAllowLongSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + xCHMAScFastBuffer[1] > xCHMAScSlowBuffer[1] && + xCHMAMcFastBuffer[1] > xCHMAMcSlowBuffer[1] && + xCHMALcFastBuffer[1] > xCHMALcSlowBuffer[1] && + // + xCHMAScFastBuffer[2] > xCHMAScSlowBuffer[2] && + xCHMAMcFastBuffer[2] > xCHMAMcSlowBuffer[2] && + xCHMALcFastBuffer[2] > xCHMALcSlowBuffer[2] && + // + !( + // + xCHMAScFastBuffer[3] > xCHMAScSlowBuffer[3] && + xCHMAMcFastBuffer[3] > xCHMAMcSlowBuffer[3] && + xCHMALcFastBuffer[3] > xCHMALcSlowBuffer[3] + // + ) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong() + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XCHMACCHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMACCEnableSignaller || + !mXCHMACCAllowShortSignals) + { + return result; + } + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + xCHMAScFastBuffer[1] < xCHMAScSlowBuffer[1] && + xCHMAMcFastBuffer[1] < xCHMAMcSlowBuffer[1] && + xCHMALcFastBuffer[1] < xCHMALcSlowBuffer[1] && + // + xCHMAScFastBuffer[2] < xCHMAScSlowBuffer[2] && + xCHMAMcFastBuffer[2] < xCHMAMcSlowBuffer[2] && + xCHMALcFastBuffer[2] < xCHMALcSlowBuffer[2] && + // + !( + // + xCHMAScFastBuffer[3] < xCHMAScSlowBuffer[3] && + xCHMAMcFastBuffer[3] < xCHMAMcSlowBuffer[3] && + xCHMALcFastBuffer[3] < xCHMALcSlowBuffer[3] + // + ) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort() + // + ) + // + ; + + // + return result; + } + + // + // END XCHMACC Signaller ... + // + + // + // START XCHMAMX Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXCHMAMXignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXCHMAMXEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMAMXEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXCHMAMXSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXCHMAMXEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMAMXEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXCHMAMXLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + mXCHMAMXAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMAMXAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXCHMAMXLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + !mXCHMAMXAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMAMXAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXCHMAMXShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + mXCHMAMXAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMAMXAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXCHMAMXShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + !mXCHMAMXAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMAMXAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XCHMAMXHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + !mXCHMAMXAllowLongSignals) + { + return result; + } + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double xCHMANonSCMax2 = XCHMAGetCyclesMaxValue(2, cycles); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXCHMASCCrossedOverMax && + xCHMAScFastBuffer[2] < xCHMANonSCMax2 && + xCHMAScSlowBuffer[2] < xCHMANonSCMax2 && + MathAbs(xCHMANonSCMax2 - xCHMAScFastBuffer[2]) > MathAbs(xCHMAScFastBuffer[2] - xCHMAScSlowBuffer[2]) && + MathAbs(xCHMANonSCMax2 - xCHMAScSlowBuffer[2]) > MathAbs(xCHMAScFastBuffer[2] - xCHMAScSlowBuffer[2]) + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XCHMAMXHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMXEnableSignaller || + !mXCHMAMXAllowShortSignals) + { + return result; + } + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double xCHMANonSCMax2 = XCHMAGetCyclesMaxValue(2, cycles); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXCHMASCCrossedUnderMax && + xCHMAScFastBuffer[2] > xCHMANonSCMax2 && + xCHMAScSlowBuffer[2] > xCHMANonSCMax2 + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForShort( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + // + return result; + } + + // + // END XCHMAMX Signaller ... + // + + // + // START XCHMAMN Signaller ... + // + + // + // Enable Signaller ... + bool EnableSXCHMAMNignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (mXCHMAMNEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMAMNEnableSignaller = true; + + // + return result; + } + + // + // Disable Signaller ... + bool DisbaleXCHMAMNSignaller() + { + // + bool result = false; + + // + // Validate Args ... + if (!mXCHMAMNEnableSignaller) + { + return result; + } + + // + result = true; + mXCHMAMNEnableSignaller = false; + + // + return result; + } + + // + // Allow Sginaller to Issue Long Signals ... + bool EnableXCHMAMNLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + mXCHMAMNAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMAMNAllowLongSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Long Signals ... + bool DisbaleXCHMAMNLongs() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + !mXCHMAMNAllowLongSignals) + { + return result; + } + + // + result = true; + mXCHMAMNAllowLongSignals = false; + + // + return result; + } + + // + // Allow Signaller to Issue Short Sginals ... + bool EnableXCHMAMNShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + mXCHMAMNAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMAMNAllowShortSignals = true; + + // + return result; + } + + // + // Disallow Signaller to Issue Short Signals ... + bool DisableXCHMAMNShorts() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + !mXCHMAMNAllowShortSignals) + { + return result; + } + + // + result = true; + mXCHMAMNAllowShortSignals = false; + + // + return result; + } + + // + // Check Market Base Conditions for Long Signals ... + bool XCHMAMNHasLongConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + !mXCHMAMNAllowLongSignals) + { + return result; + } + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double xCHMANonSCMin2 = XCHMAGetCyclesMinValue(2, cycles); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXCHMASCCrossedOverMin && + xCHMAScFastBuffer[2] < xCHMANonSCMin2 && + xCHMAScSlowBuffer[2] < xCHMANonSCMin2 + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + + // + return result; + } + + // + // Check Market Base Conditions for Short Signals ... + bool XCHMAMNHasShortConditions() + { + // + bool result = false; + + // + // Validate Args ... + if ( + !mXCHMAMNEnableSignaller || + !mXCHMAMNAllowShortSignals) + { + return result; + } + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double xCHMANonSCMin2 = XCHMAGetCyclesMinValue(2, cycles); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + // each Strategy must has a Base Conditions, which they are usually common combinations + // of Market Properties that must be happens to lookup for signals ... + ( + // + mXConditions.isXCHMASCCrossedUnderMin && + xCHMAScFastBuffer[2] > xCHMANonSCMin2 && + xCHMAScSlowBuffer[2] > xCHMANonSCMin2 + // + ) + // + && + // + // Next Step is combine sorts of Conditions which make our choice + // so Exact in Market ... + ( + // + IsReadyForLong( + true, // XCHMA Min + true, // XCHMA Max + false, // XCHMA Cycles + false, // XCHMA Peaks + false, // XCHMA Trend Powers + true, // XOBD + true // XTS + ) + // + ) + // + ; + // + return result; + } + + // + // END XCHMAMN Signaller ... + // + + // + // END Actions Based On Signallers ... + // + + // + // Protected ... +protected: + // + // Private ... +private: + // + // XTD ... + bool mXTDEnableSignaller; + bool mXTDAllowLongSignals; + bool mXTDAllowShortSignals; + + // + // XTAM ... + bool mXTAMEnableSignaller; + bool mXTAMAllowLongSignals; + bool mXTAMAllowShortSignals; + + // + // XSI ... + bool mXSIEnableSignaller; + bool mXSIAllowLongSignals; + bool mXSIAllowShortSignals; + + // + // XTSFI ... + bool mXTSFIEnableSignaller; + bool mXTSFIAllowLongSignals; + bool mXTSFIAllowShortSignals; + + // + // XOBDLH ... + bool mXOBDLHEnableSignaller; + bool mXOBDLHAllowLongSignals; + bool mXOBDLHAllowShortSignals; + + // + // XCHMACC ... + bool mXCHMACCEnableSignaller; + bool mXCHMACCAllowLongSignals; + bool mXCHMACCAllowShortSignals; + + // + // XCHMAMX ... + bool mXCHMAMXEnableSignaller; + bool mXCHMAMXAllowLongSignals; + bool mXCHMAMXAllowShortSignals; + + // + // XCHMAMN ... + bool mXCHMAMNEnableSignaller; + bool mXCHMAMNAllowLongSignals; + bool mXCHMAMNAllowShortSignals; + + // + // Here we Define some Global Market Variables to Analyse MArket Conditions + // using them at each time ... + XMarketConditions mXConditions; +}; \ No newline at end of file diff --git a/Projects/XUSCHF5/Documents/.gitkeep b/Projects/XUSCHF5/Documents/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Documents/Reports/.gitkeep b/Projects/XUSCHF5/Documents/Reports/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Documents/Settings/.gitkeep b/Projects/XUSCHF5/Documents/Settings/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Experts/.gitkeep b/Projects/XUSCHF5/Experts/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Experts/x-saherelm.xuschf5.ea.mq5 b/Projects/XUSCHF5/Experts/x-saherelm.xuschf5.ea.mq5 new file mode 100644 index 00000000..0838146b --- /dev/null +++ b/Projects/XUSCHF5/Experts/x-saherelm.xuschf5.ea.mq5 @@ -0,0 +1,399 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Expert Advisor +// ---------------------------------------- +// Name: XAUUSD +// Description: this is an expert controller +// advisors which provides a mechanism for use them ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XUSCHF5 EA" +#property strict + +// +// START Inputs ... +// + +input group "Commons"; + +// +// XCTIMER inputs ... +input bool xUSCHF5ShowCandleTimer = true; // Show Condle Remaining Time +input color xUSCHF5CandleTimerColot = clrYellow; // Candle Timer Color +input ENUM_BASE_CORNER xUSCHF5CandleTimerCorner = CORNER_RIGHT_LOWER; // Where to Show Candle Timer + +// +// END Inputs ... +// + +// +// START Including Providers ... +// + +// +// Logger Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Alert Library ... +#include "../Libraries/x-saherelm.alert.lib.mq5" + +// +// Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// XUSCHF5 Signal Provider ... +#include "../Providers/x-saherelm.xuschf5.provider.lib.mq5" + +// +// END Including Providers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +bool isXUSCHF5NewHour; +bool isXUSCHF5NewDay; +bool isXUSCHF5NewWeek; +bool isXUSCHF5NewMonth; + +// +int xUSCHF5CTimerHandler = INVALID_HANDLE; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + logTag = "XUSCHF5EA"; + drawPrefix = logTag; + alertPrefix = logTag; + + // + // Apply default Chart Style for EA ... + ApplyChartStyle(); + + // + // Reset Timings ... + ResetTiming(); + + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize XUSCHF5 Provider ... + if (!XUSCHF5InitSignalProviderLibrary()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Init XCTimer ... + if (xUSCHF5ShowCandleTimer) + { + if (!XUSCHF5CTimerInit()) + { + return INIT_FAILED; + } + } + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + + // + // De Initialize XUSCHF5 Provider ... + XUSCHF5DeinitSignalProviderLibrary(reason); + + // + // De Init XDraw Library ... + // OnDeinitDrawLibrary(); + + // + IndicatorRelease(xUSCHF5CTimerHandler); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + // Handle Monthly Alert ... + bool isFirstMonth = xMonth == -1; + isXUSCHF5NewMonth = IsNewMonth(); + bool canMonthlyAlert = + isXUSCHF5NewMonth && + xUSCHF5EnableAlerts && + xUSCHF5EnableMonthlyAlerts; + bool canMonthlyReport = + !isFirstMonth && + canMonthlyAlert && + xUSCHF5EnableMonthlyReports; + if (canMonthlyAlert) + { + // + string message = "New Month ..."; + + // + // Prepare Monthly Report ... + if (canMonthlyReport) + { + // + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_MONTHLY); + + // + message = "Last Month Report:\n" + report; + } + + // + // Reset Report ... + xUSCHF5Reporter.Reset(XREPORT_MONTHLY); + + // + SendAlert(message); + } + + // + // Handle Weekly Alert ... + bool isFirstWeek = xDayOfWeek == -1; + isXUSCHF5NewWeek = IsNewWeek(); + bool canWeeklyAlert = + isXUSCHF5NewWeek && + xUSCHF5EnableAlerts && + xUSCHF5EnableWeeklyAlerts; + bool canWeeklyReport = + !isFirstWeek && + canWeeklyAlert && + xUSCHF5EnableWeeklyReports; + if (canWeeklyAlert) + { + // + string message = "New Week ..."; + + // + // Prepare Weekly Report ... + if (canWeeklyReport) + { + // + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_WEEKLY); + + // + message = "Last Week Report:\n" + report; + } + + // + // Reset Report ... + xUSCHF5Reporter.Reset(XREPORT_WEEKLY); + + // + SendAlert(message); + } + + // + // Handle Daily Alert ... + bool isFirstDay = xDay == -1; + isXUSCHF5NewDay = IsNewDay(); + bool canDailyAlert = + isXUSCHF5NewDay && + xUSCHF5EnableAlerts && + xUSCHF5EnableDailyAlerts; + bool canDailyReport = + !isFirstDay && + canDailyAlert && + xUSCHF5EnableDailyReports; + if (canDailyAlert) + { + // + string message = "New Day ..."; + + // + // Prepare Daily Report ... + if (canDailyReport) + { + // + string report = xUSCHF5Reporter.GenerateReportString(XREPORT_DAILY); + + // + message = "Last Week Report:\n" + report; + } + + // + // Reset Report ... + xUSCHF5Reporter.Reset(XREPORT_DAILY); + + // + SendAlert(message); + } + + // + // Handle Hourly Alert ... + bool isFirstHour = xHour == -1; + isXUSCHF5NewHour = IsNewHour(); + bool canHourlyAlert = + isXUSCHF5NewHour && + xUSCHF5EnableAlerts && + xUSCHF5EnableHourlyAlerts; + if (canHourlyAlert) + { + // + string message = "New Hour ..."; + + // + SendAlert(message); + } + + // + // Prevent Going Forward if user Disable it ... + if (xUSCHF5EnableProvider) + { + // + // Handle Processing on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderDoControlState(); + } + + // + // Check Can Ignore Tick or not .. + bool canIgnoreTick = xUSCHF5IsTestMode + ? !IsNewCandle() + : !IsNewCandle() && xUSCHF5WaitUntilNextCandle; + if (canIgnoreTick) + { + return; + } + + // + xUSCHF5WaitUntilNextCandle = false; + + // + // Prevent Going Forward if user Disable it ... + if (xUSCHF5EnableProvider) + { + // + // Handle Processing on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderHandleTick(); + } +} + +// +// Handle Trade Events ... +void OnTrade() +{ + + // + // Prevent Going Forward if user Disable it ... + if (xUSCHF5EnableProvider) + { + // + // Handle Processing Trades on XUSCHF5 Signal Provider ... + XUSCHF5SignalProviderHandleTrade(); + } +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + + // + // Validate XUSCHF5 Provider Inputs ... + result = XUSCHF5ValidateInputs(); + if (!result) + { + return false; + } + + // + // Logging State ... + string message = "Validation of (" + logTag + ") Inputs " + (result ? "Succeeded" : "Failed") + " ..."; + LogMessage(message); + + // + return result; +} + +bool XUSCHF5CTimerInit() +{ + // + bool result = true; + + // + xUSCHF5CTimerHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xctimer.indicator", + // + // Inputs ... + xUSCHF5CandleTimerColot, + xUSCHF5CandleTimerCorner); + + // + if (xUSCHF5CTimerHandler == INVALID_HANDLE) + { + result = false; + } + + // + return result; +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/.gitkeep b/Projects/XUSCHF5/Helpers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 new file mode 100644 index 00000000..f565e415 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xama.indicator.helper.lib.mq5 @@ -0,0 +1,607 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XAMA Indicator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XAMA Indicator States ... +enum ENUM_X_XAMA_STATES +{ + X_XAMA_BULLISH = 1, + X_XAMA_BEARISH = -1, + X_XAMA_NEUTURAL = 0, +}; + +// +// XAMA Indicator Buffer Lines ... +enum ENUM_X_XAMA_BUFFER_LINES +{ + X_XAMA_MA_LINE = 0, + X_XAMA_MC_COLOR_LINE = 1, + X_XAMA_STATE_LINE = 2, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XAMA Indicator"; + +// +// input int xAMALength = 18; // Market Length +// input int xAMAFastEMA = 2; // Fast EMA Period +// input int xAMASlowEMA = 30; // Slow EMA Period +// input int xAMAShift = 0; // Shift +// input ENUM_APPLIED_PRICE xAMAAppliedTo = PRICE_CLOSE; // Applied To + +// +// Configurations ... +int xAMALength = 18; // Market Length +int xAMAFastEMA = 2; // Fast EMA Period +int xAMASlowEMA = 30; // Slow EMA Period +int xAMAShift = 0; // Shift +ENUM_APPLIED_PRICE xAMAAppliedTo = PRICE_CLOSE; // Applied To + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xAMAHandler = INVALID_HANDLE; +double xAMAMaBuffer[]; +double xAMAStateBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XAMAValidateInputs() +{ + // + bool result = false; + + // + result = + xAMALength > 2 && + xAMAFastEMA < xAMALength && + xAMAFastEMA < xAMASlowEMA && + xAMAShift >= 0; + + // + if (!result) + { + // + LogMessage("XAMA Indicator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Indicators ... +bool XAMAInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Indicator Handlers ... + ResetLastError(); + + // + // XAMA Handler ... + ArraySetAsSeries(xAMAMaBuffer, true); + ArraySetAsSeries(xAMAStateBuffer, true); + xAMAHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xama.indicator", + // + // Inputs ... + xAMALength, + xAMAFastEMA, + xAMASlowEMA, + xAMAShift, + xAMAAppliedTo + // + ); + if (xAMAHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XAMA Indicator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Indicators ... +void XAMAReleaseHandlers() +{ + IndicatorRelease(xAMAHandler); +} + +// +// Handle Reading Buffers ... +void XAMAReadBuffers( + int xAMAItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XAMA Ma Buffer ... + CopyBuffer( + xAMAHandler, + X_XAMA_MA_LINE, + 0, + xAMAItemsPerTick, + xAMAMaBuffer); + + // + // XAMA State Buffer ... + CopyBuffer( + xAMAHandler, + X_XAMA_STATE_LINE, + 0, + xAMAItemsPerTick, + xAMAStateBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XAMA Custom Functions ... +// + +// +// Check SC is Peak ... +bool XAMAIsPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xAMAMaBuffer + // + ); + + // + return result; +} + +// +// Check SC is Vale ... +bool XAMAIsVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xAMAMaBuffer + // + ); + + // + return result; +} + +// +// Check TM Crossed Up ... +bool XAMAIsStartBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BULLISH && + xAMAStateBuffer[bar_index + 1] != X_XAMA_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Up After Neutural State ... +bool XAMAIsStartBullishAfterNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BULLISH && + xAMAStateBuffer[bar_index + 1] == X_XAMA_NEUTURAL + // + ; + + // + return result; +} + +// +// Check TM In Up State ... +bool XAMAIsBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Ends Up State ... +bool XAMAIsEndBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] != X_XAMA_BULLISH && + xAMAStateBuffer[bar_index + 1] == X_XAMA_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Ends Up State By Neutural ... +bool XAMAIsEndBullishByNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_NEUTURAL && + xAMAStateBuffer[bar_index + 1] == X_XAMA_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Down ... +bool XAMAIsStartBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BEARISH && + xAMAStateBuffer[bar_index + 1] != X_XAMA_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Down After Neutural State ... +bool XAMAIsStartBearishAfterNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BEARISH && + xAMAStateBuffer[bar_index + 1] == X_XAMA_NEUTURAL + // + ; + + // + return result; +} + +// +// Check TM In Down State ... +bool XAMAIsBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Ends Down State ... +bool XAMAIsEndBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] != X_XAMA_BEARISH && + xAMAStateBuffer[bar_index + 1] == X_XAMA_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Ends Down State By Neutural ... +bool XAMAIsEndBearishByNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_NEUTURAL && + xAMAStateBuffer[bar_index + 1] == X_XAMA_BEARISH + // + ; + + // + return result; +} + +// +// Check TM In Neutural State ... +bool XAMAIsNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XAMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xAMAStateBuffer[bar_index] == X_XAMA_NEUTURAL + // + ; + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XAMAIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xAMAMaBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XAMA Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..d7071b48 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xchlh.oscillator.helper.lib.mq5 @@ -0,0 +1,1032 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XCHLH Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// Cycles Enumeration ... +enum ENUM_X_XCHLH_CYCLES +{ + X_XCHLH_CYCLE_LONG, + X_XCHLH_CYCLE_MEDIUM, + X_XCHLH_CYCLE_SHORT, +}; + +// +// XCHLH Hot States ... +enum ENUM_X_XCHLH_HOT_STATES +{ + X_XCHLH_HOT_HH = 1, + X_XCHLH_NEUTURAL = 0, + X_XCHLH_HOT_LL = -1, +}; + +// +// XCHLH Buffer Lines ... +enum ENUM_X_XCHLH_BUFFER_LINES +{ + X_XCHLH_LC_HH_LINE = 0, + X_XCHLH_LC_LL_LINE = 1, + X_XCHLH_MC_HH_LINE = 2, + X_XCHLH_MC_LL_LINE = 3, + X_XCHLH_SC_HH_LINE = 4, + X_XCHLH_SC_LL_LINE = 5, + X_XCHLH_SIGNAL_T_LINE = 6, + X_XCHLH_SIGNAL_B_LINE = 7, + X_XCHLH_HOT_STATE_LINE = 8, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// // +// input group "XCHLH Oscillator"; + +// // +// // Common ... +// input group "XCHLH Hot Areas"; +// input bool xCHLHDrawHotAreas = false; // Draw Hot Areas Symbol +// input uchar xCHLHHotHHArrowCode = 234; // Hot HH Arrow Code +// input color xCHLHHotHHArrowColor = clrAqua; // Hot HH Arrow Color +// input uchar xCHLHHotLLArrowCode = 233; // Hot LL Arrow Code +// input color xCHLHHotLLArrowColor = clrFuchsia; // Hot LL Arrow Color + +// // +// // LC Inputs ... +// input group "XCHLH Long Cycle"; +// input group "XCHLH LC Market"; +// input int xCHLHLcLength = 288; // Length +// input double xCHLHLcThresholdInPips = 0.3; // Threshold In Pips +// input ENUM_SERIESMODE xCHLHLcHHMode = MODE_HIGH; // Highest High Calculation Method +// input ENUM_SERIESMODE xCHLHLcLLMode = MODE_LOW; // Lowest Low Calculation Method +// input group "XCHLH LC Style"; +// input int xCHLHLcDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHLHLcDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHLHLcDrawStyle = STYLE_DOT; // Draw Style +// input color xCHLHLcHHColor = clrAqua; // Highest High Color +// input color xCHLHLcLLColor = clrFuchsia; // Lowest Low Color +// input group "XCHLH LC Drawings"; +// input bool xCHLHLcDrawHH = true; // Draw Highest High +// input bool xCHLHLcDrawLL = true; // Draw Lowest Low + +// // +// // MC Inputs ... +// input group "XCHLH Medium Cycle"; +// input group "XCHLH MC Market"; +// input int xCHLHMcLength = 72; // Length +// input double xCHLHMcThresholdInPips = 0.3; // Threshold In Pips +// input ENUM_SERIESMODE xCHLHMcHHMode = MODE_HIGH; // Highest High Calculation Method +// input ENUM_SERIESMODE xCHLHMcLLMode = MODE_LOW; // Lowest Low Calculation Method +// input group "XCHLH MC Style"; +// input int xCHLHMcDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHLHMcDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHLHMcDrawStyle = STYLE_DOT; // Draw Style +// input color xCHLHMcHHColor = clrLime; // Highest High Color +// input color xCHLHMcLLColor = clrRed; // Lowest Low Color +// input group "XCHLH MC Drawings"; +// input bool xCHLHMcDrawHH = true; // Draw Highest High +// input bool xCHLHMcDrawLL = true; // Draw Lowest Low + +// // +// // SC Inputs ... +// input group "XCHLH Short Cycle"; +// input group "XCHLH SC Market"; +// input int xCHLHScLength = 7; // Length +// input double xCHLHScThresholdInPips = 0.3; // Threshold In Pips +// input ENUM_SERIESMODE xCHLHScHHMode = MODE_HIGH; // Highest High Calculation Method +// input ENUM_SERIESMODE xCHLHScLLMode = MODE_LOW; // Lowest Low Calculation Method +// input group "XCHLH SC Style"; +// input int xCHLHScDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHLHScDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHLHScDrawStyle = STYLE_DOT; // Draw Style +// input color xCHLHScHHColor = clrLightBlue; // Highest High Color +// input color xCHLHScLLColor = clrLightSalmon; // Lowest Low Color +// input group "XCHLH SC Drawings"; +// input bool xCHLHScDrawHH = true; // Draw Highest High +// input bool xCHLHScDrawLL = true; // Draw Lowest Low + +// +// Configurations ... +// +// Common ... +bool xCHLHDrawHotAreas = false; // Draw Hot Areas Symbol +uchar xCHLHHotHHArrowCode = 234; // Hot HH Arrow Code +color xCHLHHotHHArrowColor = clrAqua; // Hot HH Arrow Color +uchar xCHLHHotLLArrowCode = 233; // Hot LL Arrow Code +color xCHLHHotLLArrowColor = clrFuchsia; // Hot LL Arrow Color + +// +// LC Inputs ... +int xCHLHLcLength = 288; // Length +double xCHLHLcThresholdInPips = 0.3; // Threshold In Pips +ENUM_SERIESMODE xCHLHLcHHMode = MODE_HIGH; // Highest High Calculation Method +ENUM_SERIESMODE xCHLHLcLLMode = MODE_LOW; // Lowest Low Calculation Method +int xCHLHLcDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHLHLcDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHLHLcDrawStyle = STYLE_DOT; // Draw Style +color xCHLHLcHHColor = clrAqua; // Highest High Color +color xCHLHLcLLColor = clrFuchsia; // Lowest Low Color +bool xCHLHLcDrawHH = true; // Draw Highest High +bool xCHLHLcDrawLL = true; // Draw Lowest Low + +// +// MC Inputs ... +int xCHLHMcLength = 72; // Length +double xCHLHMcThresholdInPips = 0.3; // Threshold In Pips +ENUM_SERIESMODE xCHLHMcHHMode = MODE_HIGH; // Highest High Calculation Method +ENUM_SERIESMODE xCHLHMcLLMode = MODE_LOW; // Lowest Low Calculation Method +int xCHLHMcDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHLHMcDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHLHMcDrawStyle = STYLE_DOT; // Draw Style +color xCHLHMcHHColor = clrLime; // Highest High Color +color xCHLHMcLLColor = clrRed; // Lowest Low Color +bool xCHLHMcDrawHH = true; // Draw Highest High +bool xCHLHMcDrawLL = true; // Draw Lowest Low + +// +// SC Inputs ... +int xCHLHScLength = 7; // Length +double xCHLHScThresholdInPips = 0.3; // Threshold In Pips +ENUM_SERIESMODE xCHLHScHHMode = MODE_HIGH; // Highest High Calculation Method +ENUM_SERIESMODE xCHLHScLLMode = MODE_LOW; // Lowest Low Calculation Method +int xCHLHScDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHLHScDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHLHScDrawStyle = STYLE_DOT; // Draw Style +color xCHLHScHHColor = clrLightBlue; // Highest High Color +color xCHLHScLLColor = clrLightSalmon; // Lowest Low Color +bool xCHLHScDrawHH = true; // Draw Highest High +bool xCHLHScDrawLL = true; // Draw Lowest Low + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xCHLHHandler = INVALID_HANDLE; +double xCHLHLcHHBuffer[]; +double xCHLHLcLLBuffer[]; +double xCHLHMcHHBuffer[]; +double xCHLHMcLLBuffer[]; +double xCHLHScHHBuffer[]; +double xCHLHScLLBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XCHLHValidateInputs() +{ + // + bool result = false; + + // + result = + xCHLHScLength >= 2 && + xCHLHMcLength > xCHLHScLength && + xCHLHLcLength > xCHLHMcLength; + + // + if (!result) + { + // + LogMessage("XCHLH Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XCHLHInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XCHLH Handler ... + ArraySetAsSeries(xCHLHLcHHBuffer, true); + ArraySetAsSeries(xCHLHLcLLBuffer, true); + ArraySetAsSeries(xCHLHMcHHBuffer, true); + ArraySetAsSeries(xCHLHMcLLBuffer, true); + ArraySetAsSeries(xCHLHScHHBuffer, true); + ArraySetAsSeries(xCHLHScLLBuffer, true); + xCHLHHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xchlh.oscillator", + // + // Inputs ... + // + // Commons ... + "", + xCHLHDrawHotAreas, + xCHLHHotHHArrowCode, + xCHLHHotHHArrowColor, + xCHLHHotLLArrowCode, + xCHLHHotLLArrowColor, + // + // LC ... + "", + "", + xCHLHLcLength, + xCHLHLcThresholdInPips, + xCHLHLcHHMode, + xCHLHLcLLMode, + "", + xCHLHLcDrawWidth, + xCHLHLcDrawType, + xCHLHLcDrawStyle, + xCHLHLcHHColor, + xCHLHLcLLColor, + "", + xCHLHLcDrawHH, + xCHLHLcDrawLL, + // + // MC ... + "", + "", + xCHLHMcLength, + xCHLHMcThresholdInPips, + xCHLHMcHHMode, + xCHLHMcLLMode, + "", + xCHLHMcDrawWidth, + xCHLHMcDrawType, + xCHLHMcDrawStyle, + xCHLHMcHHColor, + xCHLHMcLLColor, + "", + xCHLHMcDrawHH, + xCHLHMcDrawLL, + // + // SC ... + "", + "", + xCHLHScLength, + xCHLHScThresholdInPips, + xCHLHScHHMode, + xCHLHScLLMode, + "", + xCHLHScDrawWidth, + xCHLHScDrawType, + xCHLHScDrawStyle, + xCHLHScHHColor, + xCHLHScLLColor, + "", + xCHLHScDrawHH, + xCHLHScDrawLL); + if (xCHLHHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XCHLH Indicator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XCHLHReleaseHandlers() +{ + IndicatorRelease(xCHLHHandler); +} + +// +// Handle Reading Buffers ... +void XCHLHReadBuffers( + int xCHLHItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XCHLH LC HH Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_LC_HH_LINE, + 0, + xCHLHItemsPerTick, + xCHLHLcHHBuffer); + + // + // XCHLH LC LL Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_LC_LL_LINE, + 0, + xCHLHItemsPerTick, + xCHLHLcLLBuffer); + + // + // XCHLH MC HH Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_MC_HH_LINE, + 0, + xCHLHItemsPerTick, + xCHLHMcHHBuffer); + + // + // XCHLH MC LL Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_MC_LL_LINE, + 0, + xCHLHItemsPerTick, + xCHLHMcLLBuffer); + + // + // XCHLH SC HH Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_SC_HH_LINE, + 0, + xCHLHItemsPerTick, + xCHLHScHHBuffer); + + // + // XCHLH SC LL Buffer ... + CopyBuffer( + xCHLHHandler, + X_XCHLH_SC_LL_LINE, + 0, + xCHLHItemsPerTick, + xCHLHScLLBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XCHLH Custom Functions ... +// + +// +// Check LC and MC has Same HH ... +bool XCHLHIsLCMCHasSameHH( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcHHBuffer[bar_index]; + double mcValue = xCHLHMcHHBuffer[bar_index]; + + // + result = lcValue == mcValue; + + // + return result; +} + +// +// Check LC and MC has Same LL ... +bool XCHLHIsLCMCHasSameLL( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcLLBuffer[bar_index]; + double mcValue = xCHLHMcLLBuffer[bar_index]; + + // + result = lcValue == mcValue; + + // + return result; +} + +// +// Check LC and SC has Same HH ... +bool XCHLHIsLCSCHasSameHH( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcHHBuffer[bar_index]; + double scValue = xCHLHScHHBuffer[bar_index]; + + // + result = lcValue == scValue; + + // + return result; +} + +// +// Check LC and SC has Same LL ... +bool XCHLHIsLCSCHasSameLL( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcLLBuffer[bar_index]; + double scValue = xCHLHScLLBuffer[bar_index]; + + // + result = lcValue == scValue; + + // + return result; +} + +// +// Check MC and SC has Same HH ... +bool XCHLHIsMCSCHasSameHH( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double mcValue = xCHLHMcHHBuffer[bar_index]; + double scValue = xCHLHScHHBuffer[bar_index]; + + // + result = mcValue == scValue; + + // + return result; +} + +// +// Check MC and SC has Same LL ... +bool XCHLHIsMCSCHasSameLL( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double mcValue = xCHLHMcLLBuffer[bar_index]; + double scValue = xCHLHScLLBuffer[bar_index]; + + // + result = mcValue == scValue; + + // + return result; +} + +// +// Check Is Same Highest Highs ... +bool XCHLHIsSameHHs( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcHHBuffer[bar_index]; + double mcValue = xCHLHMcHHBuffer[bar_index]; + double scValue = xCHLHScHHBuffer[bar_index]; + + // + result = + // + lcValue == mcValue && + mcValue == scValue + // + ; + + // + return result; +} + +// +// Check Is Same Lowest Lows ... +bool XCHLHIsSameLLs( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if (!XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + double lcValue = xCHLHLcLLBuffer[bar_index]; + double mcValue = xCHLHMcLLBuffer[bar_index]; + double scValue = xCHLHScLLBuffer[bar_index]; + + // + result = + // + lcValue == mcValue && + mcValue == scValue + // + ; + + // + return result; +} + +// +// Check Medium Cycle is On Top of Long Cycle's Mid ... +bool XCHLHIsMCOnTopOfLC( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + ENUM_X_XCHLH_CYCLES sCycle = X_XCHLH_CYCLE_MEDIUM; + ENUM_X_XCHLH_CYCLES dCycle = X_XCHLH_CYCLE_LONG; + + // + result = + // + XCHLHCheckCycleIsOnTopOfAnother( + bar_index, + sCycle, + dCycle) + // + ; + + // + return result; +} + +// +// Check Medium Cycle is In Bottom of Long Cycle's Mid ... +bool XCHLHIsMCInBottomOfLC( + int bar_index // Specified Bar Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + ENUM_X_XCHLH_CYCLES sCycle = X_XCHLH_CYCLE_MEDIUM; + ENUM_X_XCHLH_CYCLES dCycle = X_XCHLH_CYCLE_LONG; + + // + result = + // + XCHLHCheckCycleIsInBottomOfAnother( + bar_index, + sCycle, + dCycle) + // + ; + + // + return result; +} + +// +// Check and Validate Buffer Sizes ... +bool XCHLHIsValidBufferSizes( + int size // Specified Min Size +) +{ + // + bool result = false; + + // + result = + // + ArraySize(xCHLHLcHHBuffer) > size && + ArraySize(xCHLHLcLLBuffer) > size && + // + ArraySize(xCHLHMcHHBuffer) > size && + ArraySize(xCHLHMcLLBuffer) > size && + // + ArraySize(xCHLHScHHBuffer) > size && + ArraySize(xCHLHScLLBuffer) > size; + + // + return result; +} + +// +// Get Cycle Middle Value ... +double XCHLHGetCycleMid( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES cycle // Specified Cycle ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + // Retrieve Cycle Max Value ... + double iMax = XCHLHGetCycleMax( + bar_index, + cycle); + + // + // Retrieve Cycle Min Value ... + double iMin = XCHLHGetCycleMin( + bar_index, + cycle); + + // + result = (iMax - iMin) / 2; + + // + return result; +} + +// +// Get Cycle Max Value ... +double XCHLHGetCycleMax( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES cycle // Specified Cycle ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + switch (cycle) + { + // + // Long Cycle ... + case X_XCHLH_CYCLE_LONG: + result = xCHLHLcHHBuffer[1]; + break; + + // + // Medium Cycle ... + case X_XCHLH_CYCLE_MEDIUM: + result = xCHLHMcHHBuffer[1]; + break; + + // + // Short Cycle ... + case X_XCHLH_CYCLE_SHORT: + result = xCHLHScHHBuffer[1]; + break; + } + + // + return result; +} + +// +// Get Specified Cycles Max Value ... +double XCHLHGetCyclesMax( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES &cycles[] // Specified Cycle ... +) +{ + // + bool result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + ArraySize(cycles) <= 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + // Loop Through Cycles ... + for (int i = 0; i < ArraySize(cycles); i++) + { + // + ENUM_X_XCHLH_CYCLES iCycle = cycles[i]; + + // + double iValue = XCHLHGetCycleMax( + bar_index, + iCycle); + + // + result = result == 0 || result < iValue ? iValue : result; + } + + // + return result; +} + +// +// Get Cycle Min Value ... +double XCHLHGetCycleMin( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES cycle // Specified Cycle ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + switch (cycle) + { + // + // Long Cycle ... + case X_XCHLH_CYCLE_LONG: + result = xCHLHLcLLBuffer[1]; + break; + + // + // Medium Cycle ... + case X_XCHLH_CYCLE_MEDIUM: + result = xCHLHMcLLBuffer[1]; + break; + + // + // Short Cycle ... + case X_XCHLH_CYCLE_SHORT: + result = xCHLHScLLBuffer[1]; + break; + } + + // + return result; +} + +// +// Get Specified Cycles Min Value ... +double XCHLHGetCyclesMin( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES &cycles[] // Specified Cycle ... +) +{ + // + bool result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + ArraySize(cycles) <= 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + // Loop Through Cycles ... + for (int i = 0; i < ArraySize(cycles); i++) + { + // + ENUM_X_XCHLH_CYCLES iCycle = cycles[i]; + + // + double iValue = XCHLHGetCycleMin( + bar_index, + iCycle); + + // + result = result == 0 || result > iValue ? iValue : result; + } + + // + return result; +} + +// +// Check a Cycle is On Top of Another Cycle's Mid ... +bool XCHLHCheckCycleIsOnTopOfAnother( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES sourceCycle, // Specified Source Cycle which Checks ... + ENUM_X_XCHLH_CYCLES destCycle // Specified Dest Cycle which source Checked based on it ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + // Retrieve Min Value of Source Cycle ... + double iMin = XCHLHGetCycleMin( + bar_index, + sourceCycle); + + // + // Retrieve Mid Value of Dest Cycle ... + double iMid = XCHLHGetCycleMid( + bar_index, + destCycle); + + // + // Generate Result ... + result = + // + iMin >= iMid + // + ; + + // + return result; +} + +// +// Check a Cycle is Under Bottom of Another Cycle's Mid ... +bool XCHLHCheckCycleIsInBottomOfAnother( + int bar_index, // Specified Bar Index ... + ENUM_X_XCHLH_CYCLES sourceCycle, // Specified Source Cycle which Checks ... + ENUM_X_XCHLH_CYCLES destCycle // Specified Dest Cycle which source Checked based on it ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHLHIsValidBufferSizes(bar_index + 1)) + { + return result; + } + + // + // Retrieve Max Value of Source Cycle ... + double iMax = XCHLHGetCycleMax( + bar_index, + sourceCycle); + + // + // Retrieve Mid Value of Dest Cycle ... + double iMid = XCHLHGetCycleMid( + bar_index, + destCycle); + + // + // Generate Result ... + result = + // + iMax <= iMid + // + ; + + // + return result; +} + +// +// END XCHLH Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..e84d762f --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xchma.oscillator.helper.lib.mq5 @@ -0,0 +1,2229 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XCHMA Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XCHMA Cycles ... +enum ENUM_XCHMA_CYCLES +{ + X_XCHMA_CYCLE_LONG, + X_XCHMA_CYCLE_MEDIUM, + X_XCHMA_CYCLE_SHORT, +}; + +// +// XCHMA Oscillator Hot State Presentation ... +enum ENUM_XCHMA_HOT_STATES +{ + X_XCHMA_HOT_BULLISH = 1, + X_XCHMA_HOT_NEUTURAL = 0, + X_XCHMA_HOT_BEARISH = -1, +}; + +// +// XCHMA Oscillator Cycles State Presentation ... +enum ENUM_XCHMA_CYCLE_STATES +{ + X_XCHMA_FAST_CROSSED_OVER_SLOW = 2, + X_XCHMA_FAST_OVER_SLOW = 1, + X_XCHMA_NEUTURAL = 0, + X_XCHMA_FAST_UNDER_SLOW = -1, + X_XCHMA_FAST_CROSSED_UNDER_SLOW = -2, +}; + +// +// XCHMA Oscillator Buffer Lines ... +enum ENUM_X_XCHMA_BUFFER_LINES +{ + X_XCHMA_LC_FAST_LINE = 0, + X_XCHMA_LC_SLOW_LINE = 1, + X_XCHMA_LC_STATE_LINE = 6, + X_XCHMA_MC_FAST_LINE = 2, + X_XCHMA_MC_SLOW_LINE = 3, + X_XCHMA_MC_STATE_LINE = 7, + X_XCHMA_SC_FAST_LINE = 4, + X_XCHMA_SC_SLOW_LINE = 5, + X_XCHMA_SC_STATE_LINE = 8, + X_XCHMA_HOT_STATE_LINE = 9, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XCHMA Oscillator"; + +// // +// // Commons ... +// input group "XCHMA Hot Areas"; +// input bool xCHMADrawHotAreas = false; // Draw Hot Areas Symbol; +// input uchar xCHMAHotBullishArrowCode = 228; // Hot Bullish Arrow Code; +// input color xCHMAHotBullishArrowColor = clrAqua; // Hot Bullish Arrow Color; +// input uchar xCHMAHotBearishArrowCode = 230; // Hot Bearish Arrow Code; +// input color xCHMAHotBearishArrowColor = clrFuchsia; // Hot Bearish Arrow Color; + +// // +// // LC Inputs ... +// input group "XCHMA Long Cycle"; +// input group "XCHMA LC Market"; +// input int xCHMALcFastLength = 288; // Fast Length +// input int xCHMALcSlowLength = 576; // Slow Length +// input ENUM_MA_METHOD xCHMALcMethod = MODE_EMA; // Calculation Method +// input ENUM_APPLIED_PRICE xCHMALcAppliedTo = PRICE_CLOSE; // Applied To +// input group "XCHMA LC Style"; +// input int xCHMALcDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHMALcDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHMALcDrawStyle = STYLE_DOT; // Draw Style +// input color xCHMALcFastColor = clrAqua; // Fast Color +// input color xCHMALcSlowColor = clrFuchsia; // Slow Color +// input group "XCHMA LC Drawings"; +// input bool xCHMALcDrawFast = true; // Draw Fast +// input bool xCHMALcDrawSlow = true; // Draw Slow +// input bool xCHMALcDrawCrosses = false; // Draw Cross Lines + +// // +// // MC Inputs ... +// input group "XCHMA Medium Cycle"; +// input group "XCHMA MC Market"; +// input int xCHMAMcFastLength = 72; // Fast Length +// input int xCHMAMcSlowLength = 144; // Slow Length +// input ENUM_MA_METHOD xCHMAMcMethod = MODE_EMA; // Calculation Method +// input ENUM_APPLIED_PRICE xCHMAMcAppliedTo = PRICE_CLOSE; // Applied To +// input group "XCHMA MC Style"; +// input int xCHMAMcDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHMAMcDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHMAMcDrawStyle = STYLE_DOT; // Draw Style +// input color xCHMAMcFastColor = clrLime; // Fast Color +// input color xCHMAMcSlowColor = clrRed; // Slow Color +// input group "XCHMA MC Drawings"; +// input bool xCHMAMcDrawFast = true; // Draw Fast +// input bool xCHMAMcDrawSlow = true; // Draw Slow +// input bool xCHMAMcDrawCrosses = false; // Draw Cross Lines + +// // +// // SC Inputs ... +// input group "XCHMA Short Cycle"; +// input group "XCHMA SC Market"; +// input int xCHMAScFastLength = 7; // Fast Length +// input int xCHMAScSlowLength = 14; // Slow Length +// input ENUM_MA_METHOD xCHMAScMethod = MODE_SMA; // Calculation Method +// input ENUM_APPLIED_PRICE xCHMAScAppliedTo = PRICE_CLOSE; // Applied To +// input group "XCHMA SC Style"; +// input int xCHMAScDrawWidth = 1; // Draw Width +// input ENUM_DRAW_TYPE xCHMAScDrawType = DRAW_LINE; // Draw Type +// input ENUM_LINE_STYLE xCHMAScDrawStyle = STYLE_SOLID; // Draw Style +// input color xCHMAScFastColor = clrLightBlue; // Fast Color +// input color xCHMAScSlowColor = clrLightSalmon; // Slow Color +// input group "XCHMA SC Drawings"; +// input bool xCHMAScDrawFast = true; // Draw Fast +// input bool xCHMAScDrawSlow = true; // Draw Slow +// input bool xCHMAScDrawCrosses = false; // Draw Cross Lines + +// +// Configurations ... +// +// Commons ... +bool xCHMADrawHotAreas = false; // Draw Hot Areas Symbol; +uchar xCHMAHotBullishArrowCode = 228; // Hot Bullish Arrow Code; +color xCHMAHotBullishArrowColor = clrAqua; // Hot Bullish Arrow Color; +uchar xCHMAHotBearishArrowCode = 230; // Hot Bearish Arrow Code; +color xCHMAHotBearishArrowColor = clrFuchsia; // Hot Bearish Arrow Color; + +// +// LC Inputs ... +int xCHMALcFastLength = 288; // Fast Length +int xCHMALcSlowLength = 576; // Slow Length +ENUM_MA_METHOD xCHMALcMethod = MODE_EMA; // Calculation Method +ENUM_APPLIED_PRICE xCHMALcAppliedTo = PRICE_CLOSE; // Applied To +int xCHMALcDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHMALcDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHMALcDrawStyle = STYLE_DOT; // Draw Style +color xCHMALcFastColor = clrAqua; // Fast Color +color xCHMALcSlowColor = clrFuchsia; // Slow Color +bool xCHMALcDrawFast = true; // Draw Fast +bool xCHMALcDrawSlow = true; // Draw Slow +bool xCHMALcDrawCrosses = false; // Draw Cross Lines + +// +// MC Inputs ... +int xCHMAMcFastLength = 72; // Fast Length +int xCHMAMcSlowLength = 144; // Slow Length +ENUM_MA_METHOD xCHMAMcMethod = MODE_EMA; // Calculation Method +ENUM_APPLIED_PRICE xCHMAMcAppliedTo = PRICE_CLOSE; // Applied To +int xCHMAMcDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHMAMcDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHMAMcDrawStyle = STYLE_DOT; // Draw Style +color xCHMAMcFastColor = clrLime; // Fast Color +color xCHMAMcSlowColor = clrRed; // Slow Color +bool xCHMAMcDrawFast = true; // Draw Fast +bool xCHMAMcDrawSlow = true; // Draw Slow +bool xCHMAMcDrawCrosses = false; // Draw Cross Lines + +// +// SC Inputs ... +int xCHMAScFastLength = 7; // Fast Length +int xCHMAScSlowLength = 14; // Slow Length +ENUM_MA_METHOD xCHMAScMethod = MODE_SMA; // Calculation Method +ENUM_APPLIED_PRICE xCHMAScAppliedTo = PRICE_CLOSE; // Applied To +int xCHMAScDrawWidth = 1; // Draw Width +ENUM_DRAW_TYPE xCHMAScDrawType = DRAW_LINE; // Draw Type +ENUM_LINE_STYLE xCHMAScDrawStyle = STYLE_SOLID; // Draw Style +color xCHMAScFastColor = clrLightBlue; // Fast Color +color xCHMAScSlowColor = clrLightSalmon; // Slow Color +bool xCHMAScDrawFast = true; // Draw Fast +bool xCHMAScDrawSlow = true; // Draw Slow +bool xCHMAScDrawCrosses = false; // Draw Cross Lines + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xCHMAHandler = INVALID_HANDLE; +double xCHMALcFastBuffer[]; +double xCHMALcSlowBuffer[]; +double xCHMAMcFastBuffer[]; +double xCHMAMcSlowBuffer[]; +double xCHMAScFastBuffer[]; +double xCHMAScSlowBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XCHMAValidateInputs() +{ + // + bool result = false; + + // + result = + xCHMAScFastLength >= 2 && + xCHMAScSlowLength > xCHMAScFastLength && + xCHMAMcFastLength > xCHMAScSlowLength && + xCHMAMcSlowLength > xCHMAMcFastLength && + xCHMALcFastLength > xCHMAMcSlowLength && + xCHMALcSlowLength > xCHMALcFastLength; + + // + if (!result) + { + // + LogMessage("XCHMA Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XCHMAInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XCHMA Handler ... + ArraySetAsSeries(xCHMALcFastBuffer, true); + ArraySetAsSeries(xCHMALcSlowBuffer, true); + ArraySetAsSeries(xCHMAMcFastBuffer, true); + ArraySetAsSeries(xCHMAMcSlowBuffer, true); + ArraySetAsSeries(xCHMAScFastBuffer, true); + ArraySetAsSeries(xCHMAScSlowBuffer, true); + xCHMAHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xchma.oscillator", + // + // Inputs ... + "", + xCHMADrawHotAreas, + xCHMAHotBullishArrowCode, + xCHMAHotBullishArrowColor, + xCHMAHotBearishArrowCode, + xCHMAHotBearishArrowColor, + // + // Long Cycle ... + "", + "", + xCHMALcFastLength, + xCHMALcSlowLength, + xCHMALcMethod, + xCHMALcAppliedTo, + "", + xCHMALcDrawWidth, + xCHMALcDrawType, + xCHMALcDrawStyle, + xCHMALcFastColor, + xCHMALcSlowColor, + "", + xCHMALcDrawFast, + xCHMALcDrawSlow, + xCHMALcDrawCrosses, + // + // Medium Cycle ... + "", + "", + xCHMAMcFastLength, + xCHMAMcSlowLength, + xCHMAMcMethod, + xCHMAMcAppliedTo, + "", + xCHMAMcDrawWidth, + xCHMAMcDrawType, + xCHMAMcDrawStyle, + xCHMAMcFastColor, + xCHMAMcSlowColor, + "", + xCHMAMcDrawFast, + xCHMAMcDrawSlow, + xCHMAMcDrawCrosses, + // + // Short Cycle ... + "", + "", + xCHMAScFastLength, + xCHMAScSlowLength, + xCHMAScMethod, + xCHMAScAppliedTo, + "", + xCHMAScDrawWidth, + xCHMAScDrawType, + xCHMAScDrawStyle, + xCHMAScFastColor, + xCHMAScSlowColor, + "", + xCHMAScDrawFast, + xCHMAScDrawSlow, + xCHMAScDrawCrosses); + if (xCHMAHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XCHMA Oscillator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XCHMAReleaseHandlers() +{ + IndicatorRelease(xCHMAHandler); +} + +// +// Handle Reading Buffers ... +void XCHMAReadBuffers( + int xCHMAItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XCHMA Long Cycle ... + // + // XCHMA Fast ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_LC_FAST_LINE, + 0, + xCHMAItemsPerTick, + xCHMALcFastBuffer); + + // + // XCHMA Slow ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_LC_SLOW_LINE, + 0, + xCHMAItemsPerTick, + xCHMALcSlowBuffer); + + // + // XCHMA Medium Cycle ... + // + // XCHMA Fast ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_MC_FAST_LINE, + 0, + xCHMAItemsPerTick, + xCHMAMcFastBuffer); + + // + // XCHMA Slow ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_MC_SLOW_LINE, + 0, + xCHMAItemsPerTick, + xCHMAMcSlowBuffer); + + // + // XCHMA Short Cycle ... + // + // XCHMA Fast ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_SC_FAST_LINE, + 0, + xCHMAItemsPerTick, + xCHMAScFastBuffer); + + // + // XCHMA Slow ... + CopyBuffer( + xCHMAHandler, + X_XCHMA_SC_SLOW_LINE, + 0, + xCHMAItemsPerTick, + xCHMAScSlowBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XCHMA Custom Functions ... +// + +// +// Retrieve Max Cycles Value ... +double XCHMAGetMax( + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if (!XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + // SC Fast ... + result = MathMax( + result, + xCHMAScFastBuffer[bar_index]); + + // + // SC Slow ... + result = MathMax( + result, + xCHMAScSlowBuffer[bar_index]); + + // + // MC Fast ... + result = MathMax( + result, + xCHMAMcFastBuffer[bar_index]); + + // + // MC Slow ... + result = MathMax( + result, + xCHMAMcSlowBuffer[bar_index]); + + // + // LC Fast ... + result = MathMax( + result, + xCHMALcFastBuffer[bar_index]); + + // + // LC Slow ... + result = MathMax( + result, + xCHMALcSlowBuffer[bar_index]); + + // + return result; +} + +// +// Retrieve Max Cycles Value ... +double XCHMAGetMin( + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if (!XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = xCHMAScFastBuffer[bar_index]; + + // + // SC Fast ... + result = MathMin( + result, + xCHMAScFastBuffer[bar_index]); + + // + // SC Slow ... + result = MathMin( + result, + xCHMAScSlowBuffer[bar_index]); + + // + // MC Fast ... + result = MathMin( + result, + xCHMAMcFastBuffer[bar_index]); + + // + // MC Slow ... + result = MathMin( + result, + xCHMAMcSlowBuffer[bar_index]); + + // + // LC Fast ... + result = MathMin( + result, + xCHMALcFastBuffer[bar_index]); + + // + // LC Slow ... + result = MathMin( + result, + xCHMALcSlowBuffer[bar_index]); + + // + return result; +} + +// +// Short Cycle Over Max Of Cycle Channels ... +bool XCHMAIsSCOverMax( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double shortCycleMax1 = XCHMAGetCycleMaxValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMax1 = XCHMAGetCyclesMaxValue( + bar_index, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMax1 > nonOfShortCycleMax1 + // + ; + + // + return result; +} + +// +// Short Cycle Under Max Of Cycle Channels ... +bool XCHMAIsSCUnderMax( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double shortCycleMin1 = XCHMAGetCycleMinValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMax1 = XCHMAGetCyclesMaxValue( + bar_index, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMin1 < nonOfShortCycleMax1 + // + ; + + // + return result; +} + +// +// Short Cycle Over Min Of Cycle Channels ... +bool XCHMAIsSCOverMin( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double shortCycleMax1 = XCHMAGetCycleMaxValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMin1 = XCHMAGetCyclesMinValue( + bar_index, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMax1 > nonOfShortCycleMin1 + // + ; + + // + return result; +} + +// +// Short Cycle Under Min Of Cycle Channels ... +bool XCHMAIsSCUnderMin( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double shortCycleMin1 = XCHMAGetCycleMinValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMin1 = XCHMAGetCyclesMinValue( + bar_index, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMin1 < nonOfShortCycleMin1 + // + ; + + // + return result; +} + +// +// Short Cycle Crossed Over Max Of Cycle Channels ... +bool XCHMAIsSCCrossedOverMax( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double shortCycleMin1 = XCHMAGetCycleMinValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + double shortCycleMin2 = XCHMAGetCycleMinValue( + bar_index + 1, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMax1 = XCHMAGetCyclesMaxValue( + bar_index, + cycles); + double nonOfShortCycleMax2 = XCHMAGetCyclesMaxValue( + bar_index + 1, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMin1 > nonOfShortCycleMax1 && + shortCycleMin2 <= nonOfShortCycleMax2 + // + ; + + // + return result; +} + +// +// Short Cycle Crossed Under Max Of Cycle Channels ... +bool XCHMAIsSCCrossedUnderMax( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double shortCycleMax1 = XCHMAGetCycleMaxValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + double shortCycleMax2 = XCHMAGetCycleMaxValue( + bar_index + 1, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMax1 = XCHMAGetCyclesMaxValue( + bar_index, + cycles); + double nonOfShortCycleMax2 = XCHMAGetCyclesMaxValue( + bar_index + 1, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMax1 < nonOfShortCycleMax1 && + shortCycleMax2 >= nonOfShortCycleMax2 + // + ; + + // + return result; +} + +// +// Short Cycle Crossed Over Min Of Cycle Channels ... +bool XCHMAIsSCCrossedOverMin( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double shortCycleMin1 = XCHMAGetCycleMinValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + double shortCycleMin2 = XCHMAGetCycleMinValue( + bar_index + 1, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMin1 = XCHMAGetCyclesMinValue( + bar_index, + cycles); + double nonOfShortCycleMin2 = XCHMAGetCyclesMinValue( + bar_index + 1, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMin1 > nonOfShortCycleMin1 && + shortCycleMin2 <= nonOfShortCycleMin2 + // + ; + + // + return result; +} + +// +// Short Cycle Crossed Under Min Of Cycle Channels ... +bool XCHMAIsSCCrossedUnderMin( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XCHMAIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double shortCycleMax1 = XCHMAGetCycleMaxValue( + bar_index, + X_XCHMA_CYCLE_SHORT); + double shortCycleMax2 = XCHMAGetCycleMaxValue( + bar_index + 1, + X_XCHMA_CYCLE_SHORT); + + // + ENUM_XCHMA_CYCLES cycles[]; + Add( + X_XCHMA_CYCLE_MEDIUM, + cycles); + Add( + X_XCHMA_CYCLE_LONG, + cycles); + + // + double nonOfShortCycleMin1 = XCHMAGetCyclesMinValue( + bar_index, + cycles); + double nonOfShortCycleMin2 = XCHMAGetCyclesMinValue( + bar_index + 1, + cycles); + + // + // Calculate Result ... + result = + // + shortCycleMax1 < nonOfShortCycleMin1 && + shortCycleMax2 >= nonOfShortCycleMin2 + // + ; + + // + return result; +} + +// +// Long Cycle ... +// + +// +// Check LC is Peak ... +bool XCHMAIsLCPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsIncreasing( + bar_index + length, + bar_index, + xCHMALcSlowBuffer + // + ); + + // + return result; +} + +// +// Check LC is Vale ... +bool XCHMAIsLCVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xCHMALcSlowBuffer + // + ); + + // + return result; +} + +// +// Check LC Fast Crossed Over Slow ... +bool XCHMAIsLCFastCrossedOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossOver( + xCHMALcFastBuffer, + xCHMALcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check LC Fast Over Slow ... +bool XCHMAIsLCFastOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsOver( + xCHMALcFastBuffer, + xCHMALcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check LC Fast Crossed Under Slow ... +bool XCHMAIsLCFastCrossedUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossUnder( + xCHMALcFastBuffer, + xCHMALcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check LC Fast Under Slow ... +bool XCHMAIsLCFastUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsUnder( + xCHMALcFastBuffer, + xCHMALcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Get Trend Power ... +double XCHMAGetLCTrendPower( + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + MathAbs(xCHMALcFastBuffer[bar_index] - xCHMALcSlowBuffer[bar_index]) + // + ; + + // + return result; +} + +// +// Check XTM TrendsDown or Up ... +bool XCHMAIsLCTrendsUp( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetLCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetLCTrendPower(i + 1); + double iTrend = XCHMAGetLCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsUpCount > trendsDownCount + // + ; + + // + return result; +} + +// +// Check XTM TrendsDown or Up ... +bool XCHMAIsLCTrendsDown( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetLCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetLCTrendPower(i + 1); + double iTrend = XCHMAGetLCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsDownCount > trendsUpCount + // + ; + + // + return result; +} + +// +// Medium Cycle ... +// + +// +// Check MC is Peak ... +bool XCHMAIsMCPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsIncreasing( + bar_index + length, + bar_index, + xCHMAMcSlowBuffer + // + ); + + // + return result; +} + +// +// Check MC is Vale ... +bool XCHMAIsMCVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xCHMAMcSlowBuffer + // + ); + + // + return result; +} + +// +// Check MC Fast Crossed Over Slow ... +bool XCHMAIsMCFastCrossedOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossOver( + xCHMAMcFastBuffer, + xCHMAMcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check MC Fast Over Slow ... +bool XCHMAIsMCFastOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsOver( + xCHMAMcFastBuffer, + xCHMAMcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check MC Fast Crossed Under Slow ... +bool XCHMAIsMCFastCrossedUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossUnder( + xCHMAMcFastBuffer, + xCHMAMcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check MC Fast Under Slow ... +bool XCHMAIsMCFastUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsUnder( + xCHMAMcFastBuffer, + xCHMAMcSlowBuffer, + bar_index); + + // + return result; +} + +// +// Get Trend Power ... +double XCHMAGetMCTrendPower( + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + MathAbs(xCHMAMcFastBuffer[bar_index] - xCHMAMcSlowBuffer[bar_index]) + // + ; + + // + return result; +} + +// +// Check XTM TrendsDown or Up ... +bool XCHMAIsMCTrendsUp( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetMCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetMCTrendPower(i + 1); + double iTrend = XCHMAGetMCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsUpCount > trendsDownCount + // + ; + + // + return result; +} + +// +// Check XTM TrendsDown or Up ... +bool XCHMAIsMCTrendsDown( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetMCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetMCTrendPower(i + 1); + double iTrend = XCHMAGetMCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsDownCount > trendsUpCount + // + ; + + // + return result; +} + +// +// Short Cycle ... +// + +// +// Check SC is Peak ... +bool XCHMAIsSCPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsIncreasing( + bar_index + length, + bar_index, + xCHMAScSlowBuffer + // + ); + + // + return result; +} + +// +// Check SC is Vale ... +bool XCHMAIsSCVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xCHMAScSlowBuffer + // + ); + + // + return result; +} + +// +// Check SC Fast Crossed Over Slow ... +bool XCHMAIsSCFastCrossedOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossOver( + xCHMAScFastBuffer, + xCHMAScSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check SC Fast Over Slow ... +bool XCHMAIsSCFastOverSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsOver( + xCHMAScFastBuffer, + xCHMAScSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check SC Fast Crossed Under Slow ... +bool XCHMAIsSCFastCrossedUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossUnder( + xCHMAScFastBuffer, + xCHMAScSlowBuffer, + bar_index); + + // + return result; +} + +// +// Check SC Fast Under Slow ... +bool XCHMAIsSCFastUnderSlow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsUnder( + xCHMAScFastBuffer, + xCHMAScSlowBuffer, + bar_index); + + // + return result; +} + +// +// Get SC Trend Power ... +double XCHMAGetSCTrendPower( + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + MathAbs(xCHMAScFastBuffer[bar_index] - xCHMAScSlowBuffer[bar_index]) + // + ; + + // + return result; +} + +// +// Check SC Trends Up ... +bool XCHMAIsSCTrendsUp( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetSCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetSCTrendPower(i + 1); + double iTrend = XCHMAGetSCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsUpCount > trendsDownCount + // + ; + + // + return result; +} + +// +// Check SC Trends Down ... +bool XCHMAIsSCTrendsDown( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + length + 2)) + { + return result; + } + + // + double trend1 = XCHMAGetSCTrendPower(bar_index); + + // + int trendsUpCount = 0; + int trendsDownCount = 0; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iPrevTrend = XCHMAGetSCTrendPower(i + 1); + double iTrend = XCHMAGetSCTrendPower(i); + + // + if ( + trend1 > iTrend && + iTrend >= iPrevTrend && + trend1 >= iPrevTrend) + { + trendsUpCount++; + } + else if ( + trend1 < iTrend && + iTrend <= iPrevTrend && + trend1 <= iPrevTrend) + { + trendsDownCount++; + } + } + + // + result = + // + trendsDownCount > trendsUpCount + // + ; + + // + return result; +} + +// +// Utility Functions ... +// + +// +// Check a Cycle is Over of Another ... +bool XCHMAIsCycleOverAnother( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES sourceCycle, // Specified Cycle ... + ENUM_XCHMA_CYCLES destCycle // Specified Cycle ... +) +{ + // + bool result = false; + + // + // Validate BufferSize ... + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double sourceMinValue = XCHMAGetCycleMinValue(bar_index, sourceCycle); + double destMaxValue = XCHMAGetCycleMaxValue(bar_index, destCycle); + + // + result = + // + sourceMinValue > destMaxValue + // + ; + + // + return result; +} + +// +// Check a Cycle is Under of Another ... +bool XCHMAIsCycleUnderAnother( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES sourceCycle, // Specified Cycle ... + ENUM_XCHMA_CYCLES destCycle // Specified Cycle ... +) +{ + // + bool result = false; + + // + // Validate BufferSize ... + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double sourceMaxValue = XCHMAGetCycleMaxValue(bar_index, sourceCycle); + double destMinValue = XCHMAGetCycleMinValue(bar_index, destCycle); + + // + result = + // + sourceMaxValue < destMinValue + // + ; + + // + return result; +} + +// +// Get Cycle Min Value ... +double XCHMAGetCycleMinValue( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES cycle // Specified Cycle ... +) +{ + // + double result = 0; + + // + // Validate BufferSize ... + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + switch (cycle) + { + // + case X_XCHMA_CYCLE_LONG: + result = MathMin( + xCHMALcFastBuffer[bar_index], + xCHMALcSlowBuffer[bar_index]); + break; + + // + case X_XCHMA_CYCLE_MEDIUM: + result = MathMin( + xCHMAMcFastBuffer[bar_index], + xCHMAMcSlowBuffer[bar_index]); + break; + + // + case X_XCHMA_CYCLE_SHORT: + result = MathMin( + xCHMAScFastBuffer[bar_index], + xCHMAScSlowBuffer[bar_index]); + break; + } + + // + return result; +} + +// +// Get Cycles Min Value ... +double XCHMAGetCyclesMinValue( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES &cycle[] // Specified Cycles ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + // + bar_index <= 0 || + ArraySize(cycle) <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1) + // + ) + { + return result; + } + + // + // Loop Through Cycles ... + for (int i = 0; i < ArraySize(cycle); i++) + { + // + ENUM_XCHMA_CYCLES iCycle = cycle[i]; + double iValue = XCHMAGetCycleMinValue( + bar_index, + iCycle); + + // + result = result == 0 || result > iValue ? iValue : result; + } + + // + return result; +} + +// +// Get Cycle Max Value ... +double XCHMAGetCycleMaxValue( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES cycle // Specified Cycle ... +) +{ + // + double result = 0; + + // + // Validate BufferSize ... + if ( + bar_index <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + switch (cycle) + { + // + case X_XCHMA_CYCLE_LONG: + result = MathMax( + xCHMALcFastBuffer[bar_index], + xCHMALcSlowBuffer[bar_index]); + break; + + // + case X_XCHMA_CYCLE_MEDIUM: + result = MathMax( + xCHMAMcFastBuffer[bar_index], + xCHMAMcSlowBuffer[bar_index]); + break; + + // + case X_XCHMA_CYCLE_SHORT: + result = MathMax( + xCHMAScFastBuffer[bar_index], + xCHMAScSlowBuffer[bar_index]); + break; + } + + // + return result; +} + +// +// Get Cycles Max Value ... +double XCHMAGetCyclesMaxValue( + int bar_index, // Specified Index ... + ENUM_XCHMA_CYCLES &cycle[] // Specified Cycles ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + // + bar_index <= 0 || + ArraySize(cycle) <= 0 || + !XCHMAIsValidBuffersSize(bar_index + 1) + // + ) + { + return result; + } + + // + // Loop Through Cycles ... + for (int i = 0; i < ArraySize(cycle); i++) + { + // + ENUM_XCHMA_CYCLES iCycle = cycle[i]; + double iValue = XCHMAGetCycleMaxValue( + bar_index, + iCycle); + + // + result = result == 0 || result < iValue ? iValue : result; + } + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XCHMAIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xCHMALcFastBuffer) < size || + ArraySize(xCHMALcSlowBuffer) < size || + // + ArraySize(xCHMAMcFastBuffer) < size || + ArraySize(xCHMAMcSlowBuffer) < size || + // + ArraySize(xCHMAScFastBuffer) < size || + ArraySize(xCHMAScSlowBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// Add Specified Object to it's correspond Buffer ... +void Add( + ENUM_XCHMA_CYCLES item, + ENUM_XCHMA_CYCLES &buffer[]) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// END XCHMA Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..19d3417c --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xfi.oscillator.helper.lib.mq5 @@ -0,0 +1,358 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XFI Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XFI Oscillator"; + +// // +// input int xFILength = 18; // Market Length +// input ENUM_MA_METHOD xFIMethod = MODE_SMA; // MA Method +// input ENUM_APPLIED_VOLUME xFIAppliedTo = VOLUME_TICK; // Applied To + +// +// Configurations ... +int xFILength = 18; // Market Length +ENUM_MA_METHOD xFIMethod = MODE_SMA; // MA Method +ENUM_APPLIED_VOLUME xFIAppliedTo = VOLUME_TICK; // Applied To + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xFIHandler = INVALID_HANDLE; +double xFIBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XFIValidateInputs() +{ + // + bool result = false; + + // + result = xFILength > 2; + + // + if (!result) + { + // + LogMessage("XFI Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XFIInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XFI Handler ... + ArraySetAsSeries(xFIBuffer, true); + xFIHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xfi.oscillator", + // + // Inputs ... + xFILength, + xFIMethod, + xFIAppliedTo + // + ); + if (xFIHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XFI Oscillator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XFIReleaseHandlers() +{ + IndicatorRelease(xFIHandler); +} + +// +// Handle Reading Buffers ... +void XFIReadBuffers( + int xFIItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XFI Signal ... + CopyBuffer( + xFIHandler, + 0, + 0, + xFIItemsPerTick, + xFIBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XFI Custom Functions ... +// + +// +// Check SC is Peak ... +bool XFIIsPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XFIIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xFIBuffer + // + ); + + // + return result; +} + +// +// Check SC is Vale ... +bool XFIIsVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XFIIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xFIBuffer + // + ); + + // + return result; +} + +// +// Detect XFI Crossed Over Zero ... +bool XFIIsCrossedOverZero( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XFIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xFIBuffer[bar_index] > 0 && + xFIBuffer[bar_index + 1] <= 0; + + // + return result; +} + +// +// Detect XFI Over Zero ... +bool XFIIsOverZero( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XFIIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + xFIBuffer[bar_index] > 0; + + // + return result; +} + +// +// Detect XFI Crossed Under Zero ... +bool XFIIsCrossedUnderZero( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XFIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xFIBuffer[bar_index] < 0 && + xFIBuffer[bar_index + 1] >= 0; + + // + return result; +} + +// +// Detect XFI Under Zero ... +bool XFIIsUnderZero( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XFIIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + xFIBuffer[bar_index] < 0; + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XFIIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xFIBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XFI Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 new file mode 100644 index 00000000..e6a92f65 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xlh.indicator.helper.lib.mq5 @@ -0,0 +1,668 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XLH Indicator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XLH Indicator Buffer Lines ... +enum ENUM_X_XLH_BUFFER_LINES +{ + X_XLH_HH_LINE = 0, + X_XLH_LL_LINE = 1, + X_XLH_SIGNAL_LINE = 2, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XLH Indicator"; + +// input int xLHLength = 72; // Length +// input ENUM_SERIESMODE xLHHHMode = MODE_HIGH; // Highest High Calculation Method +// input ENUM_SERIESMODE xLHLLMode = MODE_LOW; // Lowest Low Calculation Method + +// +// Configurations ... +int xLHLength = 72; // Length +ENUM_SERIESMODE xLHHHMode = MODE_HIGH; // Highest High Calculation Method +ENUM_SERIESMODE xLHLLMode = MODE_LOW; // Lowest Low Calculation Method + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +// +int xLHHandler = INVALID_HANDLE; + +// +double xLHHHBuffer[]; +double xLHLLBuffer[]; +double xLHSignalBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XLHValidateInputs() +{ + // + bool result = false; + + // + result = xLHLength >= 2; + + // + if (!result) + { + // + LogMessage("XLH Indicator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Indicators ... +bool XLHInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XLH Handler ... + ArraySetAsSeries(xLHHHBuffer, true); + ArraySetAsSeries(xLHLLBuffer, true); + ArraySetAsSeries(xLHSignalBuffer, true); + + // + xLHHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xlh.indicator", + // + // Inputs ... + xLHLength, + xLHHHMode, + xLHLLMode + // + ); + if (xLHHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XLH Indicator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Indicators ... +void XLHReleaseHandlers() +{ + IndicatorRelease(xLHHandler); +} + +// +// Handle Reading Buffers ... +void XLHReadBuffers( + int xLHItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // HH Buffer ... + CopyBuffer( + xLHHandler, + X_XLH_HH_LINE, + 0, + xLHItemsPerTick, + xLHHHBuffer + // + ); + + // + // LL Buffer ... + CopyBuffer( + xLHHandler, + X_XLH_LL_LINE, + 0, + xLHItemsPerTick, + xLHLLBuffer + // + ); + + // + // Signal Buffer ... + CopyBuffer( + xLHHandler, + X_XLH_SIGNAL_LINE, + 0, + xLHItemsPerTick, + xLHSignalBuffer + // + ); +} + +// +// END Handler Funcions ... +// + +// +// START XLH Custom Functions ... +// + +// +// TODO: What we have to Implement ... +// - [] + +// +// Check Candle High is HH ... +bool XLHIsHighAttachedHH( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + XOHCL candle = GetCandle(bar_index); + + // + result = + // + candle.high == xLHHHBuffer[bar_index] + // + ; + + // + return result; +} + +// +// Check Candle Low is LL ... +bool XLHIsLowAttachedLL( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + XOHCL candle = GetCandle(bar_index); + + // + result = + // + candle.low == xLHLLBuffer[bar_index] + // + ; + + // + return result; +} + +// +// Check Price Jumping Up Signal ... +bool XLHIsPriceCrossedOverSignal( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + XOHCL candle1 = GetCandle(bar_index); + XOHCL candle2 = GetCandle(bar_index + 1); + + // + result = + // + candle1.low > xLHSignalBuffer[bar_index] && + candle2.low < xLHSignalBuffer[bar_index + 1] + // + ; + + // + return result; +} + +// +// Check Price Over Signal ... +bool XLHIsPriceOverSignal( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + XOHCL candle1 = GetCandle(bar_index); + + // + result = + // + candle1.low > xLHSignalBuffer[bar_index] + // + ; + + // + return result; +} + +// +// Check Price Jumping Down Signal ... +bool XLHIsPriceCrossedUnderSignal( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + XOHCL candle1 = GetCandle(bar_index); + XOHCL candle2 = GetCandle(bar_index + 1); + + // + result = + // + candle1.high < xLHSignalBuffer[bar_index] && + candle2.high > xLHSignalBuffer[bar_index + 1] + // + ; + + // + return result; +} + +// +// Check Price Down Signal ... +bool XLHIsPriceUnderSignal( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + XOHCL candle1 = GetCandle(bar_index); + + // + result = + // + candle1.high < xLHSignalBuffer[bar_index] + // + ; + + // + return result; +} + +// +// Check Price Ranging Signal ... +bool XLHIsPriceInSignalRange( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + XOHCL candle1 = GetCandle(bar_index); + + // + result = + // + candle1.high > xLHSignalBuffer[bar_index] && + candle1.low < xLHSignalBuffer[bar_index] + // + ; + + // + return result; +} + +// +// Check HH Increased ... +bool XLHIsHHIncreased( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsIncreasing( + bar_index + length, + bar_index, + xLHHHBuffer + // + ); + + // + return result; +} + +// +// Check HH Decreased ... +bool XLHIsHHDecreased( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xLHHHBuffer + // + ); + + // + return result; +} + +// +// Check LL Increased ... +bool XLHIsLLIncreased( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsIncreasing( + bar_index + length, + bar_index, + xLHLLBuffer + // + ); + + // + return result; +} + +// +// Check LL Decreased ... +bool XLHIsLLDecreased( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xLHLLBuffer + // + ); + + // + return result; +} + +// +// Check HH Same in Length ... +bool XLHIsHHSameInLength( + int bar_index, // Specified Index ... + int length = 5 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + double value1 = xLHHHBuffer[bar_index]; + + // + // Loop ... + result = true; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iValue = xLHHHBuffer[i]; + if (iValue != value1) + { + // + result = false; + + // + break; + } + } + + // + return result; +} + +// +// Check LL Same in Length ... +bool XLHIsLLSameInLength( + int bar_index, // Specified Index ... + int length = 5 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XLHIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + double value1 = xLHLLBuffer[bar_index]; + + // + // Loop ... + result = true; + for (int i = bar_index + 1; i < bar_index + length + 1; i++) + { + // + double iValue = xLHLLBuffer[i]; + if (iValue != value1) + { + // + result = false; + + // + break; + } + } + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XLHIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xLHHHBuffer) < size || + ArraySize(xLHLLBuffer) < size || + ArraySize(xLHSignalBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XLH Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 new file mode 100644 index 00000000..f90f15b2 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xobd.indicator.helper.lib.mq5 @@ -0,0 +1,249 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XOBD Indicator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XOBD Indicator"; + +// input int xOBDLength = 5; // Swing Length +// input uchar xOBDSwingHighArrowCode = 108; // Swing High Arrow Code +// input color xOBDSwingHighArrowColor = clrMagenta; // Swing High Arrow Color +// input uchar xOBDSwingLowArrowCode = 108; // Swing Low Arrow Code +// input color xOBDSwingLowArrowColor = clrAqua; // Swing Low Arrow Color + +// +// Configurations ... +int xOBDLength = 5; // Swing Length +uchar xOBDSwingHighArrowCode = 108; // Swing High Arrow Code +color xOBDSwingHighArrowColor = clrMagenta; // Swing High Arrow Color +uchar xOBDSwingLowArrowCode = 108; // Swing Low Arrow Code +color xOBDSwingLowArrowColor = clrAqua; // Swing Low Arrow Color + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +// +int xOBDHandler = INVALID_HANDLE; + +// +double xOBDBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XOBDValidateInputs() +{ + // + bool result = false; + + // + result = xOBDLength >= 2; + + // + if (!result) + { + // + LogMessage("XOBD Indicator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Indicators ... +bool XOBDInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XOBD Handler ... + ArraySetAsSeries(xOBDBuffer, true); + + // + xOBDHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xobd.indicator", + // + // Inputs ... + xOBDLength, + xOBDSwingHighArrowCode, + xOBDSwingHighArrowColor, + xOBDSwingLowArrowCode, + xOBDSwingLowArrowColor + // + ); + if (xOBDHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XOBD Indicator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Indicators ... +void XOBDReleaseHandlers() +{ + IndicatorRelease(xOBDHandler); +} + +// +// Handle Reading Buffers ... +void XOBDReadBuffers( + int xOBDItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // OBD Buffer ... + CopyBuffer( + xOBDHandler, + 0, + 0, + xOBDItemsPerTick, + xOBDBuffer + // + ); +} + +// +// END Handler Funcions ... +// + +// +// START XOBD Custom Functions ... +// + +// +// Check is Swing Low Occured or not ... +bool XOBDIsSwingLow( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XOBDIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = xOBDBuffer[bar_index] == X_SWING_LOW; + + // + return result; +} + +// +// Check is Swing High Occured or not ... +bool XOBDIsSwingHigh( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XOBDIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = xOBDBuffer[bar_index] == X_SWING_HIGH; + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XOBDIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xOBDBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XOBD Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..e6971b7a --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xrsi.oscillator.helper.lib.mq5 @@ -0,0 +1,433 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XRSI Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XRSI Oscillator Buffer Lines ... +// + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XRSI Oscillator"; + +// // +// input group "XRSI Market"; +// input int xRSILength = 18; // Market Length +// input ENUM_APPLIED_PRICE xRSIAppliedTo = PRICE_OPEN; // Applied To + +// // +// input group "XRSI Short Entry"; +// input double xRSIShortEntryValue = 70; // Short Entry Level +// input color xRSIShortEntryColor = clrRed; // Short Entry Level Color +// input ENUM_LINE_STYLE xRSIShortEntryLineStyle = STYLE_SOLID; // Short Entry Style + +// // +// input group "XRSI Short Exit"; +// input double xRSIShortExitValue = 40; // Short Exit Level +// input color xRSIShortExitColor = clrRed; // Short Exit Level Color +// input ENUM_LINE_STYLE xRSIShortExitLineStyle = STYLE_DOT; // Short Exit Style + +// // +// input group "XRSI Long Entry"; +// input double xRSILongEntryValue = 30; // Long Entry Level +// input color xRSILongEntryColor = clrRed; // Long Entry Level Color +// input ENUM_LINE_STYLE xRSILongEntryLineStyle = STYLE_SOLID; // Long Entry Style + +// // +// input group "XRSI Long Exit"; +// input double xRSILongExitValue = 60; // Long Exit Level +// input color xRSILongExitColor = clrRed; // Long Exit Level Color +// input ENUM_LINE_STYLE xRSILongExitLineStyle = STYLE_DOT; // Long Exit Style + +// +// Configurations ... +int xRSILength = 18; // Market Length +ENUM_APPLIED_PRICE xRSIAppliedTo = PRICE_OPEN; // Applied To + +// +double xRSIShortEntryValue = 70; // Short Entry Level +color xRSIShortEntryColor = clrRed; // Short Entry Level Color +ENUM_LINE_STYLE xRSIShortEntryLineStyle = STYLE_SOLID; // Short Entry Style + +// +double xRSIShortExitValue = 40; // Short Exit Level +color xRSIShortExitColor = clrRed; // Short Exit Level Color +ENUM_LINE_STYLE xRSIShortExitLineStyle = STYLE_DOT; // Short Exit Style + +// +double xRSILongEntryValue = 30; // Long Entry Level +color xRSILongEntryColor = clrRed; // Long Entry Level Color +ENUM_LINE_STYLE xRSILongEntryLineStyle = STYLE_SOLID; // Long Entry Style + +// +double xRSILongExitValue = 60; // Long Exit Level +color xRSILongExitColor = clrRed; // Long Exit Level Color +ENUM_LINE_STYLE xRSILongExitLineStyle = STYLE_DOT; // Long Exit Style + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xRSIHandler = INVALID_HANDLE; +double xRSIBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XRSIValidateInputs() +{ + // + bool result = false; + + // + result = + xRSILongEntryValue < xRSILongExitValue && + xRSIShortEntryValue > xRSIShortExitValue && + xRSIShortEntryValue > xRSILongExitValue && + xRSIShortExitValue < xRSILongExitValue; + + // + if (!result) + { + // + LogMessage("XRSI Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XRSIInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XRSI Handler ... + ArraySetAsSeries(xRSIBuffer, true); + xRSIHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xrsi.oscillator", + // + // Inputs ... + // + // Market ... + "", + xRSILength, + xRSIAppliedTo, + // + // Short Entry ... + "", + xRSIShortEntryValue, + xRSIShortEntryColor, + xRSIShortEntryLineStyle, + // + // Short Exit ... + "", + xRSIShortExitValue, + xRSIShortExitColor, + xRSIShortExitLineStyle, + // + // Long Entry ... + "", + xRSILongEntryValue, + xRSILongEntryColor, + xRSILongEntryLineStyle, + // + // Long Exit ... + "", + xRSILongExitValue, + xRSILongExitColor, + xRSILongExitLineStyle + // + ); + if (xRSIHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XRSI Oscillator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XRSIReleaseHandlers() +{ + IndicatorRelease(xRSIHandler); +} + +// +// Handle Reading Buffers ... +void XRSIReadBuffers( + int xRSIItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XRSI Signal ... + CopyBuffer( + xRSIHandler, + 0, + 0, + xRSIItemsPerTick, + xRSIBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XRSI Custom Functions ... +// + +// +// Check SC is Peak ... +bool XRSIIsPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xRSIBuffer + // + ); + + // + return result; +} + +// +// Check SC is Vale ... +bool XRSIIsVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xRSIBuffer + // + ); + + // + return result; +} + +// +// RSI Value GO Up from Long Entry ... +bool XRSIIsCrossedOverLongEntry( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xRSIBuffer[bar_index + 1] > xRSILongEntryValue && + xRSIBuffer[bar_index + 2] <= xRSILongEntryValue; + + // + return result; +} + +// +// RSI Value GO Up from Long Exit ... +bool XRSIIsCrossedOverLongExit( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xRSIBuffer[bar_index + 1] > xRSILongExitValue && + xRSIBuffer[bar_index + 2] <= xRSILongExitValue; + + // + return result; +} + +// +// RSI Value Go Down Short Entry ... +bool XRSIIsCrossedUnderShortEntry( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xRSIBuffer[bar_index + 1] < xRSIShortEntryValue && + xRSIBuffer[bar_index + 2] >= xRSIShortEntryValue; + + // + return result; +} + +// +// RSI Value Go Down Short Exit ... +bool XRSIIsCrossedUnderShortExit( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XRSIIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + xRSIBuffer[bar_index + 1] < xRSIShortExitValue && + xRSIBuffer[bar_index + 2] >= xRSIShortExitValue; + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XRSIIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xRSIBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XRSI Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..6286228b --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xtd.oscillator.helper.lib.mq5 @@ -0,0 +1,931 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XTD Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XTD Oscillator States ... +enum ENUM_X_XTD_STATES +{ + X_XTD_BULLISH_CROSSED_OVER_BEARISH = 2, + X_XTD_BULLISH_OVER_BEARISH = 1, + X_XTD_NEUTURAL = 0, + X_XTD_BULLISH_UNDER_BEARISH = -1, + X_XTD_BULLISH_CROSSED_UNDER_BEARISH = -2 +}; + +// +// XTD Oscillator Buffer Lines ... +enum ENUM_X_XTD_BUFFER_LINES +{ + X_XTD_BULLISH_POWER_LINE = 0, + X_XTD_BEARISH_POWER_LINE = 1, + X_XTD_SIGNAL_LINE = 2, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XTD Oscillator"; + +// input int xTDLength = 18; // Market Length +// input bool xTDDrawCrosses = false; // Draw Cross Arrows +// input uchar xTDBullishArrowCode = 228; // Cross Over Arrow Code +// input color xTDBullishArrowColor = clrAqua; // Cross Over Arrow Color +// input uchar xTDBearishArrowCode = 230; // Cross Under Arrow Code +// input color xTDBearishArrowColor = clrMagenta; // Cross Under Arrow Color + +// +// Configurations ... +int xTDLength = 18; // Market Length +bool xTDDrawCrosses = false; // Draw Cross Arrows +uchar xTDBullishArrowCode = 228; // Cross Over Arrow Code +color xTDBullishArrowColor = clrAqua; // Cross Over Arrow Color +uchar xTDBearishArrowCode = 230; // Cross Under Arrow Code +color xTDBearishArrowColor = clrMagenta; // Cross Under Arrow Color + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xTDHandler = INVALID_HANDLE; +double xTDBullishBuffer[]; +double xTDBearishBuffer[]; +double xTDSignalBuffer[]; +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XTDValidateInputs() +{ + // + bool result = false; + + // + result = xTDLength >= 2; + + // + if (!result) + { + // + LogMessage("XTD Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XTDInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XTD Handler ... + ArraySetAsSeries(xTDBullishBuffer, true); + ArraySetAsSeries(xTDBearishBuffer, true); + ArraySetAsSeries(xTDSignalBuffer, true); + xTDHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xtd.oscillator", + // + // Inputs ... + xTDLength, + xTDDrawCrosses, + xTDBullishArrowCode, + xTDBullishArrowColor, + xTDBearishArrowCode, + xTDBearishArrowColor); + if (xTDHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XTD Oscillator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XTDReleaseHandlers() +{ + IndicatorRelease(xTDHandler); +} + +// +// Handle Reading Buffers ... +void XTDReadBuffers( + int xTDItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XTD Bullish Buffer ... + CopyBuffer( + xTDHandler, + X_XTD_BULLISH_POWER_LINE, + 0, + xTDItemsPerTick, + xTDBullishBuffer); + + // + // XTD Bullish Buffer ... + CopyBuffer( + xTDHandler, + X_XTD_BEARISH_POWER_LINE, + 0, + xTDItemsPerTick, + xTDBearishBuffer); + + // + // XTD Signal Buffer ... + CopyBuffer( + xTDHandler, + X_XTD_SIGNAL_LINE, + 0, + xTDItemsPerTick, + xTDSignalBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XTD Custom Functions ... +// + +// +// Check Signal Vale ... +bool XTDIsSignalVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xTDSignalBuffer + // + ); + + // + return result; +} + +// +// Check Signal Peak ... +bool XTDIsSignalPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xTDSignalBuffer + // + ); + + // + return result; +} + +// +// Check Signal Vale ... +bool XTDIsBullishVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xTDBullishBuffer + // + ); + + // + return result; +} + +// +// Check Signal Peak ... +bool XTDIsBullishPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xTDBullishBuffer + // + ); + + // + return result; +} + +// +// Check Signal Vale ... +bool XTDIsBearishVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xTDBearishBuffer + // + ); + + // + return result; +} + +// +// Check Signal Peak ... +bool XTDIsBearishPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xTDBearishBuffer + // + ); + + // + return result; +} + +// +// Check Signal Peak ... + +// +// Check Bullish Crossed Over Bearish ... +bool XTDIsBullCrossedOverBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossOver( + xTDBullishBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Bullish Over Bearish ... +bool XTDIsBullOverBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsOver( + xTDBullishBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Bullish Crossed Under Bearish ... +bool XTDIsBullCrossedUnderBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossUnder( + xTDBullishBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Bullish Under Bearish ... +bool XTDIsBullUnderBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsUnder( + xTDBullishBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Signal Crossed Over Bearish ... +bool XTDIsSignalCrossedOverBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossOver( + xTDSignalBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Signal Over Bearish ... +bool XTDIsSignalOverBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsOver( + xTDSignalBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Signal Crossed Under Bearish ... +bool XTDIsSignalCrossedUnderBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsCrossUnder( + xTDSignalBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check Signal Under Bearish ... +bool XTDIsSignalUnderBear( + int bar_index // Specified Bar Index +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTDIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = IsUnder( + xTDSignalBuffer, + xTDBearishBuffer, + 1); + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XTDIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + ArraySize(xTDBullishBuffer) < size || + ArraySize(xTDBullishBuffer) < size || + ArraySize(xTDSignalBuffer) < size) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// Count Signal Crossed Over Bear ... +int XTDCountSignalCrossedOverBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = 0; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsSignalCrossedOverBear(i); + if (isCrossedOnI) + { + result++; + } + } + + // + return result; +} + +// +// Count Signal Crossed Under Bear ... +int XTDCountSignalCrossedUnderBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = 0; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsSignalCrossedUnderBear(i); + if (isCrossedOnI) + { + result++; + } + } + + // + return result; +} + +// +// Count Bull Crossed Over Bear ... +int XTDCountBullCrossedOverBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = 0; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsBullCrossedOverBear(i); + if (isCrossedOnI) + { + result++; + } + } + + // + return result; +} + +// +// Count Bull Crossed Under Bear ... +int XTDCountBullCrossedUnderBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = 0; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsBullCrossedUnderBear(i); + if (isCrossedOnI) + { + result++; + } + } + + // + return result; +} + +// +// Find Last Signal Crossed Over Bear ... +int XTDFindLastSignalCrossedOverBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = -1; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsSignalCrossedOverBear(i); + if (isCrossedOnI) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +// Find Last Signal Crossed Onder Bear ... +int XTDFindLastSignalCrossedUnderBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = -1; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsSignalCrossedUnderBear(i); + if (isCrossedOnI) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +// Find Last Bull Crossed Over Bear ... +int XTDFindLastBullCrossedOverBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = -1; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsBullCrossedOverBear(i); + if (isCrossedOnI) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +// Find Last Bull Crossed Under Bear ... +int XTDFindLastBullCrossedUnderBearIndex( + int bar_index // Specified Bar Index +) +{ + // + int result = -1; + + // + int count = ArraySize(xTDSignalBuffer) - 1; + if ( + bar_index <= 0 || + count <= bar_index + 1) + { + return result; + } + + // + // Loop Through ... + for (int i = bar_index + 1; i < count && result == -1; i++) + { + // + // Check Cross On i Point ... + bool isCrossedOnI = XTDIsBullCrossedUnderBear(i); + if (isCrossedOnI) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +// END XTD Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 new file mode 100644 index 00000000..a871ed42 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xtm.indicator.helper.lib.mq5 @@ -0,0 +1,598 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XTM Indicator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// XTM Indicator States ... +enum ENUM_X_XTM_STATES +{ + X_XTM_BULLISH = 1, + X_XTM_BEARISH = -1, + X_XTM_NEUTURAL = 0, +}; + +// +// XTM Indicator Buffer Lines ... +enum ENUM_X_XTM_BUFFER_LINES +{ + X_XTM_MA_LINE = 0, + X_XTM_MC_COLOR_LINE = 1, + X_XTM_STATE_LINE = 2, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// input group "XTM Indicator"; + +// input int xTMMaPeriod = 18; // Period +// input int xTMMaShift = 0; // Shift +// input ENUM_MA_METHOD xTMMaMethod = MODE_EMA; // Method +// input ENUM_APPLIED_PRICE xTMMaAppliedTo = PRICE_OPEN; // Applied To + +// +// Configurations ... +int xTMMaPeriod = 18; // Period +int xTMMaShift = 0; // Shift +ENUM_MA_METHOD xTMMaMethod = MODE_EMA; // Method +ENUM_APPLIED_PRICE xTMMaAppliedTo = PRICE_OPEN; // Applied To + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xTMHandler = INVALID_HANDLE; +double xTMMaBuffer[]; +double xTMStateBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XTMValidateInputs() +{ + // + bool result = false; + + // + result = xTMMaPeriod >= 2; + + // + if (!result) + { + // + LogMessage("XTM Indicator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Indicators ... +bool XTMInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XTM Handler ... + ArraySetAsSeries(xTMMaBuffer, true); + ArraySetAsSeries(xTMStateBuffer, true); + xTMHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xtm.indicator", + // + // Inputs ... + xTMMaPeriod, + xTMMaShift, + xTMMaMethod, + xTMMaAppliedTo); + if (xTMHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XTM Indicator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Indicators ... +void XTMReleaseHandlers() +{ + IndicatorRelease(xTMHandler); +} + +// +// Handle Reading Buffers ... +void XTMReadBuffers( + int xTMItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // Ma Buffer ... + CopyBuffer( + xTMHandler, + X_XTM_MA_LINE, + 0, + xTMItemsPerTick, + xTMMaBuffer); + + // + // State Buffer ... + CopyBuffer( + xTMHandler, + X_XTM_STATE_LINE, + 0, + xTMItemsPerTick, + xTMStateBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XTM Custom Functions ... +// + +// +// Find Peak based On this Indicator ... +bool XTMIsPeak( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + // Must Decreasing ... + bool isIncreasing = IsIncreasing( + bar_index + length, + bar_index, + xTMMaBuffer + // + ); + + // + return result; +} + +// +// Find Vale based On this Indicator ... +bool XTMIsVale( + int bar_index, // Specified Index ... + int length = 10 // Specified Length ... +) +{ + // + bool result = false; + + // + if ( + length <= 0 || + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + length + 1)) + { + return result; + } + + // + result = IsDecreasing( + bar_index + length, + bar_index, + xTMMaBuffer + // + ); + + // + return result; +} + +// +// Check TM Crossed Up ... +bool XTMIsStartBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BULLISH && + xTMStateBuffer[bar_index + 1] != X_XTM_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Up After Neutural State ... +bool XTMIsStartBullishAfterNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BULLISH && + xTMStateBuffer[bar_index + 1] == X_XTM_NEUTURAL + // + ; + + // + return result; +} + +// +// Check TM In Up State ... +bool XTMIsBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Ends Up State ... +bool XTMIsEndBullish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] != X_XTM_BULLISH && + xTMStateBuffer[bar_index + 1] == X_XTM_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Ends Up State By Neutural ... +bool XTMIsEndBullishByNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_NEUTURAL && + xTMStateBuffer[bar_index + 1] == X_XTM_BULLISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Down ... +bool XTMIsStartBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BEARISH && + xTMStateBuffer[bar_index + 1] != X_XTM_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Crossed Down After Neutural State ... +bool XTMIsStartBearishAfterNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BEARISH && + xTMStateBuffer[bar_index + 1] == X_XTM_NEUTURAL + // + ; + + // + return result; +} + +// +// Check TM In Down State ... +bool XTMIsBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Ends Down State ... +bool XTMIsEndBearish( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] != X_XTM_BEARISH && + xTMStateBuffer[bar_index + 1] == X_XTM_BEARISH + // + ; + + // + return result; +} + +// +// Check TM Ends Down State By Neutural ... +bool XTMIsEndBearishByNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_NEUTURAL && + xTMStateBuffer[bar_index + 1] == X_XTM_BEARISH + // + ; + + // + return result; +} + +// +// Check TM In Neutural State ... +bool XTMIsNeutural( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + if ( + bar_index <= 0 || + !XTMIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + // + xTMStateBuffer[bar_index] == X_XTM_NEUTURAL + // + ; + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XTMIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xTMMaBuffer) < size || + ArraySize(xTMStateBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +// END XTM Custom Functions ... +// diff --git a/Projects/XUSCHF5/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 b/Projects/XUSCHF5/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 new file mode 100644 index 00000000..875eec08 --- /dev/null +++ b/Projects/XUSCHF5/Helpers/x-saherelm.xts.oscillator.helper.lib.mq5 @@ -0,0 +1,1179 @@ +///////////////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XTS Oscillator Helper for Signal Providers +// -------------------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +///////////////////////////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Enum Definitions ... +// + +// +// Methods to Calculate TimeFrames ... +enum ENUM_X_PERIOD_METHOD +{ + // + X_PERIOD_NOTHING, + // + X_PERIOD_AUTO, + // + X_PERIOD_MANUALLY +}; + +// +// Buffer Lines ... +enum ENUM_X_XTS_BUFFER_LINES +{ + X_XTS_CURRENT_LINE = 0, + X_XTS_NEAREST_LINE = 1, + X_XTS_MEDIEST_LINE = 2, + X_XTS_FAREST_LINE = 3, +}; + +// +// Periods ... +enum ENUM_X_XTS_PERIODS +{ + // + // Current Period ... + X_XTS_PERIOD_CURRENT, + // + // Nearest Period ... + X_XTS_PERIOD_NEAREST, + // + // Mediest Period ... + X_XTS_PERIOD_MEDIEST, + // + // Farest Period ... + X_XTS_PERIOD_FAREST, +}; + +// +// END Enum Definitions ... +// + +// +// START Inputs ... +// + +// // +// input group "XTS Oscillator"; + +// // +// input group "XTS Current Period"; +// input ENUM_APPLIED_PRICE xTSCurrentAppliedTo = PRICE_CLOSE; // Current Applied To +// // +// input group "XTS Nearest Period"; +// input ENUM_X_PERIOD_METHOD xTSNearestMethod = X_PERIOD_AUTO; // How to Find Nearest Period +// input ENUM_TIMEFRAMES xTSNearestPeriod = NULL; // Nearest Time Frame +// input ENUM_APPLIED_PRICE xTSNearestAppliedTo = PRICE_CLOSE; // Nearest Applied To +// // +// input group "XTS Mediest Period"; +// input ENUM_X_PERIOD_METHOD xTSMediestMethod = X_PERIOD_AUTO; // How to Find Mediest Period +// input ENUM_TIMEFRAMES xTSMediestPeriod = NULL; // Mediest Time Frame +// input ENUM_APPLIED_PRICE xTSMediestAppliedTo = PRICE_CLOSE; // Mediest Applied To +// // +// input group "XTS Farest Period"; +// input ENUM_X_PERIOD_METHOD xTSFarestMethod = X_PERIOD_AUTO; // How to Find Farest Period +// input ENUM_TIMEFRAMES xTSFarestPeriod = NULL; // Farest Time Frame +// input ENUM_APPLIED_PRICE xTSFarestAppliedTo = PRICE_CLOSE; // Farest Applied To + +// +// Configurations ... +ENUM_APPLIED_PRICE xTSCurrentAppliedTo = PRICE_CLOSE; // Current Applied To +// +ENUM_X_PERIOD_METHOD xTSNearestMethod = X_PERIOD_AUTO; // How to Find Nearest Period +ENUM_TIMEFRAMES xTSNearestPeriod = NULL; // Nearest Time Frame +ENUM_APPLIED_PRICE xTSNearestAppliedTo = PRICE_CLOSE; // Nearest Applied To +// +ENUM_X_PERIOD_METHOD xTSMediestMethod = X_PERIOD_AUTO; // How to Find Mediest Period +ENUM_TIMEFRAMES xTSMediestPeriod = NULL; // Mediest Time Frame +ENUM_APPLIED_PRICE xTSMediestAppliedTo = PRICE_CLOSE; // Mediest Applied To +// +ENUM_X_PERIOD_METHOD xTSFarestMethod = X_PERIOD_AUTO; // How to Find Farest Period +ENUM_TIMEFRAMES xTSFarestPeriod = NULL; // Farest Time Frame +ENUM_APPLIED_PRICE xTSFarestAppliedTo = PRICE_CLOSE; // Farest Applied To + +// +// END Inputs ... +// + +// +// START Definitions ... +// + +int xTSHandler = INVALID_HANDLE; +double xTSCurrentBuffer[]; +double xTSNearestBuffer[]; +double xTSMediestBuffer[]; +double xTSFarestBuffer[]; + +// +// END Definitions ... +// + +// +// START Handler Functions ... +// + +// +// Validate Inputs ... +bool XTSValidateInputs() +{ + // + bool result = false; + + // + result = true; + + // + if (!result) + { + // + LogMessage("XTS Oscillator Inputs Validation Failed ..."); + } + + // + return result; +} + +// +// Init Oscillators ... +bool XTSInitHandlers() +{ + // + bool result = false; + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XTS Handler ... + ArraySetAsSeries(xTSCurrentBuffer, true); + ArraySetAsSeries(xTSNearestBuffer, true); + ArraySetAsSeries(xTSMediestBuffer, true); + ArraySetAsSeries(xTSFarestBuffer, true); + xTSHandler = iCustom( + _Symbol, + _Period, + "x-saherelm.xts.oscillator", + // + // Inputs ... + "", + xTSCurrentAppliedTo, + "", + xTSNearestMethod, + xTSNearestPeriod, + xTSNearestAppliedTo, + "", + xTSMediestMethod, + xTSMediestPeriod, + xTSMediestAppliedTo, + "", + xTSFarestMethod, + xTSFarestPeriod, + xTSFarestAppliedTo + // + ); + if (xTSHandler == INVALID_HANDLE) + { + // + LogMessage("failed to Initialize XTS Oscillator: " + (string)GetLastError()); + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Oscillators ... +void XTSReleaseHandlers() +{ + IndicatorRelease(xTSHandler); +} + +// +// Handle Reading Buffers ... +void XTSReadBuffers( + int xTSItemsPerTick // Number Of Reading Buffer Items Per Tick +) +{ + // + // XTS Current ... + CopyBuffer( + xTSHandler, + X_XTS_CURRENT_LINE, + 0, + xTSItemsPerTick, + xTSCurrentBuffer); + + // + // XTS Nearest ... + CopyBuffer( + xTSHandler, + X_XTS_NEAREST_LINE, + 0, + xTSItemsPerTick, + xTSNearestBuffer); + + // + // XTS Mediest ... + CopyBuffer( + xTSHandler, + X_XTS_MEDIEST_LINE, + 0, + xTSItemsPerTick, + xTSMediestBuffer); + + // + // XTS Farest ... + CopyBuffer( + xTSHandler, + X_XTS_FAREST_LINE, + 0, + xTSItemsPerTick, + xTSFarestBuffer); +} + +// +// END Handler Funcions ... +// + +// +// START XTS Custom Functions ... +// + +// +// Calculate Min Value ... +double XTSGetMinValue( + int bar_index // Specified Index ... +) +{ + // + ENUM_X_XTS_PERIODS periods[]; + XTSGetAllPeriodsEnum(periods); + + // + double result = XTSGetPeriodsMinValue( + periods, + bar_index); + + // + return result; +} + +// +// Calculate Max Value ... +double XTSGetMaxValue( + int bar_index // Specified Index ... +) +{ + // + ENUM_X_XTS_PERIODS periods[]; + XTSGetAllPeriodsEnum(periods); + + // + double result = XTSGetPeriodsMaxValue( + periods, + bar_index); + + // + return result; +} + +// +// Check if all Periods Values are Same ... +bool XTSIsAllSame( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + result = + xTSCurrentBuffer[bar_index] == xTSNearestBuffer[bar_index] && + xTSNearestBuffer[bar_index] == xTSMediestBuffer[bar_index] && + xTSMediestBuffer[bar_index] == xTSFarestBuffer[bar_index]; + + // + return result; +} + +// +// Current ... + +// +// Check Current Buffer is Min Or Not ... +bool XTSIsCurrentMin( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double minValue = XTSGetMinValue(bar_index); + + // + result = + xTSCurrentBuffer[bar_index] == minValue; + + // + return result; +} + +// +// Check Current Buffer is Max Or Not ... +bool XTSIsCurrentMax( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double maxValue = XTSGetMaxValue(bar_index); + + // + result = + xTSCurrentBuffer[bar_index] == maxValue; + + // + return result; +} + +// +// Current VS Nearest ... + +// +// Check Current Crossed Over Nearest ... +bool XTSIsCurrentCrossedOverNearest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_NEAREST, + bar_index); + + // + return result; +} + +// +// Check Current Over Nearest ... +bool XTSIsCurrentOverNearest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_NEAREST, + bar_index); + + // + return result; +} + +// +// Check Current Crossed Under Nearest ... +bool XTSIsCurrentCrossedUnderNearest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_NEAREST, + bar_index); + + // + return result; +} + +// +// Check Current Under Nearest ... +bool XTSIsCurrentUnderNearest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_NEAREST, + bar_index); + + // + return result; +} + +// +// Current VS Mediest ... + +// +// Check Current Crossed Over Mediest ... +bool XTSIsCurrentCrossedOverMediest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_MEDIEST, + bar_index); + + // + return result; +} + +// +// Check Current Over Mediest ... +bool XTSIsCurrentOverMediest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_MEDIEST, + bar_index); + + // + return result; +} + +// +// Check Current Crossed Under Mediest ... +bool XTSIsCurrentCrossedUnderMediest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_MEDIEST, + bar_index); + + // + return result; +} + +// +// Check Current Under Mediest ... +bool XTSIsCurrentUnderMediest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_MEDIEST, + bar_index); + + // + return result; +} + +// +// Current VS Farest ... + +// +// Check Current Crossed Over Farest ... +bool XTSIsCurrentCrossedOverFarest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_FAREST, + bar_index); + + // + return result; +} + +// +// Check Current Over Farest ... +bool XTSIsCurrentOverFarest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodOverAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_FAREST, + bar_index); + + // + return result; +} + +// +// Check Current Crossed Under Farest ... +bool XTSIsCurrentCrossedUnderFarest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodCrossedUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_FAREST, + bar_index); + + // + return result; +} + +// +// Check Current Under Farest ... +bool XTSIsCurrentUnderFarest( + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + result = XTSIsPeriodUnderAnother( + X_XTS_PERIOD_CURRENT, + X_XTS_PERIOD_FAREST, + bar_index); + + // + return result; +} + +// +// Globally Custom Functions ... + +// +// Check a Period Crossed Over another one ... +bool XTSIsPeriodCrossedOverAnother( + ENUM_X_XTS_PERIODS source, // Specified Source Period which Check it's Crossed ... + ENUM_X_XTS_PERIODS dest, // Specified Dest Period Which used to Check Source Crosses ... + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double sourceValue = XTSGetPeriodValue( + source, + bar_index); + double sourceValue1 = XTSGetPeriodValue( + source, + bar_index + 1); + + // + double destValue = XTSGetPeriodValue( + dest, + bar_index); + double destValue1 = XTSGetPeriodValue( + dest, + bar_index + 1); + + // + result = + sourceValue > destValue && + sourceValue1 <= destValue1; + + // + return result; +} + +// +// Check a Period Over another one ... +bool XTSIsPeriodOverAnother( + ENUM_X_XTS_PERIODS source, // Specified Source Period which Check it's Crossed ... + ENUM_X_XTS_PERIODS dest, // Specified Dest Period Which used to Check Source Crosses ... + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double sourceValue = XTSGetPeriodValue( + source, + bar_index); + + // + double destValue = XTSGetPeriodValue( + dest, + bar_index); + + // + result = + sourceValue > destValue; + + // + return result; +} + +// +// Check a Period Crossed Under another one ... +bool XTSIsPeriodCrossedUnderAnother( + ENUM_X_XTS_PERIODS source, // Specified Source Period which Check it's Crossed ... + ENUM_X_XTS_PERIODS dest, // Specified Dest Period Which used to Check Source Crosses ... + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 2)) + { + return result; + } + + // + double sourceValue = XTSGetPeriodValue( + source, + bar_index); + double sourceValue1 = XTSGetPeriodValue( + source, + bar_index + 1); + + // + double destValue = XTSGetPeriodValue( + dest, + bar_index); + double destValue1 = XTSGetPeriodValue( + dest, + bar_index + 1); + + // + result = + sourceValue < destValue && + sourceValue1 >= destValue1; + + // + return result; +} + +// +// Check a Period Under another one ... +bool XTSIsPeriodUnderAnother( + ENUM_X_XTS_PERIODS source, // Specified Source Period which Check it's Crossed ... + ENUM_X_XTS_PERIODS dest, // Specified Dest Period Which used to Check Source Crosses ... + int bar_index // Specified Index ... +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + double sourceValue = XTSGetPeriodValue( + source, + bar_index); + + // + double destValue = XTSGetPeriodValue( + dest, + bar_index); + + // + result = + sourceValue < destValue; + + // + return result; +} + +// +// Retrieve Specific Period's Value from Buffer for Specific Bar Index ... +double XTSGetPeriodValue( + ENUM_X_XTS_PERIODS period, // Specified Period to read it's Value ... + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + bar_index < 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + switch (period) + { + // + case X_XTS_PERIOD_CURRENT: + result = xTSCurrentBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_NEAREST: + result = xTSNearestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_MEDIEST: + result = xTSMediestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_FAREST: + result = xTSFarestBuffer[bar_index]; + break; + } + + // + return result; +} + +// +// Fill All Exists Periods ... +void XTSGetAllPeriodsEnum( + ENUM_X_XTS_PERIODS &result[] // Hold's Result ... +) +{ + // + CleanBuffer(result); + + // + Add( + X_XTS_PERIOD_CURRENT, + result); + + // + Add( + X_XTS_PERIOD_NEAREST, + result); + + // + Add( + X_XTS_PERIOD_MEDIEST, + result); + + // + Add( + X_XTS_PERIOD_FAREST, + result); +} + +// +// Fill All Exists Periods Except ... +void XTSGetAllPeriodsEnumExcept( + ENUM_X_XTS_PERIODS &result[], // Hold's Result ... + ENUM_X_XTS_PERIODS exception // Excepted Period ... +) +{ + // + CleanBuffer(result); + + // + ENUM_X_XTS_PERIODS allPeriods[]; + XTSGetAllPeriodsEnum(allPeriods); + int periodsCount = ArraySize(allPeriods); + if (periodsCount <= 0) + { + return; + } + + // + // Loop ... + for (int i = 0; i < periodsCount; i++) + { + // + ENUM_X_XTS_PERIODS iPeriod = allPeriods[i]; + + // + if (iPeriod != exception) + { + Add( + iPeriod, + result); + } + } +} + +// +// Fill All Exists Periods Except ... +void XTSGetAllPeriodsEnumExcept( + ENUM_X_XTS_PERIODS &result[], // Hold's Result ... + ENUM_X_XTS_PERIODS &exceptions[] // Excepted Periods ... +) +{ + // + CleanBuffer(result); + + // + ENUM_X_XTS_PERIODS allPeriods[]; + XTSGetAllPeriodsEnum(allPeriods); + int periodsCount = ArraySize(allPeriods); + if (periodsCount <= 0) + { + return; + } + + // + int exceptionsCount = ArraySize(exceptions); + + // + // Loop ... + for (int i = 0; i < periodsCount; i++) + { + // + ENUM_X_XTS_PERIODS iPeriod = allPeriods[i]; + + // + bool canAddIPeriod = false; + if (exceptionsCount <= 0) + { + canAddIPeriod = true; + } + else + { + // + // Loop through Exceptions ... + for (int j = 0; j < exceptionsCount; j++) + { + // + ENUM_X_XTS_PERIODS jException = exceptions[j]; + + // + if (iPeriod == jException) + { + // + canAddIPeriod = false; + break; + } + + // + canAddIPeriod = true; + } + } + + // + if (canAddIPeriod) + { + // + Add( + iPeriod, + result); + } + } +} + +// +// Calculate Periods Min Value ... +double XTSGetPeriodsMinValue( + ENUM_X_XTS_PERIODS &periods[], // Specified Periods ... + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + int periodsCount = ArraySize(periods); + + // + // Validate Args ... + if ( + bar_index < 0 || + periodsCount <= 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + // Loop ... + for (int i = 0; i < periodsCount; i++) + { + // + ENUM_X_XTS_PERIODS iPeriod = periods[i]; + + // + double iValue = 0; + + // + switch (iPeriod) + { + // + case X_XTS_PERIOD_CURRENT: + iValue = xTSCurrentBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_NEAREST: + iValue = xTSNearestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_MEDIEST: + iValue = xTSMediestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_FAREST: + iValue = xTSFarestBuffer[bar_index]; + break; + } + + // + // Compare iValue to result ... + result = + result == 0 || + result > iValue + ? iValue + : result; + } + + // + return result; +} + +// +// Calculate Periods Max Value ... +double XTSGetPeriodsMaxValue( + ENUM_X_XTS_PERIODS &periods[], // Specified Periods ... + int bar_index // Specified Index ... +) +{ + // + double result = 0; + + // + int periodsCount = ArraySize(periods); + + // + // Validate Args ... + if ( + bar_index < 0 || + periodsCount <= 0 || + !XTSIsValidBuffersSize(bar_index + 1)) + { + return result; + } + + // + // Loop ... + for (int i = 0; i < periodsCount; i++) + { + // + ENUM_X_XTS_PERIODS iPeriod = periods[i]; + + // + double iValue = 0; + + // + switch (iPeriod) + { + // + case X_XTS_PERIOD_CURRENT: + iValue = xTSCurrentBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_NEAREST: + iValue = xTSNearestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_MEDIEST: + iValue = xTSMediestBuffer[bar_index]; + break; + + // + case X_XTS_PERIOD_FAREST: + iValue = xTSFarestBuffer[bar_index]; + break; + } + + // + // Compare iValue to result ... + result = + result == 0 || + result < iValue + ? iValue + : result; + } + + // + return result; +} + +// +// Check all Buffers has valid Size ... +bool XTSIsValidBuffersSize( + int size // the size of buffers which min size for requirements +) +{ + // + bool result = false; + + // + if ( + size <= 0 || + // + ArraySize(xTSCurrentBuffer) < size + // + ) + { + result = false; + } + else + { + result = true; + } + + // + return result; +} + +// +void Add( + ENUM_X_XTS_PERIODS item, // Specified Item ... + ENUM_X_XTS_PERIODS &buffer[] // Specified Buffer ... +) +{ + // + int bufferSize = ArraySize(buffer); + + // + ArrayResize( + buffer, + bufferSize + 1); + + // + buffer[bufferSize] = item; +} + +void CleanBuffer( + ENUM_X_XTS_PERIODS &buffer[] // Specified Buffer ... +) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} + +// +// END XTS Custom Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/.gitkeep b/Projects/XUSCHF5/Indicators/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xama.indicator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xama.indicator.mq5 new file mode 100644 index 00000000..14d1ef70 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xama.indicator.mq5 @@ -0,0 +1,353 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XAMA Indicator +// --------------------------------------------- +// Name: XAMA +// Description: Trend Magic Indicator ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XAMA Indicator" +#property strict + +// +// START Constants ... +// +#define ShortName "XAMA" + +// +// XAMA Indicator States ... +enum ENUM_X_XAMA_STATES +{ + X_XAMA_BULLISH = 1, + X_XAMA_BEARISH = -1, + X_XAMA_NEUTURAL = 0, +}; +// +// END Constants ... +// + +// +// START Inputs ... +// +input int length = 18; // Period +input int fastEMA = 2; // Fast EMA Period +input int slowEMA = 30; // Slow EMA Period +input int maShift = 0; // Shift +input ENUM_APPLIED_PRICE appliedTo = PRICE_CLOSE; // Applied To +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// +#property indicator_chart_window + +// +#property indicator_buffers 3 +#property indicator_plots 1 + +// +// maBuffer ... +#define maBufferIndex 0 +#define maColorBufferIndex 1 +#define stateBufferIndex 2 + +double maBuffer[]; +double maColorBuffer[]; +double stateBuffer[]; + +#property indicator_label1 "XAMA" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 clrLime, clrGray, clrRed +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +int maHandler = INVALID_HANDLE; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + + // + // Initializing MA Handler ... + maHandler = iAMA( + _Symbol, + _Period, + length, + fastEMA, + slowEMA, + maShift, + appliedTo); + if (maHandler == INVALID_HANDLE) + { + // + string message = "Error Initializing Ma Handler ..."; + LogMessage(message); + + // + return INIT_FAILED; + } + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + IndicatorRelease(maHandler); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(fastEMA, slowEMA); + maxLength = MathMax(maxLength, length); + + // + // Check Calculated Bars ... + int maCalculatedBars = BarsCalculated(maHandler); + if (maCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer); + if (copiedMas <= 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + // Do Buffers Calculation ... + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + string maBufferLabel = "XAMA " + "(" + (string)length + ")"; + + // + // Ma Buffer ... + ArraySetAsSeries(maBuffer, true); + SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA); + PlotIndexSetString(maBufferIndex, PLOT_LABEL, maBufferLabel); + + // + // Ma Color Buffer ... + ArraySetAsSeries(maColorBuffer, true); + SetIndexBuffer(maColorBufferIndex, maColorBuffer, INDICATOR_COLOR_INDEX); + + // + // State Buffer ... + ArraySetAsSeries(stateBuffer, true); + SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, " ", "(", length, ")"); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers(int bar_index) +{ + // + // Requirements ... + XOHCL candle = GetCandle(bar_index); + + // + double maValue = maBuffer[bar_index]; + + // + double lineColorIndex = + maValue < candle.low ? 0 : maValue > candle.high ? 2 + : 1; + + // + // Define State Value ... + // lineColorIndex == 0 => Bullish => 1; + // lineColorIndex == 1 => Neutural => 0; + // lineColorIndex == 2 => Bearish => -1; + double stateValue = + lineColorIndex == 0 ? X_XAMA_BULLISH : lineColorIndex == 2 ? X_XAMA_BEARISH + : X_XAMA_NEUTURAL; + + // + // Set Ma Buffer Color Index ... + maColorBuffer[bar_index] = lineColorIndex; + + // + // Set State Buffer Value ... + stateBuffer[bar_index] = stateValue; +} + +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xchlh.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xchlh.oscillator.mq5 new file mode 100644 index 00000000..5c74787c --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xchlh.oscillator.mq5 @@ -0,0 +1,753 @@ +////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Cycle Channel LH Oscillator +// --------------------------------------------------- +// Name: XCHLH +// Description: detecting HH and LL based on cycles ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XCHLH Oscillator" +#property strict + +// +// START Constants ... +// +#define ShortName "XCHLH" + +// +// XCHLH Hot States ... +enum ENUM_X_XCHLH_HOT_STATES +{ + X_XCHLH_HOT_HH = 1, + X_XCHLH_NEUTURAL = 0, + X_XCHLH_HOT_LL = -1, +}; + +// +// Including Models Library ... +#include "../Libraries/x-saherelm.models.lib.mq5" +// +// END Constants ... +// + +// +// START Inputs ... +// +// +// Common ... +input group "Hot Areas"; +input bool drawHotAreas = true; // Draw Hot Areas Symbol +input uchar hotHHArrowCode = 234; // Hot HH Arrow Code +input color hotHHArrowColor = clrAqua; // Hot HH Arrow Color +input uchar hotLLArrowCode = 233; // Hot LL Arrow Code +input color hotLLArrowColor = clrFuchsia; // Hot LL Arrow Color + +// +// LC Inputs ... +input group "Long Cycle"; +input group "LC Market"; +input int lcLength = 28; // Length +input double lcThresholdInPips = 0.3; // Threshold In Pips +input ENUM_SERIESMODE lcHHMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE lcLLMode = MODE_LOW; // Lowest Low Calculation Method +input group "LC Style"; +input int lcDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE lcDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE lcDrawStyle = STYLE_DOT; // Draw Style +input color lcHHColor = clrAqua; // Highest High Color +input color lcLLColor = clrFuchsia; // Lowest Low Color +input group "LC Drawings"; +input bool lcDrawHH = true; // Draw Highest High +input bool lcDrawLL = true; // Draw Lowest Low + +// +// MC Inputs ... +input group "Medium Cycle"; +input group "MC Market"; +input int mcLength = 14; // Length +input double mcThresholdInPips = 0.3; // Threshold In Pips +input ENUM_SERIESMODE mcHHMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE mcLLMode = MODE_LOW; // Lowest Low Calculation Method +input group "MC Style"; +input int mcDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE mcDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE mcDrawStyle = STYLE_DOT; // Draw Style +input color mcHHColor = clrLime; // Highest High Color +input color mcLLColor = clrRed; // Lowest Low Color +input group "MC Drawings"; +input bool mcDrawHH = true; // Draw Highest High +input bool mcDrawLL = true; // Draw Lowest Low + +// +// SC Inputs ... +input group "Short Cycle"; +input group "SC Market"; +input int scLength = 7; // Length +input double scThresholdInPips = 0.3; // Threshold In Pips +input ENUM_SERIESMODE scHHMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE scLLMode = MODE_LOW; // Lowest Low Calculation Method +input group "SC Style"; +input int scDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE scDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE scDrawStyle = STYLE_DOT; // Draw Style +input color scHHColor = clrLightBlue; // Highest High Color +input color scLLColor = clrLightSalmon; // Lowest Low Color +input group "SC Drawings"; +input bool scDrawHH = true; // Draw Highest High +input bool scDrawLL = true; // Draw Lowest Low +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5"; + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5"; + +// +// Includes Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5"; + +// +// START Buffers ... +// +#property indicator_separate_window + +// +#property indicator_buffers 7 +#property indicator_plots 6 + +// +// LC ... +#define lcHHBufferIndex 0 +#define lcLLBufferIndex 1 + +// +double lcHHBuffer[]; +double lcLLBuffer[]; + +// +// MC ... +#define mcHHBufferIndex 2 +#define mcLLBufferIndex 3 + +// +double mcHHBuffer[]; +double mcLLBuffer[]; + +// +// SC ... +#define scHHBufferIndex 4 +#define scLLBufferIndex 5 + +// +double scHHBuffer[]; +double scLLBuffer[]; + +// +// Hot State ... +// +#define hotStateBufferIndex 6 + +// +double hotStateBuffer[]; +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + drawPrefix = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + + // + // ReDraw Chart ... + ChartRedraw(); + + // + // De Init Draw Library ... + OnDeinitDrawLibrary(); + + // + Comment(""); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(lcLength, mcLength); + maxLength = MathMax(maxLength, scLength); + + // + limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; + + // + // Main Loop ... + for (int i = limit; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + bool isLCInputsValid = + lcLength >= 4 && + lcLength > mcLength && + lcLength > scLength; + bool isMCInputsValid = + mcLength >= 4 && + mcLength > scLength && + mcLength < lcLength; + bool isSCInputsValid = + scLength >= 4 && + scLength < mcLength && + scLength < lcLength; + if ( + isLCInputsValid && + isMCInputsValid && + isSCInputsValid) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // LC ... + LCDefineBuffers(); + + // + // MC ... + MCDefineBuffers(); + + // + // SC ... + SCDefineBuffers(); + + // + // Hot State Buffer ... + HotStateDefineBuffers(); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, ""); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // LC ... + LCCalculateBuffers(bar_index); + + // + // MC ... + MCCalculateBuffers(bar_index); + + // + // SC ... + SCCalculateBuffers(bar_index); + + // + // SIGNAL ... + SignalCalculateBuffers(bar_index); + + // + // HOT State Buffer ... + HotStateCalculateBuffers(bar_index); + + // + // After all Calculations we are ready to Draw what we want ... + DrawBuffers(bar_index); +} + +// +// LC Buffers Definitions ... +void LCDefineBuffers() +{ + // + // LC HH Buffer ... + string lcHHBufferLabel = ShortName + " LC HH (" + (string)lcLength + ")"; + ENUM_DRAW_TYPE lcHHDrawType = lcDrawHH ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(lcHHBuffer, true); + SetIndexBuffer(lcHHBufferIndex, lcHHBuffer, INDICATOR_DATA); + PlotIndexSetInteger(lcHHBufferIndex, PLOT_DRAW_BEGIN, lcLength); + PlotIndexSetString(lcHHBufferIndex, PLOT_LABEL, lcHHBufferLabel); + PlotIndexSetInteger(lcHHBufferIndex, PLOT_LINE_COLOR, lcHHColor); + PlotIndexSetInteger(lcHHBufferIndex, PLOT_LINE_STYLE, lcDrawStyle); + PlotIndexSetInteger(lcHHBufferIndex, PLOT_LINE_WIDTH, lcDrawWidth); + PlotIndexSetInteger(lcHHBufferIndex, PLOT_DRAW_TYPE, lcHHDrawType); + + // + // LC LL Buffer ... + string lcLLBufferLabel = ShortName + " LC LL (" + (string)lcLength + ")"; + ENUM_DRAW_TYPE lcLLDrawType = lcDrawLL ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(lcLLBuffer, true); + SetIndexBuffer(lcLLBufferIndex, lcLLBuffer, INDICATOR_DATA); + PlotIndexSetInteger(lcLLBufferIndex, PLOT_DRAW_BEGIN, lcLength); + PlotIndexSetString(lcLLBufferIndex, PLOT_LABEL, lcLLBufferLabel); + PlotIndexSetInteger(lcLLBufferIndex, PLOT_LINE_COLOR, lcLLColor); + PlotIndexSetInteger(lcLLBufferIndex, PLOT_LINE_STYLE, lcDrawStyle); + PlotIndexSetInteger(lcLLBufferIndex, PLOT_LINE_WIDTH, lcDrawWidth); + PlotIndexSetInteger(lcLLBufferIndex, PLOT_DRAW_TYPE, lcLLDrawType); +} + +// +// MC Buffers Definitions ... +void MCDefineBuffers() +{ + // + // MC HH Buffer ... + string mcHHBufferLabel = ShortName + " MC HH (" + (string)mcLength + ")"; + ENUM_DRAW_TYPE mcHHDrawType = mcDrawHH ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(mcHHBuffer, true); + SetIndexBuffer(mcHHBufferIndex, mcHHBuffer, INDICATOR_DATA); + PlotIndexSetInteger(mcHHBufferIndex, PLOT_DRAW_BEGIN, mcLength); + PlotIndexSetString(mcHHBufferIndex, PLOT_LABEL, mcHHBufferLabel); + PlotIndexSetInteger(mcHHBufferIndex, PLOT_LINE_COLOR, mcHHColor); + PlotIndexSetInteger(mcHHBufferIndex, PLOT_LINE_STYLE, mcDrawStyle); + PlotIndexSetInteger(mcHHBufferIndex, PLOT_LINE_WIDTH, mcDrawWidth); + PlotIndexSetInteger(mcHHBufferIndex, PLOT_DRAW_TYPE, mcHHDrawType); + + // + // MC LL Buffer ... + string mcLLBufferLabel = ShortName + " MC LL (" + (string)mcLength + ")"; + ENUM_DRAW_TYPE mcLLDrawType = mcDrawLL ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(mcLLBuffer, true); + SetIndexBuffer(mcLLBufferIndex, mcLLBuffer, INDICATOR_DATA); + PlotIndexSetInteger(mcLLBufferIndex, PLOT_DRAW_BEGIN, mcLength); + PlotIndexSetString(mcLLBufferIndex, PLOT_LABEL, mcLLBufferLabel); + PlotIndexSetInteger(mcLLBufferIndex, PLOT_LINE_COLOR, mcLLColor); + PlotIndexSetInteger(mcLLBufferIndex, PLOT_LINE_STYLE, mcDrawStyle); + PlotIndexSetInteger(mcLLBufferIndex, PLOT_LINE_WIDTH, mcDrawWidth); + PlotIndexSetInteger(mcLLBufferIndex, PLOT_DRAW_TYPE, mcLLDrawType); +} + +// +// SC Buffers Definitions ... +void SCDefineBuffers() +{ + // + // SC HH Buffer ... + string scHHBufferLabel = ShortName + " SC HH (" + (string)scLength + ")"; + ENUM_DRAW_TYPE scHHDrawType = scDrawHH ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(scHHBuffer, true); + SetIndexBuffer(scHHBufferIndex, scHHBuffer, INDICATOR_DATA); + PlotIndexSetInteger(scHHBufferIndex, PLOT_DRAW_BEGIN, scLength); + PlotIndexSetString(scHHBufferIndex, PLOT_LABEL, scHHBufferLabel); + PlotIndexSetInteger(scHHBufferIndex, PLOT_LINE_COLOR, scHHColor); + PlotIndexSetInteger(scHHBufferIndex, PLOT_LINE_STYLE, scDrawStyle); + PlotIndexSetInteger(scHHBufferIndex, PLOT_LINE_WIDTH, scDrawWidth); + PlotIndexSetInteger(scHHBufferIndex, PLOT_DRAW_TYPE, scHHDrawType); + + // + // SC LL Buffer ... + string scLLBufferLabel = ShortName + " SC LL (" + (string)scLength + ")"; + ENUM_DRAW_TYPE scLLDrawType = scDrawLL ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(scLLBuffer, true); + SetIndexBuffer(scLLBufferIndex, scLLBuffer, INDICATOR_DATA); + PlotIndexSetInteger(scLLBufferIndex, PLOT_DRAW_BEGIN, scLength); + PlotIndexSetString(scLLBufferIndex, PLOT_LABEL, scLLBufferLabel); + PlotIndexSetInteger(scLLBufferIndex, PLOT_LINE_COLOR, scLLColor); + PlotIndexSetInteger(scLLBufferIndex, PLOT_LINE_STYLE, scDrawStyle); + PlotIndexSetInteger(scLLBufferIndex, PLOT_LINE_WIDTH, scDrawWidth); + PlotIndexSetInteger(scLLBufferIndex, PLOT_DRAW_TYPE, scLLDrawType); +} + +// +// Hot State Buffer ... +void HotStateDefineBuffers() +{ + // + // Hot State Buffer ... + ArraySetAsSeries(hotStateBuffer, true); + SetIndexBuffer(hotStateBufferIndex, hotStateBuffer, INDICATOR_CALCULATIONS); +} + +// +// LC Calculations ... +void LCCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // Detect Cycle HH and LL ... + int length = lcLength; + ENUM_SERIESMODE hhMode = lcHHMode; + ENUM_SERIESMODE llMode = lcLLMode; + double threshold = PipsToPrice(lcThresholdInPips); + double hh = GetHighestHigh( + length, + bar_index, + hhMode); + double hhValue = hh + threshold; + double ll = GetLowestLow( + length, + bar_index, + llMode); + double llValue = ll - threshold; + + // + lcHHBuffer[bar_index] = hhValue; + lcLLBuffer[bar_index] = llValue; +} + +// +// MC Calculations ... +void MCCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // Detect Cycle HH and LL ... + int length = mcLength; + ENUM_SERIESMODE hhMode = mcHHMode; + ENUM_SERIESMODE llMode = mcLLMode; + double threshold = PipsToPrice(mcThresholdInPips); + double hh = GetHighestHigh( + length, + bar_index, + hhMode); + double hhValue = hh + threshold; + double ll = GetLowestLow( + length, + bar_index, + llMode); + double llValue = ll - threshold; + + // + mcHHBuffer[bar_index] = hhValue; + mcLLBuffer[bar_index] = llValue; +} + +// +// SC Calculations ... +void SCCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // Detect Cycle HH and LL ... + int length = scLength; + ENUM_SERIESMODE hhMode = scHHMode; + ENUM_SERIESMODE llMode = scLLMode; + double threshold = PipsToPrice(scThresholdInPips); + double hh = GetHighestHigh( + length, + bar_index, + hhMode); + double hhValue = hh + threshold; + double ll = GetLowestLow( + length, + bar_index, + llMode); + double llValue = ll - threshold; + + // + scHHBuffer[bar_index] = hhValue; + scLLBuffer[bar_index] = llValue; +} + +// +// SIGNAL Calculations ... +void SignalCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // LC Values ... + double lcHH = lcHHBuffer[bar_index]; + double lcLL = lcLLBuffer[bar_index]; + double lcDelta = lcHH - lcLL; + double lcAvg = lcDelta / 2; + + // + // MC Values ... + double mcHH = mcHHBuffer[bar_index]; + double mcLL = mcLLBuffer[bar_index]; + double mcDelta = mcHH - mcLL; + double mcAvg = mcDelta / 2; + + // + // SC Values ... + double scHH = scHHBuffer[bar_index]; + double scLL = scLLBuffer[bar_index]; + double scDelta = scHH - scLL; + double scAvg = scDelta / 2; + + // + // Min Value ... + double minValue = MathMin( + scLL, mcLL); + minValue = MathMin( + lcLL, minValue); + + // + // Max Value ... + double maxValue = MathMin( + scHH, mcHH); + maxValue = MathMin( + lcHH, maxValue); +} + +// +// HOT State Calculate Buffers ... +void HotStateCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // LC ... + double lcHH = lcHHBuffer[bar_index]; + double lcLL = lcLLBuffer[bar_index]; + // + double lcHH1 = lcHHBuffer[bar_index + 1]; + double lcLL1 = lcLLBuffer[bar_index + 1]; + + // + // MC ... + double mcHH = mcHHBuffer[bar_index]; + double mcLL = mcLLBuffer[bar_index]; + // + double mcHH1 = mcHHBuffer[bar_index + 1]; + double mcLL1 = mcLLBuffer[bar_index + 1]; + + // + // SC ... + double scHH = scHHBuffer[bar_index]; + double scLL = scLLBuffer[bar_index]; + // + double scHH1 = scHHBuffer[bar_index + 1]; + double scLL1 = scLLBuffer[bar_index + 1]; + + // + bool isHotLLState = scLL == mcLL && mcLL == lcLL; + bool isHotLLState1 = scLL1 == mcLL1 && mcLL1 == lcLL1; + // + bool isHotHHState = scHH == mcHH && mcHH == lcHH; + bool isHotHHState1 = scHH1 == mcHH1 && mcHH1 == lcHH1; + + // + bool isHotLL = isHotLLState && !isHotLLState1; + bool isHotHH = isHotHHState && !isHotHHState1; + + // + double hotStateValue = X_XCHLH_NEUTURAL; + if (isHotHH) + { + hotStateValue = X_XCHLH_HOT_HH; + } + else if (isHotLL) + { + hotStateValue = X_XCHLH_HOT_LL; + } + + // + hotStateBuffer[bar_index] = hotStateValue; +} + +// +// Draw Buffers ... +void DrawBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // General Requirements ... + + // + // Retrieve Candle Model ... + XOHCL candle = GetCandle(bar_index); + datetime time = iTime(_Symbol, _Period, bar_index); + + // + // Draw Arrow on Hot Areas ... + if (drawHotAreas) + { + // + double hotStateValue = hotStateBuffer[bar_index]; + bool isHotHHArea = hotStateValue == 1; + bool isHotLLArea = hotStateValue == -1; + if (isHotHHArea || isHotLLArea) + { + // + bool isHH = isHotHHArea; + + // + double price = isHH ? candle.high : candle.low; + ENUM_ARROW_ANCHOR anchor = isHH ? ANCHOR_BOTTOM : ANCHOR_TOP; + color clr = isHH ? hotHHArrowColor : hotLLArrowColor; + uchar arrowCode = isHH ? hotHHArrowCode : hotLLArrowCode; + string name = "HOT " + (isHH ? "HH" : "LL") + "_" + (string)price + "_" + (string)time; + + // + DrawArrow( + 0, + name, + 0, + time, + price, + arrowCode, + anchor, + clr, + STYLE_SOLID, + 1); + } + } +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xchma.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xchma.oscillator.mq5 new file mode 100644 index 00000000..12d6c691 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xchma.oscillator.mq5 @@ -0,0 +1,1153 @@ +/////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Cycle Channel Moving Averages Oscillator +// ---------------------------------------------------------------- +// Name: XCHMA +// Description: trend detecting based on cycles ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XCHMA Oscillator" +#property strict + +// +// START Constants ... +// +#define ShortName "XCHMA" + +// +// XCHMA Oscillator Cycles State Presentation ... +enum ENUM_XCHMA_CYCLE_STATES +{ + X_XCHMA_FAST_CROSSED_OVER_SLOW = 2, + X_XCHMA_FAST_OVER_SLOW = 1, + X_XCHMA_NEUTURAL = 0, + X_XCHMA_FAST_UNDER_SLOW = -1, + X_XCHMA_FAST_CROSSED_UNDER_SLOW = -2, +}; +// +// END Constants ... +// + +// +// START Inputs ... +// +// +// Common ... +input group "Hot Areas"; +input bool drawHotAreas = true; // Draw Hot Areas Symbol +input uchar hotBullishArrowCode = 228; // Hot Bullish Arrow Code +input color hotBullishArrowColor = clrAqua; // Hot Bullish Arrow Color +input uchar hotBearishArrowCode = 230; // Hot Bearish Arrow Code +input color hotBearishArrowColor = clrFuchsia; // Hot Bearish Arrow Color + +// +// LC Inputs ... +input group "Long Cycle"; +input group "LC Market"; +input int lcFastLength = 20; // Fast Length +input int lcSlowLength = 50; // Slow Length +input ENUM_MA_METHOD lcMethod = MODE_EMA; // Calculation Method +input ENUM_APPLIED_PRICE lcAppliedTo = PRICE_CLOSE; // Applied To +input group "LC Style"; +input int lcDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE lcDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE lcDrawStyle = STYLE_DOT; // Draw Style +input color lcFastColor = clrAqua; // Fast Color +input color lcSlowColor = clrFuchsia; // Slow Color +input group "LC Drawings"; +input bool lcDrawFast = true; // Draw Fast +input bool lcDrawSlow = true; // Draw Slow +input bool lcDrawCrosses = true; // Draw Cross Lines + +// +// MC Inputs ... +input group "Medium Cycle"; +input group "MC Market"; +input int mcFastLength = 10; // Fast Length +input int mcSlowLength = 30; // Slow Length +input ENUM_MA_METHOD mcMethod = MODE_EMA; // Calculation Method +input ENUM_APPLIED_PRICE mcAppliedTo = PRICE_CLOSE; // Applied To +input group "MC Style"; +input int mcDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE mcDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE mcDrawStyle = STYLE_DOT; // Draw Style +input color mcFastColor = clrLime; // Fast Color +input color mcSlowColor = clrRed; // Slow Color +input group "MC Drawings"; +input bool mcDrawFast = true; // Draw Fast +input bool mcDrawSlow = true; // Draw Slow +input bool mcDrawCrosses = false; // Draw Cross Lines + +// +// SC Inputs ... +input group "Short Cycle"; +input group "SC Market"; +input int scFastLength = 7; // Fast Length +input int scSlowLength = 14; // Slow Length +input ENUM_MA_METHOD scMethod = MODE_EMA; // Calculation Method +input ENUM_APPLIED_PRICE scAppliedTo = PRICE_CLOSE; // Applied To +input group "SC Style"; +input int scDrawWidth = 1; // Draw Width +input ENUM_DRAW_TYPE scDrawType = DRAW_LINE; // Draw Type +input ENUM_LINE_STYLE scDrawStyle = STYLE_SOLID; // Draw Style +input color scFastColor = clrLightBlue; // Fast Color +input color scSlowColor = clrLightSalmon; // Slow Color +input group "SC Drawings"; +input bool scDrawFast = true; // Draw Fast +input bool scDrawSlow = true; // Draw Slow +input bool scDrawCrosses = false; // Draw Cross Lines +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Includes Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// START Buffers ... +// +#property indicator_separate_window + +// +#property indicator_buffers 7 +#property indicator_plots 6 + +// +// LC ... +#define lcFastBufferIndex 0 +#define lcSlowBufferIndex 1 + +// +double lcFastBuffer[]; +double lcSlowBuffer[]; + +// +// MC ... +#define mcFastBufferIndex 2 +#define mcSlowBufferIndex 3 + +// +double mcFastBuffer[]; +double mcSlowBuffer[]; + +// +// SC ... +#define scFastBufferIndex 4 +#define scSlowBufferIndex 5 + +// +double scFastBuffer[]; +double scSlowBuffer[]; + +// +// Hot State ... +// +#define hotStateBufferIndex 6 + +// +double hotStateBuffer[]; +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// LC ... +int lcFastHandler = INVALID_HANDLE; +int lcSlowHandler = INVALID_HANDLE; + +// +// MC ... +int mcFastHandler = INVALID_HANDLE; +int mcSlowHandler = INVALID_HANDLE; + +// +// SC ... +int scFastHandler = INVALID_HANDLE; +int scSlowHandler = INVALID_HANDLE; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + drawPrefix = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init All Required Handlers ... + if (!InitHandlers()) + { + return INIT_FAILED; + } + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + + // + // ReDraw Chart ... + ChartRedraw(); + + // + // De Init Draw Library ... + OnDeinitDrawLibrary(); + + // + Comment(""); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(lcFastLength, lcSlowLength); + + // + // Get Retrieved Values from indicators ... + // + // LC ... + int lcFastCalculatedBars = BarsCalculated(lcFastHandler); + int lcSlowCalculatedBars = BarsCalculated(lcSlowHandler); + + // + // MC ... + int mcFastCalculatedBars = BarsCalculated(mcFastHandler); + int mcSlowCalculatedBars = BarsCalculated(mcSlowHandler); + + // + // SC ... + int scFastCalculatedBars = BarsCalculated(scFastHandler); + int scSlowCalculatedBars = BarsCalculated(scSlowHandler); + + // + // Check Calculated Bars ... + if ( + // + // LC ... + lcFastCalculatedBars < maxLength || + lcSlowCalculatedBars < maxLength || + // + // MC ... + mcFastCalculatedBars < maxLength || + mcSlowCalculatedBars < maxLength || + // + // SC ... + scFastCalculatedBars < maxLength || + scSlowCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; + + // + // Copy Buffers from indicators ... + // + // LC ... + int lcFastCopiedItems = CopyBuffer(lcFastHandler, 0, 0, limit + 1, lcFastBuffer); + int lcSlowCopiedItems = CopyBuffer(lcSlowHandler, 0, 0, limit + 1, lcSlowBuffer); + + // + // MC ... + int mcFastCopiedItems = CopyBuffer(mcFastHandler, 0, 0, limit + 1, mcFastBuffer); + int mcSlowCopiedItems = CopyBuffer(mcSlowHandler, 0, 0, limit + 1, mcSlowBuffer); + + // + // SC ... + int scFastCopiedItems = CopyBuffer(scFastHandler, 0, 0, limit + 1, scFastBuffer); + int scSlowCopiedItems = CopyBuffer(scSlowHandler, 0, 0, limit + 1, scSlowBuffer); + + // + // Check Copied Items Number ... + if ( + // + // LC ... + lcFastCopiedItems <= 0 || + lcSlowCopiedItems <= 0 || + // + // MC ... + mcFastCopiedItems <= 0 || + mcSlowCopiedItems <= 0 || + // + // MC ... + mcFastCopiedItems <= 0 || + mcSlowCopiedItems <= 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + bool isLCInputsValid = lcFastLength >= 4 && lcSlowLength > lcFastLength; + bool isMCInputsValid = mcFastLength >= 4 && mcSlowLength > mcFastLength; + bool isSCInputsValid = scFastLength >= 4 && scSlowLength > scFastLength; + if ( + isLCInputsValid && + isMCInputsValid && + isSCInputsValid && + lcFastLength > mcFastLength && + mcFastLength > scFastLength) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // LC ... + LCDefineBuffers(); + + // + // MC ... + MCDefineBuffers(); + + // + // SC ... + SCDefineBuffers(); + + // + // Hot State Buffer ... + HotStateDefineBuffers(); +} + +// +// Init Handlers ... +bool InitHandlers() +{ + // + bool result = false; + + // + // LC ... + result = LCInitHandlers(); + if (!result) + { + return result; + } + + // + // MC ... + result = MCInitHandlers(); + if (!result) + { + return result; + } + + // + // SC ... + result = SCInitHandlers(); + if (!result) + { + return result; + } + + // + return result; +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, ""); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // HOT State Buffer ... + HotStateCalculateBuffers(bar_index); + + // + // After all Calculations we are ready to Draw what we want ... + DrawBuffers(bar_index); +} + +// +// LC Buffers Definitions ... +void LCDefineBuffers() +{ + // + // LC Fast Buffer ... + string lcFastBufferLabel = ShortName + " LC Fast (" + (string)lcFastLength + ")"; + ENUM_DRAW_TYPE lcFastDrawType = lcDrawFast ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(lcFastBuffer, true); + SetIndexBuffer(lcFastBufferIndex, lcFastBuffer, INDICATOR_DATA); + PlotIndexSetString(lcFastBufferIndex, PLOT_LABEL, lcFastBufferLabel); + PlotIndexSetInteger(lcFastBufferIndex, PLOT_LINE_COLOR, lcFastColor); + PlotIndexSetInteger(lcFastBufferIndex, PLOT_LINE_STYLE, lcDrawStyle); + PlotIndexSetInteger(lcFastBufferIndex, PLOT_LINE_WIDTH, lcDrawWidth); + PlotIndexSetInteger(lcFastBufferIndex, PLOT_DRAW_BEGIN, lcFastLength); + PlotIndexSetInteger(lcFastBufferIndex, PLOT_DRAW_TYPE, lcFastDrawType); + + // + // LC Slow Buffer ... + string lcSlowBufferLabel = ShortName + " LC Slow (" + (string)lcSlowLength + ")"; + ENUM_DRAW_TYPE lcSlowDrawType = lcDrawSlow ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(lcSlowBuffer, true); + SetIndexBuffer(lcSlowBufferIndex, lcSlowBuffer, INDICATOR_DATA); + PlotIndexSetString(lcSlowBufferIndex, PLOT_LABEL, lcSlowBufferLabel); + PlotIndexSetInteger(lcSlowBufferIndex, PLOT_LINE_COLOR, lcSlowColor); + PlotIndexSetInteger(lcSlowBufferIndex, PLOT_LINE_STYLE, lcDrawStyle); + PlotIndexSetInteger(lcSlowBufferIndex, PLOT_LINE_WIDTH, lcDrawWidth); + PlotIndexSetInteger(lcSlowBufferIndex, PLOT_DRAW_BEGIN, lcSlowLength); + PlotIndexSetInteger(lcSlowBufferIndex, PLOT_DRAW_TYPE, lcSlowDrawType); +} + +// +// MC Buffers Definitions ... +void MCDefineBuffers() +{ + // + // MC Fast Buffer ... + string mcFastBufferLabel = ShortName + " MC Fast (" + (string)mcFastLength + ")"; + ENUM_DRAW_TYPE mcFastDrawType = mcDrawFast ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(mcFastBuffer, true); + SetIndexBuffer(mcFastBufferIndex, mcFastBuffer, INDICATOR_DATA); + PlotIndexSetString(mcFastBufferIndex, PLOT_LABEL, mcFastBufferLabel); + PlotIndexSetInteger(mcFastBufferIndex, PLOT_LINE_COLOR, mcFastColor); + PlotIndexSetInteger(mcFastBufferIndex, PLOT_LINE_STYLE, mcDrawStyle); + PlotIndexSetInteger(mcFastBufferIndex, PLOT_LINE_WIDTH, mcDrawWidth); + PlotIndexSetInteger(mcFastBufferIndex, PLOT_DRAW_BEGIN, mcFastLength); + PlotIndexSetInteger(mcFastBufferIndex, PLOT_DRAW_TYPE, mcFastDrawType); + + // + // MC Slow Buffer ... + string mcSlowBufferLabel = ShortName + " MC Slow (" + (string)mcSlowLength + ")"; + ENUM_DRAW_TYPE mcSlowDrawType = mcDrawSlow ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(mcSlowBuffer, true); + SetIndexBuffer(mcSlowBufferIndex, mcSlowBuffer, INDICATOR_DATA); + PlotIndexSetString(mcSlowBufferIndex, PLOT_LABEL, mcSlowBufferLabel); + PlotIndexSetInteger(mcSlowBufferIndex, PLOT_LINE_COLOR, mcSlowColor); + PlotIndexSetInteger(mcSlowBufferIndex, PLOT_LINE_STYLE, mcDrawStyle); + PlotIndexSetInteger(mcSlowBufferIndex, PLOT_LINE_WIDTH, mcDrawWidth); + PlotIndexSetInteger(mcSlowBufferIndex, PLOT_DRAW_BEGIN, mcSlowLength); + PlotIndexSetInteger(mcSlowBufferIndex, PLOT_DRAW_TYPE, mcSlowDrawType); +} + +// +// SC Buffers Definitions ... +void SCDefineBuffers() +{ + // + // SC Fast Buffer ... + string scFastBufferLabel = ShortName + " SC Fast (" + (string)scFastLength + ")"; + ENUM_DRAW_TYPE scFastDrawType = scDrawFast ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(scFastBuffer, true); + SetIndexBuffer(scFastBufferIndex, scFastBuffer, INDICATOR_DATA); + PlotIndexSetString(scFastBufferIndex, PLOT_LABEL, scFastBufferLabel); + PlotIndexSetInteger(scFastBufferIndex, PLOT_LINE_COLOR, scFastColor); + PlotIndexSetInteger(scFastBufferIndex, PLOT_LINE_STYLE, scDrawStyle); + PlotIndexSetInteger(scFastBufferIndex, PLOT_LINE_WIDTH, scDrawWidth); + PlotIndexSetInteger(scFastBufferIndex, PLOT_DRAW_BEGIN, scFastLength); + PlotIndexSetInteger(scFastBufferIndex, PLOT_DRAW_TYPE, scFastDrawType); + + // + // SC Slow Buffer ... + string scSlowBufferLabel = ShortName + " SC Slow (" + (string)scSlowLength + ")"; + ENUM_DRAW_TYPE scSlowDrawType = scDrawSlow ? lcDrawType : DRAW_NONE; + ArraySetAsSeries(scSlowBuffer, true); + SetIndexBuffer(scSlowBufferIndex, scSlowBuffer, INDICATOR_DATA); + PlotIndexSetString(scSlowBufferIndex, PLOT_LABEL, scSlowBufferLabel); + PlotIndexSetInteger(scSlowBufferIndex, PLOT_LINE_COLOR, scSlowColor); + PlotIndexSetInteger(scSlowBufferIndex, PLOT_LINE_STYLE, scDrawStyle); + PlotIndexSetInteger(scSlowBufferIndex, PLOT_LINE_WIDTH, scDrawWidth); + PlotIndexSetInteger(scSlowBufferIndex, PLOT_DRAW_BEGIN, scSlowLength); + PlotIndexSetInteger(scSlowBufferIndex, PLOT_DRAW_TYPE, scSlowDrawType); +} + +// +// Hot State Buffer ... +void HotStateDefineBuffers() +{ + // + // Hot State Buffer ... + ArraySetAsSeries(hotStateBuffer, true); + SetIndexBuffer(hotStateBufferIndex, hotStateBuffer, INDICATOR_CALCULATIONS); +} + +// +// LC Init Handlers ... +bool LCInitHandlers() +{ + // + ResetLastError(); + + // + // LC Fast Handler ... + lcFastHandler = iMA( + _Symbol, + _Period, + lcFastLength, + 0, + lcMethod, + lcAppliedTo); + if (lcFastHandler == INVALID_HANDLE) + { + // + LogMessage("LC Fast Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + // LC Slow Handler ... + lcSlowHandler = iMA( + _Symbol, + _Period, + lcSlowLength, + 0, + lcMethod, + lcAppliedTo); + if (lcSlowHandler == INVALID_HANDLE) + { + // + LogMessage("LC Slow Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + return true; +} + +// +// MC Init Handlers ... +bool MCInitHandlers() +{ + // + ResetLastError(); + + // + // MC Fast Handler ... + mcFastHandler = iMA( + _Symbol, + _Period, + mcFastLength, + 0, + mcMethod, + mcAppliedTo); + if (mcFastHandler == INVALID_HANDLE) + { + // + LogMessage("MC Fast Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + // MC Slow Handler ... + mcSlowHandler = iMA( + _Symbol, + _Period, + mcSlowLength, + 0, + mcMethod, + mcAppliedTo); + if (mcSlowHandler == INVALID_HANDLE) + { + // + LogMessage("MC Slow Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + return true; +} + +// +// SC Init Handlers ... +bool SCInitHandlers() +{ + // + ResetLastError(); + + // + // SC Fast Handler ... + scFastHandler = iMA( + _Symbol, + _Period, + scFastLength, + 0, + scMethod, + scAppliedTo); + if (scFastHandler == INVALID_HANDLE) + { + // + LogMessage("SC Fast Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + // SC Slow Handler ... + scSlowHandler = iMA( + _Symbol, + _Period, + scSlowLength, + 0, + scMethod, + scAppliedTo); + if (scSlowHandler == INVALID_HANDLE) + { + // + LogMessage("SC Slow Indicator initialization failed: " + (string)GetLastError()); + + // + return false; + } + + // + return true; +} + +// +// LC State ... +double GetLCState( + int bar_index // Current Candle Index ... +) +{ + // + // Fast Cross Over Slow Detection ... + bool isFastCrossedOverSlow = IsCrossOver( + lcFastBuffer, + lcSlowBuffer, + bar_index); + + // + // Fast Over Slow Detection ... + bool isFastOverSlow = IsOver( + lcFastBuffer, + lcSlowBuffer, + bar_index); + + // + // Fast Cross Under Slow Detection ... + bool isFastCrossedUnderSlow = IsCrossUnder( + lcFastBuffer, + lcSlowBuffer, + bar_index); + + // + // Fast Under Slow Detection ... + bool isFastUnderSlow = IsUnder( + lcFastBuffer, + lcSlowBuffer, + bar_index); + + // + // Generate state value which represent curren bar index + // state between fast and slow lines ... + double result = X_XCHMA_NEUTURAL; + + // + // Filling state value based on Market Conditions ... + if (isFastCrossedOverSlow) + { + result = X_XCHMA_FAST_CROSSED_OVER_SLOW; + } + else if (isFastCrossedUnderSlow) + { + result = X_XCHMA_FAST_CROSSED_UNDER_SLOW; + } + else if (isFastOverSlow) + { + result = X_XCHMA_FAST_OVER_SLOW; + } + else if (isFastUnderSlow) + { + result = X_XCHMA_FAST_UNDER_SLOW; + } + + // + return result; +} + +// +// MC State ... +double GetMCState( + int bar_index // Current Candle Index ... +) +{ + // + // Fast Cross Over Slow Detection ... + bool isFastCrossedOverSlow = IsCrossOver( + mcFastBuffer, + mcSlowBuffer, + bar_index); + + // + // Fast Over Slow Detection ... + bool isFastOverSlow = IsOver( + mcFastBuffer, + mcSlowBuffer, + bar_index); + + // + // Fast Cross Under Slow Detection ... + bool isFastCrossedUnderSlow = IsCrossUnder( + mcFastBuffer, + mcSlowBuffer, + bar_index); + + // + // Fast Under Slow Detection ... + bool isFastUnderSlow = IsUnder( + mcFastBuffer, + mcSlowBuffer, + bar_index); + + // + // Generate state value which represent curren bar index + // state between fast and slow lines ... + double result = X_XCHMA_NEUTURAL; + + // + // Filling state value based on Market Conditions ... + if (isFastCrossedOverSlow) + { + result = X_XCHMA_FAST_CROSSED_OVER_SLOW; + } + else if (isFastCrossedUnderSlow) + { + result = X_XCHMA_FAST_CROSSED_UNDER_SLOW; + } + else if (isFastOverSlow) + { + result = X_XCHMA_FAST_OVER_SLOW; + } + else if (isFastUnderSlow) + { + result = X_XCHMA_FAST_UNDER_SLOW; + } + + // + return result; +} + +// +// SC State ... +double GetSCState( + int bar_index // Current Candle Index ... +) +{ + // + // Fast Cross Over Slow Detection ... + bool isFastCrossedOverSlow = IsCrossOver( + scFastBuffer, + scSlowBuffer, + bar_index); + + // + // Fast Over Slow Detection ... + bool isFastOverSlow = IsOver( + scFastBuffer, + scSlowBuffer, + bar_index); + + // + // Fast Cross Under Slow Detection ... + bool isFastCrossedUnderSlow = IsCrossUnder( + scFastBuffer, + scSlowBuffer, + bar_index); + + // + // Fast Under Slow Detection ... + bool isFastUnderSlow = IsUnder( + scFastBuffer, + scSlowBuffer, + bar_index); + + // + // Generate state value which represent curren bar index + // state between fast and slow lines ... + double result = X_XCHMA_NEUTURAL; + + // + // Filling state value based on Market Conditions ... + if (isFastCrossedOverSlow) + { + result = X_XCHMA_FAST_CROSSED_OVER_SLOW; + } + else if (isFastCrossedUnderSlow) + { + result = X_XCHMA_FAST_CROSSED_UNDER_SLOW; + } + else if (isFastOverSlow) + { + result = X_XCHMA_FAST_OVER_SLOW; + } + else if (isFastUnderSlow) + { + result = X_XCHMA_FAST_UNDER_SLOW; + } + + // + return result; +} + +// +// HOT State Calculate Buffers ... +void HotStateCalculateBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // LC ... + double lcFast = lcFastBuffer[bar_index]; + double lcSlow = lcSlowBuffer[bar_index]; + // + double lcFastPrev = lcFastBuffer[bar_index + 1]; + double lcSlowPrev = lcSlowBuffer[bar_index + 1]; + // + double lcState = GetLCState(bar_index); + + // + // MC ... + double mcFast = mcFastBuffer[bar_index]; + double mcSlow = mcSlowBuffer[bar_index]; + // + double mcFastPrev = mcFastBuffer[bar_index + 1]; + double mcSlowPrev = mcSlowBuffer[bar_index + 1]; + // + double mcState = GetMCState(bar_index); + + // + // SC ... + double scFast = scFastBuffer[bar_index]; + double scSlow = scSlowBuffer[bar_index]; + // + double scFastPrev = scFastBuffer[bar_index + 1]; + double scSlowPrev = scSlowBuffer[bar_index + 1]; + // + double scState = GetSCState(bar_index); + + // + // Detect HOT Bearish Area ... + bool isHotBearishArea = + lcFast < lcSlow && + mcFast < mcSlow && + scFast < scSlow; + // + bool isPrevHotBearishArea = + lcFastPrev < lcSlowPrev && + mcFastPrev < mcSlowPrev && + scFastPrev < scSlowPrev; + + // + // Detect HOT Bearish Area ... + bool isHotBullishArea = + lcFast > lcSlow && + mcFast > mcSlow && + scFast > scSlow; + // + bool isPrevHotBullishArea = + lcFastPrev > lcSlowPrev && + mcFastPrev > mcSlowPrev && + scFastPrev > scSlowPrev; + + // + // Generate HotState Value ... + double hotStateValue = + isHotBullishArea && !isPrevHotBullishArea + ? 1 + : isHotBearishArea && !isPrevHotBearishArea + ? -1 + : 0; + hotStateBuffer[bar_index] = hotStateValue; +} + +// +// Draw Buffers ... +void DrawBuffers( + int bar_index // Current Candle Index ... +) +{ + // + // General Requirements ... + + // + // Retrieve Candle Model ... + XOHCL candle = GetCandle(bar_index); + datetime time = iTime(_Symbol, _Period, bar_index); + + // + // Draw Arrow on Hot Areas ... + if (drawHotAreas) + { + // + double hotStateValue = hotStateBuffer[bar_index]; + bool isHotBullishArea = hotStateValue == 1; + bool isHotBearishArea = hotStateValue == -1; + if (isHotBullishArea || isHotBearishArea) + { + // + bool isBull = isHotBullishArea; + + // + double price = isBull ? candle.low : candle.high; + ENUM_ARROW_ANCHOR anchor = isBull ? ANCHOR_TOP : ANCHOR_BOTTOM; + color clr = isBull ? hotBullishArrowColor : hotBearishArrowColor; + uchar arrowCode = isBull ? hotBullishArrowCode : hotBearishArrowCode; + string name = "HOT " + (isBull ? "Bullish" : "Bearish") + "_" + (string)price + "_" + (string)time; + + // + DrawArrow( + 0, + name, + 0, + time, + price, + arrowCode, + anchor, + clr); + } + } + + // + // Draw LC Crosses ... + if (lcDrawCrosses) + { + // + double lcStateValue = GetLCState(bar_index); + bool isLcFastCrossedOverSlow = lcStateValue == X_XCHMA_FAST_CROSSED_OVER_SLOW; + bool isLcFastCrossedUnderSlow = lcStateValue == X_XCHMA_FAST_CROSSED_UNDER_SLOW; + if (isLcFastCrossedOverSlow || isLcFastCrossedUnderSlow) + { + // + bool isBull = isLcFastCrossedOverSlow; + + // + color clr = isBull ? lcFastColor : lcSlowColor; + string name = "LC Fast Cross " + (isBull ? "Over" : "Under") + "_" + (string)time; + + // + DrawVerticalLine( + 0, + name, + 0, + time, + clr); + } + } + + // + // Draw MC Crosses ... + if (mcDrawCrosses) + { + // + double mcStateValue = GetMCState(bar_index); + bool isMcFastCrossedOverSlow = mcStateValue == X_XCHMA_FAST_CROSSED_OVER_SLOW; + bool isMcFastCrossedUnderSlow = mcStateValue == X_XCHMA_FAST_CROSSED_UNDER_SLOW; + if (isMcFastCrossedOverSlow || isMcFastCrossedUnderSlow) + { + // + bool isBull = isMcFastCrossedOverSlow; + + // + color clr = isBull ? mcFastColor : mcSlowColor; + string name = "MC Fast Cross " + (isBull ? "Over" : "Under") + "_" + (string)time; + + // + DrawVerticalLine( + 0, + name, + 0, + time, + clr); + } + } + + // + // Draw SC Crosses ... + if (scDrawCrosses) + { + // + double scStateValue = GetSCState(bar_index); + bool isScFastCrossedOverSlow = scStateValue == X_XCHMA_FAST_CROSSED_OVER_SLOW; + bool isScFastCrossedUnderSlow = scStateValue == X_XCHMA_FAST_CROSSED_UNDER_SLOW; + if (isScFastCrossedOverSlow || isScFastCrossedUnderSlow) + { + // + bool isBull = isScFastCrossedOverSlow; + + // + color clr = isBull ? scFastColor : scSlowColor; + string name = "SC Fast Cross " + (isBull ? "Over" : "Under") + "_" + (string)time; + + // + DrawVerticalLine( + 0, + name, + 0, + time, + clr); + } + } +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xctimer.indicator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xctimer.indicator.mq5 new file mode 100644 index 00000000..6a064212 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xctimer.indicator.mq5 @@ -0,0 +1,206 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XCTimer Indicator +// --------------------------------------------- +// Name: XCTimer +// Description: Trend Magic Indicator ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XCTimer Indicator" +#property strict + +// +// START Constants ... +// +#define ShortName "XCTimer" +// +// END Constants ... +// + +// +// START Inputs ... +// +input color clr = clrYellow; +input ENUM_BASE_CORNER corner = CORNER_RIGHT_LOWER; +// +// END Inputs ... +// + +// +// START Buffers ... +// +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + CreateIndicatorObject(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Delete Object ... + ObjectDelete(0, ShortName); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + ArraySetAsSeries(time, true); + + // + int m = int(time[0] + PeriodSeconds() - TimeCurrent()); + int s = m % 60; + m = (m - s) / 60; + + // + long mSpread = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD); + + string _sp = "", _m = "", _s = ""; + if (mSpread < 10) + _sp = ".."; + else if (mSpread < 100) + _sp = "."; + if (m < 10) + _m = "0"; + if (s < 10) + _s = "0"; + + // + string objText = "Spread: " + IntegerToString(mSpread) + _sp + " Next Bar in " + _m + IntegerToString(m) + ":" + _s + IntegerToString(s); + + // + ObjectSetInteger(0, ShortName, OBJPROP_COLOR, clr); + ObjectSetString(0, ShortName, OBJPROP_TEXT, objText); + ObjectSetInteger(0, ShortName, OBJPROP_FONTSIZE, 10); + ObjectSetString(0, ShortName, OBJPROP_FONT, "Courier"); + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +void CreateIndicatorObject() +{ + // + ObjectCreate(0, ShortName, OBJ_LABEL, 0, 0, 0); + ObjectSetInteger(0, ShortName, OBJPROP_CORNER, corner); + ObjectSetInteger(0, ShortName, OBJPROP_XDISTANCE, 10); + ObjectSetInteger(0, ShortName, OBJPROP_YDISTANCE, 2); + ENUM_ANCHOR_POINT Anchor = ANCHOR_LEFT_UPPER; + switch (corner) + { + case CORNER_LEFT_UPPER: + Anchor = ANCHOR_LEFT_UPPER; + break; + case CORNER_RIGHT_UPPER: + Anchor = ANCHOR_RIGHT_UPPER; + break; + case CORNER_LEFT_LOWER: + Anchor = ANCHOR_LEFT_LOWER; + break; + case CORNER_RIGHT_LOWER: + Anchor = ANCHOR_RIGHT_LOWER; + break; + } + + // + ObjectSetInteger(0, ShortName, OBJPROP_ANCHOR, Anchor); +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xfi.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xfi.oscillator.mq5 new file mode 100644 index 00000000..cfd393ca --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xfi.oscillator.mq5 @@ -0,0 +1,317 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XFI Oscillator +// --------------------------------------------- +// Name: XFI +// Description: Price Momentum Power Detection +// Market Analysor ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XFI Oscillator" +#property strict + +// +// START Constants ... +// +#define ShortName "XFI" +// +// END Constants ... +// + +// +// START Inputs ... +// +input int length = 18; // Length +input ENUM_MA_METHOD method = MODE_SMA; // MA Method +input ENUM_APPLIED_VOLUME appliedTo = VOLUME_TICK; // Applied To +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// +#property indicator_separate_window + +// +#property indicator_buffers 2 +#property indicator_plots 1 + +// +// FI Buffer ... +#define fiBufferIndex 0 +#define fiColorBufferIndex 1 + +// +double fiBuffer[]; +double fiColorBuffer[]; + +// +#property indicator_label1 "XFI" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 clrAqua, clrGray, clrFuchsia +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +int fiHandler = INVALID_HANDLE; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + + // + fiHandler = iForce( + _Symbol, + _Period, + length, + method, + appliedTo); + if (fiHandler == INVALID_HANDLE) + { + // + string message = "Error Initializing Handler ..."; + LogMessage(message); + + // + return INIT_FAILED; + } + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + IndicatorRelease(fiHandler); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, length); + + // + // Check Calculated Bars ... + int fiCalculatedBars = BarsCalculated(fiHandler); + if (fiCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + int copiedFis = CopyBuffer(fiHandler, 0, 0, limit, fiBuffer); + if (copiedFis <= 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = 0; i < limit && !IsStopped(); i++) + { + // + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + string fiBufferLabel = "XFI " + "(" + (string)length + ")"; + + // + // FI Buffer ... + ArraySetAsSeries(fiBuffer, true); + SetIndexBuffer(fiBufferIndex, fiBuffer, INDICATOR_DATA); + PlotIndexSetString(fiBufferIndex, PLOT_LABEL, fiBufferLabel); + + // + // FI Color Buffer ... + ArraySetAsSeries(fiColorBuffer, true); + SetIndexBuffer(fiColorBufferIndex, fiColorBuffer, INDICATOR_COLOR_INDEX); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, ""); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Selected Bar Index +) +{ + // + double iValue = fiBuffer[bar_index]; + + // + double iColorIndex = + iValue > 0 ? 0 : iValue < 0 ? 2 + : 1; + + // + // Set Buffer Color Index ... + fiColorBuffer[bar_index] = iColorIndex; +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xlh.indicator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xlh.indicator.mq5 new file mode 100644 index 00000000..4dfc64e2 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xlh.indicator.mq5 @@ -0,0 +1,346 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XLH Indicator +// --------------------------------------------- +// Name: XLH +// Description: Moving Average Indicator +// Market Analysor ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XLH Indicator" +#property strict + +// +// START Constants ... +// +#define ShortName "XLH" +// +// END Constants ... +// + +// +// START Inputs ... +// +input int length = 14; // Length +input ENUM_SERIESMODE hhMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE llMode = MODE_LOW; // Lowest Low Calculation Method +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// +#property indicator_chart_window + +// +#property indicator_buffers 3 +#property indicator_plots 3 + +// +// HH Buffer ... +#define hhBufferIndex 0 + +// +double hhBuffer[]; + +// +#property indicator_label1 "XLH HH" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrAqua +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 + +// +// LL Buffer ... +#define llBufferIndex 1 + +// +double llBuffer[]; + +// +#property indicator_label2 "XLH LL" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrFuchsia +#property indicator_style2 STYLE_DOT +#property indicator_width2 1 + +// +// Signal Buffer ... +#define signalBufferIndex 2 + +// +double signalBuffer[]; + +// +#property indicator_label3 "XLH S" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrGold +#property indicator_style3 STYLE_DOT +#property indicator_width3 1 +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, length); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // HH Buffer ... + string hhBufferLabel = ShortName + " HH " + "(" + (string)length + ")"; + ArraySetAsSeries(hhBuffer, true); + SetIndexBuffer(hhBufferIndex, hhBuffer, INDICATOR_DATA); + PlotIndexSetInteger(hhBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(hhBufferIndex, PLOT_LABEL, hhBufferLabel); + + // + // LL Buffer ... + string llBufferLabel = ShortName + " LL " + "(" + (string)length + ")"; + ArraySetAsSeries(llBuffer, true); + SetIndexBuffer(llBufferIndex, llBuffer, INDICATOR_DATA); + PlotIndexSetInteger(llBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(llBufferIndex, PLOT_LABEL, llBufferLabel); + + // + // Signal Buffer ... + string signalBufferLabel = ShortName + " S " + "(" + (string)length + ")"; + ArraySetAsSeries(signalBuffer, true); + SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_DATA); + PlotIndexSetInteger(signalBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(signalBufferIndex, PLOT_LABEL, signalBufferLabel); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, ""); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Selected Bar Index +) +{ + // + // Calculate Threshold ... + // + // HH Buffer ... + int hhIndex = iHighest( + _Symbol, + _Period, + hhMode, + length, + bar_index); + double hhValue = GetAppliedPrice( + hhIndex, + hhMode); + + // + hhBuffer[bar_index] = hhValue; + + // + // LL Buffer ... + int llIndex = iLowest( + _Symbol, + _Period, + llMode, + length, + bar_index); + double llValue = GetAppliedPrice( + llIndex, + llMode); + + // + llBuffer[bar_index] = llValue; + + // + XOHCL c = GetCandle(bar_index); + double lhDiff = hhValue - llValue; + double signalValue = (lhDiff / 2); + + // + signalBuffer[bar_index] = (hhValue - signalValue); +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xobd.indicator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xobd.indicator.mq5 new file mode 100644 index 00000000..4ac05cf6 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xobd.indicator.mq5 @@ -0,0 +1,390 @@ +///////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 OrderBlock Detector Indicator +// ----------------------------------------------------- +// Name: XOBD +// Description: detect Order Blocks based on Swings ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XOBD Indicator" +#property strict + +// +// START Constants ... +// +#define ShortName "XOBD" +// +// END Constants ... +// + +// +// START Inputs ... +// +// +input int length = 5; // Swing Length + +// +input uchar swingHighArrowCode = 108; // Swing High Arrow Code +input color swingHighArrowColor = clrMagenta; // Swing High Arrow Color + +// +input uchar swingLowArrowCode = 108; // Swing Low Arrow Code +input color swingLowArrowColor = clrAqua; // Swing Low Arrow Color +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Include Common and Models Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Include Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// START Buffers ... +// +#property indicator_chart_window + +// +#property indicator_buffers 1 +#property indicator_plots 0 + +// +#define swingBufferIndex 0 +double swingBuffer[]; +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + drawPrefix = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + OnDeinitDrawLibrary(); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, length * 3); + + // + limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; + + // + // Main Loop ... + for (int i = limit; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + ArraySetAsSeries(swingBuffer, true); + SetIndexBuffer(swingBufferIndex, swingBuffer, INDICATOR_CALCULATIONS); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, " ", "( ", length, " )"); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers(int bar_index) +{ + // + // GetCandleSwing(bar_index); + ENUM_X_SWING_TYPE type = X_NO_SWING; + + // + // Try To Detect Order Blocks ... + bool isSwingLow = false; + bool isSwingHigh = false; + + // + // Reading Candles Data ... + XOHCL candles[]; + for (int i = bar_index; i < bar_index + ((length * 2) + 2); i++) + { + // + XOHCL iCandle = GetCandle( + _Symbol, + _Period, + i); + + // + Add( + iCandle, + candles); + } + + // + // Swing Low ... + isSwingLow = + // + candles[1].close > candles[2].close && + candles[2].close > candles[3].close && + // + candles[3].close < candles[4].close && + // + candles[5].close > candles[4].close && + candles[6].close > candles[5].close + // + ; + + // + if (isSwingLow) + { + type = X_SWING_LOW; + } + + // + if (!isSwingLow) + { + // + // Swing High ... + isSwingHigh = + // + candles[1].close < candles[2].close && + candles[2].close < candles[3].close && + // + candles[3].close > candles[4].close && + // + candles[5].close < candles[4].close && + candles[6].close < candles[5].close + // + ; + + // + if (isSwingHigh) + { + type = X_SWING_HIGH; + } + } + + // + switch (type) + { + // + // Swing High ... + case X_SWING_HIGH: + // + swingBuffer[bar_index] = type; + DrawSwingArrow(1, bar_index); + break; + + // + // Swinmg Low ... + case X_SWING_LOW: + // + swingBuffer[bar_index] = type; + DrawSwingArrow(0, bar_index); + break; + + // + // No Swing ... + default: + case X_NO_SWING: + // + swingBuffer[bar_index] = 0; + break; + } +} + +// +// Draw a Swing Arrow Shape ... +void DrawSwingArrow( + int type, // Swing Type: 0 - Low / 1 - High ... + int bar_index) +{ + // + bool isSwingHigh = type == 1; + XOHCL candle = GetCandle(bar_index + 3); + double arrowDistanceInPoint = 0; + + // + // Define Required Object Properties fro Draw an Arrow ... + datetime time = iTime(_Symbol, _Period, bar_index + 3); + double purePrice = isSwingHigh ? candle.high : candle.low; + color clr = isSwingHigh ? swingHighArrowColor : swingLowArrowColor; + ENUM_ARROW_ANCHOR anchor = isSwingHigh ? ANCHOR_BOTTOM : ANCHOR_TOP; + uchar arrowCode = uchar(isSwingHigh ? swingHighArrowCode : swingLowArrowCode); + double price = isSwingHigh ? purePrice + arrowDistanceInPoint : purePrice - arrowDistanceInPoint; + string name = "Swing " + (isSwingHigh ? "High" : "Low") + "_" + (string)time + "_" + (string)purePrice; + + // + // Draw desired Arrow ... + DrawArrow( + 0, + name, + 0, + time, + price, + arrowCode, + anchor, + clr); +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xrsi.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xrsi.oscillator.mq5 new file mode 100644 index 00000000..5659e07d --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xrsi.oscillator.mq5 @@ -0,0 +1,397 @@ +///////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 OrderBlock Detector Oscillator +// ------------------------------------------------------ +// Name: XRSI +// Description: detect market conditions based on RSI ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XRSI Oscillator" +#property strict + +// +// START Constants ... +// + +#define ShortName "XRSI" + +// +// END Constants ... +// + +// +// START Inputs ... +// + +// +input group "Market"; +input int length = 14; // Market Length +input ENUM_APPLIED_PRICE appliedTo = PRICE_CLOSE; // Applied To + +// +input group "Short Entry"; +input double shortEntryValue = 70; // Short Entry Level +input color shortEntryColor = clrRed; // Short Entry Level Color +input ENUM_LINE_STYLE shortEntryLineStyle = STYLE_DOT; // Short Entry Style + +// +input group "Short Exit"; +input double shortExitValue = 40; // Short Exit Level +input color shortExitColor = clrRed; // Short Exit Level Color +input ENUM_LINE_STYLE shortExitLineStyle = STYLE_DOT; // Short Exit Style + +// +input group "Long Entry"; +input double longEntryValue = 30; // Long Entry Level +input color longEntryColor = clrRed; // Long Entry Level Color +input ENUM_LINE_STYLE longEntryLineStyle = STYLE_DOT; // Long Entry Style + +// +input group "Long Exit"; +input double longExitValue = 60; // Long Exit Level +input color longExitColor = clrRed; // Long Exit Level Color +input ENUM_LINE_STYLE longExitLineStyle = STYLE_DOT; // Long Exit Style + +// +// START Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Include Common and Models Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// + +// +#property indicator_separate_window +#property indicator_buffers 2 +#property indicator_plots 1 + +// +#define rsiBufferIndex 0 +#define rsiColorBufferIndex 1 + +// +double rsiBuffer[]; +double rsiColorBuffer[]; + +// +#property indicator_label1 "XRSI" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 clrAqua, clrGray, clrFuchsia +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +int rsiHandler = INVALID_HANDLE; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + + // + rsiHandler = iRSI( + _Symbol, + _Period, + length, + appliedTo); + if (rsiHandler == INVALID_HANDLE) + { + return INIT_FAILED; + } + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + + // + IndicatorRelease(rsiHandler); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, length); + + // + int rsiCalculatedBars = BarsCalculated(rsiHandler); + if (rsiCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; + + // + int rsiCopiedItems = CopyBuffer(rsiHandler, 0, 0, limit, rsiBuffer); + if (rsiCopiedItems <= 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // RSI ... + string rsiBufferLabel = ShortName + " (" + (string)length + ")"; + ArraySetAsSeries(rsiBuffer, true); + SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_DATA); + PlotIndexSetInteger(rsiBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(rsiBufferIndex, PLOT_LABEL, rsiBufferLabel); + + // + // RSI Color Buffer ... + ArraySetAsSeries(rsiColorBuffer, true); + SetIndexBuffer(rsiColorBufferIndex, rsiColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Set Indicator Levels here ... + // OB, ExitLong, ExitShort, OS ... + IndicatorSetInteger(INDICATOR_LEVELS, 4); + + // + // SHORTENTRY ... + IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, shortEntryValue); + IndicatorSetInteger(INDICATOR_LEVELCOLOR, 0, shortEntryColor); + IndicatorSetInteger(INDICATOR_LEVELSTYLE, 0, shortEntryLineStyle); + IndicatorSetString(INDICATOR_LEVELTEXT, 0, "Short Entry"); + + // + // LONGEXIT ... + IndicatorSetDouble(INDICATOR_LEVELVALUE, 1, longExitValue); + IndicatorSetInteger(INDICATOR_LEVELCOLOR, 1, longExitColor); + IndicatorSetInteger(INDICATOR_LEVELSTYLE, 1, shortExitLineStyle); + IndicatorSetString(INDICATOR_LEVELTEXT, 1, "Long Exit"); + + // + // SHORTEXIT ... + IndicatorSetDouble(INDICATOR_LEVELVALUE, 2, shortExitValue); + IndicatorSetInteger(INDICATOR_LEVELCOLOR, 2, shortExitColor); + IndicatorSetInteger(INDICATOR_LEVELSTYLE, 2, longEntryLineStyle); + IndicatorSetString(INDICATOR_LEVELTEXT, 2, "Short Exit"); + + // + // LONGENTRY ... + IndicatorSetDouble(INDICATOR_LEVELVALUE, 3, longEntryValue); + IndicatorSetInteger(INDICATOR_LEVELCOLOR, 3, longEntryColor); + IndicatorSetInteger(INDICATOR_LEVELSTYLE, 3, longExitLineStyle); + IndicatorSetString(INDICATOR_LEVELTEXT, 3, "Long Entry"); + + // + // Set Maximum and Minimum for subwindow + IndicatorSetInteger(INDICATOR_DIGITS, 2); + IndicatorSetDouble(INDICATOR_MINIMUM, 0); + IndicatorSetDouble(INDICATOR_MAXIMUM, 100); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, " ", "( ", length, " )"); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers(int bar_index) +{ + // + double iValue = rsiBuffer[bar_index]; + + // + double iColorIndex = 0; + + // + if ( + iValue >= shortEntryValue || + iValue <= longEntryValue || + (iValue < longExitValue && + iValue > shortExitValue)) + { + iColorIndex = 0; + } + else if ( + iValue <= shortEntryValue && + iValue >= longExitValue) + { + iColorIndex = 2; + } + else if ( + iValue < shortExitValue && + iValue > longEntryValue) + { + iColorIndex = 1; + } + + // + rsiColorBuffer[bar_index] = iColorIndex; +} + +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xtd.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xtd.oscillator.mq5 new file mode 100644 index 00000000..5f46d187 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xtd.oscillator.mq5 @@ -0,0 +1,465 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Trend Detector Oscillator +// -------------------------------------------------- +// Name: XTD +// Description: trend detecting in both sides ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XTD Oscillator" +#property strict + +// +// START Constants ... +// +#define ShortName "XTD" + +// +// XTD Oscillator States ... +enum ENUM_X_XTD_STATES +{ + X_XTD_BULLISH_CROSSED_OVER_BEARISH = 2, + X_XTD_BULLISH_OVER_BEARISH = 1, + X_XTD_NEUTURAL = 0, + X_XTD_BULLISH_UNDER_BEARISH = -1, + X_XTD_BULLISH_CROSSED_UNDER_BEARISH = -2 +}; +// +// END Constants ... +// + +// +// Include Models Library ... +#include "../Libraries/x-saherelm.models.lib.mq5" + +// +// START Inputs ... +// +input int length = 14; // Market Length +input bool drawCrosses = true; // Draw Cross Arrows + +// +// Bullish ... +input uchar bullishArrowCode = 228; // Cross Over Arrow Code +input color bullishArrowColor = clrAqua; // Cross Over Arrow Color + +// +// Bearish ... +input uchar bearishArrowCode = 230; // Cross Under Arrow Code +input color bearishArrowColor = clrMagenta; // Cross Under Arrow Color +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5"; + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5"; + +// +// Includes Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5"; + +// +// START Buffers ... +// +#property indicator_separate_window + +// +#property indicator_buffers 3 +#property indicator_plots 3 + +// +#define bullishBufferIndex 0 +#define bearishBufferIndex 1 +#define signalBufferIndex 2 + +// +double bullishBuffer[]; +double bearishBuffer[]; +double signalBuffer[]; + +// +#property indicator_label1 "XBullPower" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrLime +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +#property indicator_label2 "XBearPower" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrRed +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +#property indicator_label3 "XSignal" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrGold +#property indicator_style3 STYLE_DOT +#property indicator_width3 1 +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +int xtdBullishCandleCount = 0; +int xtdBearishCandleCount = 0; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + drawPrefix = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + + // + // De Init Draw Library ... + OnDeinitDrawLibrary(); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, length); + + // + limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; + + // + // Main Loop ... + for (int i = limit; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i, close); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (length >= 5) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // Bullish Buffer ... + string bullishBufferLabel = ShortName + "BullPow " + "(" + (string)length + ")"; + ArraySetAsSeries(bullishBuffer, true); + SetIndexBuffer(bullishBufferIndex, bullishBuffer, INDICATOR_DATA); + PlotIndexSetInteger(bullishBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(bullishBufferIndex, PLOT_LABEL, bullishBufferLabel); + + // + // Bearish Buffer ... + string bearishBufferLabel = ShortName + "BearPow " + "(" + (string)length + ")"; + ArraySetAsSeries(bearishBuffer, true); + SetIndexBuffer(bearishBufferIndex, bearishBuffer, INDICATOR_DATA); + PlotIndexSetInteger(bearishBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(bearishBufferIndex, PLOT_LABEL, bearishBufferLabel); + + // + // Signal Buffer ... + string signalBufferLabel = ShortName + "Signal " + "(" + (string)length + ")"; + ArraySetAsSeries(signalBuffer, true); + SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_DATA); + PlotIndexSetInteger(signalBufferIndex, PLOT_DRAW_BEGIN, length); + PlotIndexSetString(signalBufferIndex, PLOT_LABEL, signalBufferLabel); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, " ", "( ", length, " )"); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index, + const double &close[]) +{ + // + // Reset Global Counters ... + xtdBullishCandleCount = 0; + xtdBearishCandleCount = 0; + + // + // Loop through Closes ... + for (int i = bar_index; i <= bar_index + length; i++) + { + for (int j = i + 1; j <= bar_index + length; j++) + { + // + if (close[i] > close[j]) + { + xtdBullishCandleCount++; + } + + // + if (close[i] < close[j]) + { + xtdBearishCandleCount++; + } + } + } + + // + // Bullish Power Buffer ... + bullishBuffer[bar_index] = MathAbs(xtdBullishCandleCount); + + // + // Bearish Power Buffer ... + bearishBuffer[bar_index] = MathAbs(xtdBearishCandleCount); + + // + // Signal Buffer ... + signalBuffer[bar_index] = bullishBuffer[bar_index] - bearishBuffer[bar_index]; + + // + // Check and Draw Crosses if it's Specified ... + if (drawCrosses) + { + DrawCrosses(bar_index); + } +} + +// +// +double GetState( + int bar_index // Specified Bar Index +) +{ + // + // Check Cross Points ... + // bullishCrossedOverBearish = 2; + // bullishOverBearish = 1; + // bullishCrossedUnderBearish = -2; + // bullishUnderBearish = -1; + // OtherWise = 0; + bool isBullishCrossedOverBearish = IsCrossOver( + bullishBuffer, + bearishBuffer, + bar_index); + bool isBullishCrossedUnderBearish = IsCrossUnder( + bullishBuffer, + bearishBuffer, + bar_index); + bool isBullishOverBearish = IsOver( + bullishBuffer, + bearishBuffer, + bar_index); + bool isBullishUnderBearish = IsUnder( + bullishBuffer, + bearishBuffer, + bar_index); + + // + double result = X_XTD_NEUTURAL; + if (isBullishCrossedOverBearish) + { + result = X_XTD_BULLISH_CROSSED_OVER_BEARISH; + } + else if (isBullishCrossedUnderBearish) + { + result = X_XTD_BULLISH_CROSSED_UNDER_BEARISH; + } + else if (isBullishOverBearish) + { + result = X_XTD_BULLISH_OVER_BEARISH; + } + else if (isBullishUnderBearish) + { + result = X_XTD_BULLISH_UNDER_BEARISH; + } + else + { + result = X_XTD_NEUTURAL; + } + + // + return result; +} + +// +// Draw Crosses ... +void DrawCrosses( + int bar_index // the bars which required to draw cross arrow on it ... +) +{ + // + double stateValue = GetState(bar_index); + + // + bool isOver = stateValue == 2; + double low = iLow(_Symbol, _Period, bar_index); + double high = iHigh(_Symbol, _Period, bar_index); + + // + double price = isOver ? low : high; + datetime time = iTime(_Symbol, _Period, bar_index); + ENUM_ARROW_ANCHOR anchor = isOver ? ANCHOR_TOP : ANCHOR_BOTTOM; + uchar arrowCode = isOver ? bullishArrowCode : bearishArrowCode; + color arrowColor = isOver ? bullishArrowColor : bearishArrowColor; + string crossName = "Trend " + (isOver ? "Up" : "Down") + "_" + (string)time + "_" + (string)price; + + // + DrawArrow( + 0, + crossName, + 0, + time, + price, + arrowCode, + anchor, + arrowColor); +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xtm.indicator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xtm.indicator.mq5 new file mode 100644 index 00000000..eac88e0a --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xtm.indicator.mq5 @@ -0,0 +1,349 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Candle Indicator +// --------------------------------------------- +// Name: XTM +// Description: Trend Magic Indicator ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XTM Indicator" +#property strict + +// +// START Constants ... +// +#define ShortName "XTM" + +// +// XTM Indicator States ... +enum ENUM_X_XTM_STATES +{ + X_XTM_BULLISH = 1, + X_XTM_BEARISH = -1, + X_XTM_NEUTURAL = 0, +}; +// +// END Constants ... +// + +// +// START Inputs ... +// +input int maPeriod = 14; // Period +input int maShift = 0; // Shift +input ENUM_MA_METHOD maMethod = MODE_SMA; // Method +input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // Applied To +// +// END Inputs ... +// + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// +#property indicator_chart_window + +// +#property indicator_buffers 3 +#property indicator_plots 1 + +// +// maBuffer ... +#define maBufferIndex 0 +#define maColorBufferIndex 1 +#define stateBufferIndex 2 + +double maBuffer[]; +double maColorBuffer[]; +double stateBuffer[]; + +#property indicator_label1 "XTM" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 clrLime, clrGray, clrRed +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +int maHandler = INVALID_HANDLE; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + + // + // Initializing MA Handler ... + maHandler = iMA( + _Symbol, + _Period, + maPeriod, + maShift, + maMethod, + maAppliedTo); + if (maHandler == INVALID_HANDLE) + { + // + string message = "Error Initializing Ma Handler ..."; + LogMessage(message); + + // + return INIT_FAILED; + } + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = MathMax(0, maPeriod); + + // + // Check Calculated Bars ... + int maCalculatedBars = BarsCalculated(maHandler); + if (maCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer); + if (copiedMas <= 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + // Do Buffers Calculation ... + CalculateBuffers(i); + } + + // + return rates_total; +} +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = false; + + // + // Validate Args ... + if (maPeriod >= 2) + { + result = true; + } + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + string maBufferLabel = "XTM " + "(" + (string)maPeriod + ")"; + + // + // Ma Buffer ... + ArraySetAsSeries(maBuffer, true); + SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA); + PlotIndexSetString(maBufferIndex, PLOT_LABEL, maBufferLabel); + + // + // Ma Color Buffer ... + ArraySetAsSeries(maColorBuffer, true); + SetIndexBuffer(maColorBufferIndex, maColorBuffer, INDICATOR_COLOR_INDEX); + + // + // State Buffer ... + ArraySetAsSeries(stateBuffer, true); + SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + // + string indicatorShortName = ""; + StringConcatenate(indicatorShortName, ShortName, " ", "(", maPeriod, ")"); + + // + IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers(int bar_index) +{ + // + // Requirements ... + XOHCL candle = GetCandle(bar_index); + + // + double maValue = maBuffer[bar_index]; + + // + double lineColorIndex = + maValue < candle.low ? 0 : maValue > candle.high ? 2 + : 1; + + // + // Define State Value ... + // lineColorIndex == 0 => Bullish => 1; + // lineColorIndex == 1 => Neutural => 0; + // lineColorIndex == 2 => Bearish => -1; + double stateValue = + lineColorIndex == 0 ? X_XTM_BULLISH : lineColorIndex == 2 ? X_XTM_BEARISH + : X_XTM_NEUTURAL; + + // + // Set Ma Buffer Color Index ... + maColorBuffer[bar_index] = lineColorIndex; + + // + // Set State Buffer Value ... + stateBuffer[bar_index] = stateValue; +} + +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Indicators/x-saherelm.xts.oscillator.mq5 b/Projects/XUSCHF5/Indicators/x-saherelm.xts.oscillator.mq5 new file mode 100644 index 00000000..46e9fbf9 --- /dev/null +++ b/Projects/XUSCHF5/Indicators/x-saherelm.xts.oscillator.mq5 @@ -0,0 +1,558 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XTS Oscillator +// --------------------------------------------- +// Name: XTS +// Description: Time Sections Oscillator ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XTS Oscillator" +#property strict + +// +// START Constants ... +// + +#define ShortName "XTS" + +enum ENUM_X_PERIOD_METHOD +{ + // + X_PERIOD_NOTHING, + // + X_PERIOD_AUTO, + // + X_PERIOD_MANUALLY +}; + +// +// XTS Oscillator States ... + +// +// END Constants ... +// + +// +// START Inputs ... +// +input group "Current Period"; +input ENUM_APPLIED_PRICE currentAppliedTo = PRICE_CLOSE; // Current Applied To +// +input group "Nearest Period"; +input ENUM_X_PERIOD_METHOD nearestMethod = X_PERIOD_AUTO; // How to Find Nearest Period +input ENUM_TIMEFRAMES nearestPeriod = NULL; // Nearest Time Frame +input ENUM_APPLIED_PRICE nearestAppliedTo = PRICE_CLOSE; // Nearest Applied To +// +input group "Mediest Period"; +input ENUM_X_PERIOD_METHOD mediestMethod = X_PERIOD_AUTO; // How to Find Mediest Period +input ENUM_TIMEFRAMES mediestPeriod = NULL; // Mediest Time Frame +input ENUM_APPLIED_PRICE mediestAppliedTo = PRICE_CLOSE; // Mediest Applied To +// +input group "Farest Period"; +input ENUM_X_PERIOD_METHOD farestMethod = X_PERIOD_AUTO; // How to Find Farest Period +input ENUM_TIMEFRAMES farestPeriod = NULL; // Farest Time Frame +input ENUM_APPLIED_PRICE farestAppliedTo = PRICE_CLOSE; // Farest Applied To + +// +// Includes Logging Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Includes Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// START Buffers ... +// +#property indicator_separate_window + +// +#property indicator_buffers 4 +#property indicator_plots 4 + +// +// Current ... +#define currentBufferIndex 0 + +double currentBuffer[]; + +#property indicator_label1 "XTS C" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrBrown +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +// Nearest ... +#define nearestBufferIndex 1 + +double nearestBuffer[]; + +#property indicator_label2 "XTS N" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrAqua +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// Mediest ... +#define mediestBufferIndex 2 + +double mediestBuffer[]; + +#property indicator_label3 "XTS M" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrLime +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// Farest ... +#define farestBufferIndex 3 + +double farestBuffer[]; + +#property indicator_label4 "XTS F" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrLightBlue +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +ENUM_TIMEFRAMES mNearestPeriod = NULL; +ENUM_TIMEFRAMES mMediestPeriod = NULL; +ENUM_TIMEFRAMES mFarestPeriod = NULL; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + logTag = ShortName; + drawPrefix = ShortName; + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Oscillator ShortName ... + SetOscillatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + OnDeinitDrawLibrary(); + + // + Comment(""); +} + +// +// Calculations ... +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + int maxLength = 30; + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = 0; i < limit && !IsStopped(); i++) + { + // + // Do Buffers Calculation ... + CalculateBuffers(i); + } + + // + return rates_total; +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = true; + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + int maxLength = 30; + + // + // Current ... + ArraySetAsSeries(currentBuffer, true); + SetIndexBuffer(currentBufferIndex, currentBuffer, INDICATOR_DATA); + PlotIndexSetInteger(currentBufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + // Nearest ... + ArraySetAsSeries(nearestBuffer, true); + SetIndexBuffer(nearestBufferIndex, nearestBuffer, INDICATOR_DATA); + PlotIndexSetInteger(nearestBufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + // Mediest ... + ArraySetAsSeries(mediestBuffer, true); + SetIndexBuffer(mediestBufferIndex, mediestBuffer, INDICATOR_DATA); + PlotIndexSetInteger(mediestBufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + // Farest ... + ArraySetAsSeries(farestBuffer, true); + SetIndexBuffer(farestBufferIndex, farestBuffer, INDICATOR_DATA); + PlotIndexSetInteger(farestBufferIndex, PLOT_DRAW_BEGIN, maxLength); +} + +// +// Set Oscillator Short Name and also we can define Buffers Labels ... +void SetOscillatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers(int bar_index) +{ + // + // Current ... + CalculateCurrent(bar_index); + + // + // Nearest ... + CalculateNearest(bar_index); + + // + // Mediest ... + CalculateMediest(bar_index); + + // + // Farest ... + CalculateFarest(bar_index); + + // + // Commenting ... + string comment = GenerateDescriptionComment(); + Comment(comment); +} + +// +// Current ... +void CalculateCurrent(int bar_index) +{ + // + datetime barTime = iTime( + _Symbol, + _Period, + bar_index); + datetime startTime = GetPeriodStartTime( + _Symbol, + _Period, + barTime); + int startBarIndex = iBarShift( + _Symbol, + _Period, + startTime); + + // + XOHCL c = GetCandle( + _Symbol, + _Period, + startBarIndex); + + // + double value = GetAppliedPrice( + c, + currentAppliedTo); + + // + currentBuffer[bar_index] = value; +} + +// +// Nearest ... +void CalculateNearest(int bar_index) +{ + // + if (mNearestPeriod == NULL) + { + // + switch (nearestMethod) + { + // + case X_PERIOD_AUTO: + mNearestPeriod = GetNearestTimeFrame(_Period); + break; + + // + case X_PERIOD_NOTHING: + case X_PERIOD_MANUALLY: + mNearestPeriod = nearestPeriod; + break; + } + } + + // + datetime barTime = iTime( + _Symbol, + _Period, + bar_index); + datetime startTime = GetPeriodStartTime( + _Symbol, + mNearestPeriod, + barTime); + int startBarIndex = iBarShift( + _Symbol, + _Period, + startTime); + + // + XOHCL c = GetCandle( + _Symbol, + _Period, + startBarIndex); + + // + double value = GetAppliedPrice( + c, + nearestAppliedTo); + + // + nearestBuffer[bar_index] = value; +} + +// +// Mediest ... +void CalculateMediest(int bar_index) +{ + // + if (mMediestPeriod == NULL) + { + // + switch (mediestMethod) + { + // + case X_PERIOD_AUTO: + mMediestPeriod = GetMediestTimeFrame(_Period); + break; + + // + case X_PERIOD_NOTHING: + case X_PERIOD_MANUALLY: + mMediestPeriod = mediestPeriod; + break; + } + } + + // + datetime barTime = iTime( + _Symbol, + _Period, + bar_index); + datetime startTime = GetPeriodStartTime( + _Symbol, + mMediestPeriod, + barTime); + int startBarIndex = iBarShift( + _Symbol, + _Period, + startTime); + + // + XOHCL c = GetCandle( + _Symbol, + _Period, + startBarIndex); + + // + double value = GetAppliedPrice( + c, + mediestAppliedTo); + + // + mediestBuffer[bar_index] = value; +} + +// +// Farest ... +void CalculateFarest(int bar_index) +{ + // + if (mFarestPeriod == NULL) + { + // + switch (farestMethod) + { + // + case X_PERIOD_AUTO: + mFarestPeriod = GetFarestTimeFrame(_Period); + break; + + // + case X_PERIOD_NOTHING: + case X_PERIOD_MANUALLY: + mFarestPeriod = farestPeriod; + break; + } + } + + // + datetime barTime = iTime( + _Symbol, + _Period, + bar_index); + datetime startTime = GetPeriodStartTime( + _Symbol, + mFarestPeriod, + barTime); + int startBarIndex = iBarShift( + _Symbol, + _Period, + startTime); + + // + XOHCL c = GetCandle( + _Symbol, + _Period, + startBarIndex); + + // + double value = GetAppliedPrice( + c, + farestAppliedTo); + + // + farestBuffer[bar_index] = value; +} + +// +// Generate Comment ... +string GenerateDescriptionComment() +{ + // + string result = ""; + + // + result += "Nearest : " + EnumToString(mNearestPeriod) + "\n"; + result += "Mediest : " + EnumToString(mMediestPeriod) + "\n"; + result += "Farest : " + EnumToString(mFarestPeriod) + "\n"; + + // + return result; +} +// +// END Functions ... +// diff --git a/Projects/XUSCHF5/Libraries/.gitkeep b/Projects/XUSCHF5/Libraries/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.alert.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.alert.lib.mq5 new file mode 100644 index 00000000..10790632 --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.alert.lib.mq5 @@ -0,0 +1,200 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Alert Library +// -------------------------------------- +// Name: XAlert +// Description: provides Alerts abilities ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Inputs ... +// +input group "Alerts"; +input bool enableAlerts = true; // Enable Alerts +input bool logAlerts = true; // Log Alerts +input bool terminalAlerts = false; // Terminal Alerts +input bool mailAlerts = false; // Mail Alerts +input bool pushAlerts = false; // Push Alerts +// +// END Inputs ... +// + +// +#include "x-saherelm.log.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string alertPrefix = "X-Alert"; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Initial Library if required ... +bool OnInInitAlertLibrary() +{ + return false; +} + +// +// DeInitial Library if required ... +void OnDeinitAlertLibrary() +{ +} + +// +// Attach Alert Prefix to Message ... +string PrepareAlertMessage(string message) +{ + // + StringReplace(message, "\n", " | "); + + // + StringConcatenate(message, alertPrefix, " > ", message); + + // + return message; +} + +// +// Logging an Alert ... +void LogAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !logAlerts) + { + return; + } + + // + LogMessage(alertPrefix, message); +} + +// +// Terminal Alert ... +void TerminalAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !terminalAlerts) + { + return; + } + + // + // Prepare Message ... + message = PrepareAlertMessage(message); + + // Send Terminal Alert ... + Alert(message); +} + +// +// Mail Alert ... +void MailAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !mailAlerts) + { + return; + } + + // + // Send Mail Alert ... + SendMail(alertPrefix, message); +} + +// +// Send Push Notification ... +void PushAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !pushAlerts) + { + return; + } + + // + // Prepare Message ... + message = PrepareAlertMessage(message); + + // + // Send Push Notification Alert ... + SendNotification(message); +} + +// +// Alert Sending ... +void SendAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts) + { + return; + } + + // + // Log ... + if (logAlerts) + { + LogAlert(message); + } + + // + // Terminal ... + if (terminalAlerts) + { + TerminalAlert(message); + } + + // + // Mail ... + if (mailAlerts) + { + MailAlert(message); + } + + // + // Push ... + if (pushAlerts) + { + PushAlert(message); + } +} +void SendAlert( + XSignal &signal, // the Signal Object which requred to Alert + bool asExecuted = true // determines Alert Signal as Executed Signal or not +) +{ + // + // Prepare Message ... + string message = asExecuted ? ExecutedSignalToString(signal) : SignalToString(signal); + + // + // Do Alerting ... + SendAlert(message); +} +// +// END Provided Functions ... +// diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.common.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.common.lib.mq5 new file mode 100644 index 00000000..290dde9b --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.common.lib.mq5 @@ -0,0 +1,4429 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XCommon +// Description: provide all commonly used functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Inputs ... +// + +// +// END Inputs ... +// + +// +// Include Models Library ... +#include "x-saherelm.models.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// + +// +// Detect is new Candle or not ... +bool IsNewCandle() +{ + // + bool result = false; + + // + static int barsOnChart = 0; + int currentBarsOnChart = Bars(_Symbol, _Period); + result = currentBarsOnChart > barsOnChart; + if (!result) + { + return result; + } + + // + barsOnChart = currentBarsOnChart; + result = true; + + // + return result; +} + +// +// Retrive Ask Price ... +double GetAsk() +{ + return SymbolInfoDouble(_Symbol, SYMBOL_ASK); +} +double GetAsk( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_ASK); + + // + return result; +} + +// +// Retrieve Bid Price ... +double GetBid() +{ + return SymbolInfoDouble(_Symbol, SYMBOL_BID); +} +double GetBid( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_BID); + + // + return result; +} + +// +// Calculate and Retrieve Spread Price ... +double GetSpread() +{ + // + double ask = GetAsk(); + double bid = GetBid(); + double result = MathAbs(ask - bid); + + // + return result; +} +double GetSpread( + string symbol // selected symbol for calculations +) +{ + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + double result = MathAbs(ask - bid); + + // + return result; +} + +// +// Get Points ... +double GetPoints() +{ + return _Point; +} +double GetPoints( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_POINT); + + // + return result; +} + +// +// Get Digits ... +int GetDigits() +{ + return _Digits; +} +int GetDigits( + string symbol // selected symbol for calculations +) +{ + // + int result = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS); + + // + return result; +} + +// +// Get Signal Entry ... +double GetEntry( + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + // Validate Arg ... + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + bool isLong = type == X_SIGNAL_LONG; + result = isLong ? GetAsk() : GetBid(); + result = NormalizePrice(result); + + // + return result; +} +double GetEntry( + string symbol, // Specified Symbol + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + // Validate Arg ... + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + bool isLong = type == X_SIGNAL_LONG; + result = isLong ? GetAsk(symbol) : GetBid(symbol); + result = NormalizePrice(result, symbol); + + // + return result; +} + +// +// Get Signal Exit ... +double GetExit( + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + // Validate Arg ... + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + bool isLong = type == X_SIGNAL_LONG; + result = isLong ? GetBid() : GetAsk(); + result = NormalizePrice(result); + + // + return result; +} +double GetExit( + string symbol, // Specified Symbol + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + // Validate Arg ... + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + bool isLong = type == X_SIGNAL_LONG; + result = isLong ? GetBid(symbol) : GetAsk(symbol); + result = NormalizePrice(result, symbol); + + // + return result; +} + +// +// Get 1 Pip in Price Value ... +double GetPipPrice() +{ + // + double result = _Point; + if (_Digits == 3 || _Digits == 5) + { + result *= 10; + } + + // + return result; +} +double GetPipPrice( + string symbol // selected symbol for calculations +) +{ + // + double symbolPoint = GetPoints(symbol); + int symbolDigits = GetDigits(symbol); + + // + double result = symbolPoint; + if (symbolDigits == 3 || symbolDigits == 5) + { + result *= 10; + } + + // + return result; +} + +// +// Converts Pips To Price ... +double PipsToPrice( + int pips // pips amount +) +{ + // + int digits = GetDigits(); + double pipValue = GetPipPrice(); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + double pips // pips amount +) +{ + // + int digits = GetDigits(); + double pipValue = GetPipPrice(); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + string symbol, // selected symbol for calculation + int pips // pips amount +) +{ + // + int digits = GetDigits(symbol); + double pipValue = GetPipPrice(symbol); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + string symbol, // selected symbol for calculation + double pips // pips amount +) +{ + // + int digits = GetDigits(symbol); + double pipValue = GetPipPrice(symbol); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} + +// +// Converts Price to Pips ... +double PriceToPips( + double price // the price amount which required to calculate +) +{ + // + int digits = GetDigits(); + double pipPrice = GetPipPrice(); + + // + double result = price / pipPrice; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PriceToPips( + string symbol, // Selected Symbol + double price // the price amount which required to calculate +) +{ + // + int digits = GetDigits(symbol); + double pipPrice = GetPipPrice(symbol); + + // + double result = price / pipPrice; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} + +// +// Get a Candle Body ... +double GetCandleBody( + XOHCL &candle // specified candle +) +{ + // + double result = MathAbs(candle.open - candle.close); + + // + return result; +} + +// +// Get a Candle Range ... +double GetCandleRange( + XOHCL &candle // specified candle +) +{ + // + double result = MathAbs(candle.high - candle.low); + + // + return result; +} + +// +// Get a Candle Shadow ... +double GetCandleShadow( + XOHCL &candle // specified candle +) +{ + // + double range = GetCandleRange(candle); + double body = GetCandleBody(candle); + + // + double result = MathAbs(range - body); + + // + return result; +} + +// +// Retrieve Applied Price at Specific Candle ... +double GetAppliedPrice( + XOHCL &candle, // specified candle + ENUM_APPLIED_PRICE source = PRICE_CLOSE // specified Applied To +) +{ + // + double result = EMPTY_VALUE; + + // + switch (source) + { + // + // Open ... + case PRICE_OPEN: + result = candle.open; + break; + + // + // High ... + case PRICE_HIGH: + result = candle.high; + break; + + // + // Low ... + case PRICE_LOW: + result = candle.low; + break; + + // + // Median ((High + Low) / 2) ... + case PRICE_MEDIAN: + result = (candle.high + candle.low) / 2; + break; + + // + // Typical ((High + Low + Close)/3) ... + case PRICE_TYPICAL: + result = (candle.high + candle.low + candle.close) / 3; + break; + + // + // Weighted ((High + Low + Close + Close)/4) ... + case PRICE_WEIGHTED: + result = (candle.high + candle.low + (candle.close * 2)) / 4; + break; + + // + // Close ... + default: + case PRICE_CLOSE: + result = candle.close; + break; + } + + // + return result; +} +double GetAppliedPrice( + int bar_index, // specify candle index + ENUM_APPLIED_PRICE source = PRICE_CLOSE // specified Applied To +) +{ + // + double result = EMPTY_VALUE; + + // + XOHCL candle = GetCandle(bar_index); + result = GetAppliedPrice(candle, source); + + // + return result; +} +double GetAppliedPrice( + int bar_index, // specify candle index + ENUM_SERIESMODE mode // converts Series Mode to Applied Price ... +) +{ + // + double result = 0; + + // + ENUM_APPLIED_PRICE mAppliedTo = To(mode); + result = GetAppliedPrice( + bar_index, + mAppliedTo); + + // + return result; +} + +// +// Converts ... +ENUM_APPLIED_PRICE To( + ENUM_SERIESMODE mode // converts Series Mode to Applied Price ... +) +{ + // + ENUM_APPLIED_PRICE result = PRICE_CLOSE; + + // + switch (mode) + { + // + // High ... + case MODE_HIGH: + result = PRICE_HIGH; + break; + + // + // Open ... + case MODE_OPEN: + result = PRICE_OPEN; + break; + + // + // Low ... + case MODE_LOW: + result = PRICE_LOW; + break; + + // + // Close ... + // Default ... + case MODE_CLOSE: + default: + result = PRICE_CLOSE; + break; + } + + // + return result; +} + +// +// Retrieve a Candel Data ... +XOHCL GetCandle(int bar_index) +{ + // + XOHCL result = {}; + + // + double open = iOpen(_Symbol, _Period, bar_index); + double high = iHigh(_Symbol, _Period, bar_index); + double close = iClose(_Symbol, _Period, bar_index); + double low = iLow(_Symbol, _Period, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} +XOHCL GetCandle( + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + XOHCL result = {}; + + // + double open = iOpen(_Symbol, mPeriod, bar_index); + double high = iHigh(_Symbol, mPeriod, bar_index); + double close = iClose(_Symbol, mPeriod, bar_index); + double low = iLow(_Symbol, mPeriod, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} +XOHCL GetCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + XOHCL result = {}; + + // + double open = iOpen(symbol, mPeriod, bar_index); + double high = iHigh(symbol, mPeriod, bar_index); + double close = iClose(symbol, mPeriod, bar_index); + double low = iLow(symbol, mPeriod, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} + +// +// Retrieve a candle index in current timeframe inside another timeframe ... +int GetCandleBarIndex( + int bar_index, // Specify Candle index in current timeframe + ENUM_TIMEFRAMES destPeriod // Specify destination timeframe +) +{ + // + int result = -1; + + // + datetime barTime = iTime(_Symbol, _Period, bar_index); + result = iBarShift(_Symbol, destPeriod, barTime); + + // + return result; +} + +// +// Retrieve a symbol candle index in source time frame inside dest timeframe ... +int GetCandleBarIndex( + int bar_index, // Specify Candle index in current timeframe + string symbol, // Specify desired Symbol + ENUM_TIMEFRAMES sourcePeriod, // Specify bar_index timeframe + ENUM_TIMEFRAMES destPeriod // Specify destination timeframe +) +{ + // + int result = -1; + + // + datetime barTime = iTime(symbol, sourcePeriod, bar_index); + result = iBarShift(symbol, destPeriod, barTime); + + // + return result; +} + +// +// Check a Candle is Bullish or not ... +bool IsBullishCandle( + XOHCL &candle // specified candle +) +{ + // + bool result = false; + + // + result = candle.open < candle.close; + + // + return result; +} +bool IsBullishCandle( + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle(bar_index); + + // + result = IsBullishCandle(candle); + + // + return result; +} +bool IsBullishCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle( + symbol, + mPeriod, + bar_index); + + // + result = IsBullishCandle(candle); + + // + return result; +} + +// +// Check a Candle is Bullish or not ... +bool IsBearishCandle( + XOHCL &candle // specified candle +) +{ + // + bool result = false; + + // + result = candle.open > candle.close; + + // + return result; +} +bool IsBearishCandle( + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle(bar_index); + + // + result = IsBearishCandle(candle); + + // + return result; +} +bool IsBearishCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle( + symbol, + mPeriod, + bar_index); + + // + result = IsBearishCandle(candle); + + // + return result; +} + +// +// Check Candle Body Bigger Than it's Shadow ... +bool HasStrongBody(XOHCL &candle) +{ + // + double bodySize = MathAbs(candle.open - candle.close); + double shadowSize = MathAbs(candle.high - candle.low) - bodySize; + + // + bool result = bodySize > (shadowSize * 1.5); + + // + return result; +} + +// +// Determines a cnadle is Swing High +// or Swing Low order block ... +ENUM_X_SWING_TYPE GetCandleSwing(int bar_index) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(bar_index + 1); + candles[1] = GetCandle(bar_index + 2); + candles[2] = GetCandle(bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = HasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} +ENUM_X_SWING_TYPE GetCandleSwing( + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(mPeriod, bar_index + 1); + candles[1] = GetCandle(mPeriod, bar_index + 2); + candles[2] = GetCandle(mPeriod, bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = HasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} +ENUM_X_SWING_TYPE GetCandleSwing( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(symbol, mPeriod, bar_index + 1); + candles[1] = GetCandle(symbol, mPeriod, bar_index + 2); + candles[2] = GetCandle(symbol, mPeriod, bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = HasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} + +// +// Retrieve Market Highest High ... +double GetHighestHigh( + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + mLength, + bar_index); + + // + result = iHigh( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetHighestHigh( + int mLength, // Which market Length use + int bar_index, // bar index + ENUM_SERIESMODE mode // Calculation mode +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + _Symbol, + _Period, + mode, + mLength, + bar_index); + + // + result = iHigh( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetHighestHigh( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + symbol, + mPeriod, + MODE_HIGH, + mLength, + bar_index); + + // + result = iHigh( + symbol, + mPeriod, + rIdx); + + // + return result; +} +double GetHighestHigh( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + ENUM_SERIESMODE mode, // Calculation mode + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + symbol, + mPeriod, + mode, + mLength, + bar_index); + + // + result = iHigh( + symbol, + mPeriod, + rIdx); + + // + return result; +} + +// +// Retrieve Market Lowest Low ... +double GetLowestLow( + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + mLength, + bar_index); + + // + result = iLow( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetLowestLow( + int mLength, // Which market Length use + int bar_index, // bar index + ENUM_SERIESMODE mode // Calculation mode +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + _Symbol, + _Period, + mode, + mLength, + bar_index); + + // + result = iLow( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetLowestLow( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + symbol, + mPeriod, + MODE_LOW, + mLength, + bar_index); + + // + result = iLow( + symbol, + mPeriod, + rIdx); + + // + return result; +} +double GetLowestLow( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + ENUM_SERIESMODE mode, // Calculation mode + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + symbol, + mPeriod, + mode, + mLength, + bar_index); + + // + result = iLow( + symbol, + mPeriod, + rIdx); + + // + return result; +} + +// +// Calculate Fib Level ... +double GetFibonacciLevel( + double upPrice, + double downPrice, + double level, + int direction) +{ + // + double ling = upPrice - downPrice; + double pLevel = (ling / 100) * (level * 100); + + // + double result = direction > 0 ? upPrice - pLevel : downPrice + pLevel; + result = NormalizeDouble(result, _Digits); + + // + return result; +} + +// +// Check first Cross Over second at bar_index ... +bool IsCrossOver( + const double &first[], // the buffer which check crossing over second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] > second[bar_index] && + !(first[bar_index + 1] > second[bar_index + 1]); + + // + return result; +} + +// +// Check first is Over second at bar_index ... +bool IsOver( + const double &first[], // the buffer which check over second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] > second[bar_index] && + first[bar_index + 1] > second[bar_index + 1]; + + // + return result; +} + +// +// Check first Cross Under second at bar_index ... +bool IsCrossUnder( + const double &first[], // the buffer which check crossing under second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] < second[bar_index] && + !(first[bar_index + 1] < second[bar_index + 1]); + + // + return result; +} + +// +// Check first is Under second at bar_index ... +bool IsUnder( + const double &first[], // the buffer which check under second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] < second[bar_index] && + first[bar_index + 1] < second[bar_index + 1]; + + // + return result; +} + +// +// Calculate Slope of Specified Buffer at Specified Index ... +double GetSlope( + int from, // In Past Index ... + int to, // In Past Index ... + double &buffer[]) +{ + // + double result = 0; + + // + double toValue = buffer[to]; + double fromValue = buffer[from]; + double deltaValue = toValue - fromValue; + double deltaTime = from - to; + + // + result = deltaValue / deltaTime; + + // + return result; +} + +// +// Check if a Value Increasing in Loopback ... +bool IsIncreasing( + int from, // Last Time Index + int to, // Fisr Tima Index + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + from <= to || + ArraySize(buffer) < from + 1) + { + return result; + } + + // + // Loop through Items ... + double toValue = buffer[to]; + double fromValue = buffer[from]; + result = toValue > fromValue; + for (int i = to + 1; i <= from - 1; i++) + { + // + double iValue = buffer[i]; + bool isPassed = toValue >= iValue; + + // + bool isIIncreasing = IsIncreasing( + from, + i, + buffer); + + // + // Check Result ... + result = result && isPassed && isIIncreasing; + if (!result) + { + break; + } + } + + // + return result; +} + +// +// Check if a Value Decreasing in Loopback ... +bool IsDecreasing( + int from, // Last Time Index + int to, // Fisr Tima Index + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + from <= to || + ArraySize(buffer) < from + 1) + { + return result; + } + + // + // Loop through Items ... + double toValue = buffer[to]; + double fromValue = buffer[from]; + result = toValue < fromValue; + for (int i = to + 1; i <= from - 1; i++) + { + // + double iValue = buffer[i]; + bool isPassed = toValue <= iValue; + + // + bool isIDecreasing = IsDecreasing( + from, + i, + buffer); + + // + // Check Result ... + result = result && isPassed && isIDecreasing; + if (!result) + { + break; + } + } + + // + return result; +} + +// +// Get Max Value of Specific Loopback of a Buffer ... +double GetMaxValue( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < mLoopback; i++) + { + // + double iValue = buffer[i]; + + // + result = + // + result == 0 || result < iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} + +// +// Get Min Value of Specific Loopback of a Buffer ... +double GetMinValue( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < mLoopback; i++) + { + // + double iValue = buffer[i]; + + // + result = + // + result == 0 || result > iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} + +// +bool IsInPeak( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback + 1) + { + return result; + } + + // + int q1Length = mLoopback / 4; + int halfLength = mLoopback / 2; + int q2Length = halfLength + q1Length; + + // + double firstValue = buffer[1]; + double q1Value = buffer[q1Length]; + double q2Value = buffer[q2Length]; + double halfValue = buffer[halfLength]; + double lastValue = buffer[ArraySize(buffer) - 1]; + + // + // Peak ... + result = + // + firstValue > lastValue + // + && + // + ( + firstValue > q1Value && + firstValue > halfValue) + // + ; + + // + return result; +} + +// +bool IsInVale( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback + 1) + { + return result; + } + + // + int q1Length = mLoopback / 4; + int halfLength = mLoopback / 2; + int q2Length = halfLength + q1Length; + + // + double firstValue = buffer[1]; + double q1Value = buffer[q1Length]; + double q2Value = buffer[q2Length]; + double halfValue = buffer[halfLength]; + double lastValue = buffer[ArraySize(buffer) - 1]; + + // + // Peak ... + result = + // + firstValue < lastValue + // + && + // + ( + firstValue < q1Value && + firstValue < halfValue) + // + ; + + // + return result; +} + +// +// Check Sharp Happens or not ... +bool IsSharpChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpChanged( + int from, // Past Index in Series + int to, // Present Index in Series + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + from <= to || + ArraySize(buffer) < from + 1) + { + return result; + } + + // + // Loop through Items ... + double toValue = buffer[to]; + double fromValue = buffer[from]; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +// Check InCreased Sharp Happens or not ... +bool IsSharpIncreasedChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = + isIncreased && + toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpIncreasedChanged( + int from, // Past Index in Series + int to, // Present Index in Series + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + from <= to || + ArraySize(buffer) < from + 1) + { + return result; + } + + // + // Loop through Items ... + double toValue = buffer[to]; + double fromValue = buffer[from]; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpIncreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpIncreasedChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpIncreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +// Check Decreased Sharp Happens or not ... +bool IsSharpDecreasedChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = + !isIncreased && + toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpDecreasedChanged( + int from, // Past Index in Series + int to, // Present Index in Series + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + from <= to || + ArraySize(buffer) < from + 1) + { + return result; + } + + // + // Loop through Items ... + double toValue = buffer[to]; + double fromValue = buffer[from]; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpDecreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpDecreasedChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpDecreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +// Validate Struct ... +bool IsValid(XSignal &model, ulong magicNumber) +{ + // + bool result = false; + + // + // Validate Signal Type ... + result = model.type != X_SIGNAL_UNKNOWN; + if (!result) + { + return result; + } + + // + // Check Symbol ... + result = StringLen(model.symbol) == 0 ? true : model.symbol == _Symbol; + if (!result) + { + return result; + } + + // + // Check magic number ... + result = model.magicNumber <= 0 ? true : model.magicNumber == magicNumber; + if (!result) + { + return result; + } + + // + // Check Entry ... + result = model.entry > 0; + if (!result) + { + return result; + } + + // + // Check SL ... + result = model.sl == 0 ? true : model.type == X_SIGNAL_LONG ? model.sl < model.entry + : model.sl > model.entry; + if (!result) + { + return result; + } + + // + // Check TP ... + result = model.tp == 0 ? true : model.type == X_SIGNAL_LONG ? model.tp > model.entry + : model.tp < model.entry; + if (!result) + { + return result; + } + + // + // Check Volume ... + result = model.volume > 0; + if (!result) + { + return result; + } + + // + // Check Time ... + result = model.time > 0; + if (!result) + { + return result; + } + + // + return result; +} + +// +void CleanBuffer(int &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void CleanBuffer(ulong &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void CleanBuffer(double &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void CleanBuffer(XSignal &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void CleanBuffer(XDeal &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void CleanBuffer(XOrder &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} + +// +bool GetLastItem( + double &item, // Holds Result + double &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + item = buffer[bufferSize - 1]; + + // + result = true; + return result; +} +bool GetLastItem( + datetime &item, // Holds Result + datetime &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + item = buffer[bufferSize - 1]; + + // + result = true; + return result; +} + +// +void Add( + int item, // item want to add + int &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + ulong item, // item want to add + ulong &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + string item, // item want to add + string &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + double item, // item want to add + double &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XOHCL &item, // item want to add + XOHCL &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + datetime &item, // item want to add + datetime &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XSignal &item, // item want to add + XSignal &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XDeal &item, // item want to add + XDeal &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XOrder &item, // item want to add + XOrder &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// Converts a Buffer to String Representation ... +string ToString( + const int &buffer[], // Specified Buffer + string separator = ",", // Specified Separator + bool addIndex = false, // Specified Add Items Indexes or Not + string indexLabel = "i:", // Specified Index Label + string indexSeparator = ">" // Specified Index Separator + +) +{ + // + string result = ""; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + for (int i = 0; i < bufferSize; i++) + { + // + if (addIndex) + { + // + if (StringLen(indexLabel) > 0) + { + result += indexLabel + " "; + } + + // + result += (string)i + " "; + + // + if (StringLen(indexSeparator) > 0) + { + result += indexSeparator + " "; + } + } + + // + string iItemString = (string)buffer[i]; + + // + result += iItemString; + + // + if (i < bufferSize - 1) + { + result += separator; + } + } + + // + return result; +} +string ToString( + const double &buffer[], // Specified Buffer + string separator = ",", // Specified Separator + bool addIndex = false, // Specified Add Items Indexes or Not + string indexLabel = "i:", // Specified Index Label + string indexSeparator = ">" // Specified Index Separator + +) +{ + // + string result = ""; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + for (int i = 0; i < bufferSize; i++) + { + // + if (addIndex) + { + // + if (StringLen(indexLabel) > 0) + { + result += indexLabel + " "; + } + + // + result += (string)i + " "; + + // + if (StringLen(indexSeparator) > 0) + { + result += indexSeparator + " "; + } + } + + // + string iItemString = (string)buffer[i]; + + // + result += iItemString; + + // + if (i < bufferSize - 1) + { + result += separator; + } + } + + // + return result; +} +string ToString( + const string &buffer[], // Specified Buffer + string separator = ",", // Specified Separator + bool addIndex = false, // Specified Add Items Indexes or Not + string indexLabel = "i:", // Specified Index Label + string indexSeparator = ">" // Specified Index Separator + +) +{ + // + string result = ""; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + for (int i = 0; i < bufferSize; i++) + { + // + if (addIndex) + { + // + if (StringLen(indexLabel) > 0) + { + result += indexLabel + " "; + } + + // + result += (string)i + " "; + + // + if (StringLen(indexSeparator) > 0) + { + result += indexSeparator + " "; + } + } + + // + string iItemString = (string)buffer[i]; + + // + result += iItemString; + + // + if (i < bufferSize - 1) + { + result += separator; + } + } + + // + return result; +} +string ToString( + const datetime &buffer[], // Specified Buffer + string separator = ",", // Specified Separator + bool addIndex = false, // Specified Add Items Indexes or Not + string indexLabel = "i:", // Specified Index Label + string indexSeparator = ">" // Specified Index Separator + +) +{ + // + string result = ""; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + for (int i = 0; i < bufferSize; i++) + { + // + if (addIndex) + { + // + if (StringLen(indexLabel) > 0) + { + result += indexLabel + " "; + } + + // + result += (string)i + " "; + + // + if (StringLen(indexSeparator) > 0) + { + result += indexSeparator + " "; + } + } + + // + string iItemString = (string)buffer[i]; + + // + result += iItemString; + + // + if (i < bufferSize - 1) + { + result += separator; + } + } + + // + return result; +} + +// +// Check a Signal is Long or not ... +bool IsLong(ENUM_X_SIGNAL_TYPE type) +{ + return type == X_SIGNAL_LONG; +} +bool IsLong(XSignal &signal) +{ + // + bool result = IsLong(signal.type); + + // + return result; +} + +// +// Check a Signal is Short or not ... +bool IsShort(ENUM_X_SIGNAL_TYPE type) +{ + return type == X_SIGNAL_SHORT; +} +bool IsShort(XSignal &signal) +{ + // + bool result = IsShort(signal.type); + + // + return result; +} + +// +// Retrieve a Signal Type String Value ... +string GetSignalType(ENUM_X_SIGNAL_TYPE type) +{ + // + string result = ""; + + // + if (type == X_SIGNAL_UNKNOWN) + { + return result; + } + + // + result = type == X_SIGNAL_LONG ? "Long" : "Short"; + + // + return result; +} +string GetSignalType(XSignal &signal) +{ + // + string result = ""; + + // + result = GetSignalType(signal.type); + + // + return result; +} +ENUM_X_SIGNAL_TYPE GetSignalType(string typeStr) +{ + // + ENUM_X_SIGNAL_TYPE result = X_SIGNAL_UNKNOWN; + + // + if (typeStr == GetSignalType(X_SIGNAL_LONG)) + { + result = X_SIGNAL_LONG; + } + else if (typeStr == GetSignalType(X_SIGNAL_SHORT)) + { + result = X_SIGNAL_SHORT; + } + + // + return result; +} + +// +// Retrieve Signal Execution String ... +string GetSignalExecutionError(int error) +{ + // + string result = ""; + + // + switch (error) + { + // + case X_TRADER_INVALID_SIGNAL_ERROR: + result = "Invalid Signal ..."; + break; + + // + case X_TRADER_NOT_ENOUGH_EQUITY_ERROR: + result = "Not Enough Equity for Trade ..."; + break; + + // + case X_TRADER_NOT_ENOUGH_BALANCE_ERROR: + result = "Not Enough Balance for Trade ..."; + break; + + // + case X_TRADER_NOT_ENOUGH_MARIGIN_ERROR: + result = "Not Enough Marigin For Trade ..."; + break; + + // + case X_TRADER_MAX_TRADES_REACHED_ERROR: + result = "Max Allowed Trade Reached ..."; + break; + + // + case X_TRADER_UNKNOWN_ERROR: + default: + result = "Unknown Issue ..."; + break; + } + + // + return result; +} + +// +// Extract Data from String ... +string ExtractString( + const string source, // Source String used for Extracting + const string startString, // Expression Start String must be Unique + const string endString // Where to End Extraction, usually a Sign +) +{ + // + string result = ""; + + // + // Validate String ... + if ( + StringLen(source) == 0 || + StringLen(endString) == 0 || + StringLen(startString) == 0) + { + return result; + } + + // + // Find Start String Position ... + int sPos = StringFind( + source, + startString); + if (sPos < 0) + { + return result; + } + + // + // Find End String Position after Start String ... + int searchEndFromPos = sPos + StringLen(startString); + int ePos = StringFind( + source, + endString, + searchEndFromPos); + if (ePos < 0) + { + return result; + } + + // + // Extract Data from Source ... + int dLength = ePos - searchEndFromPos; + result = StringSubstr( + source, + searchEndFromPos, + dLength); + + // + return result; +} + +// +// Normalize a give Volume ... +double NormalizeVolume( + double volume, // desired volume to normalize + string symbol = NULL, // Specified Symbol for Normalization + int mLength = 2 // Length of Digits +) +{ + // + double result = volume; + + // + // Normalize Symbol ... + if (StringLen(symbol) == 0) + { + symbol = _Symbol; + } + + // + // Normalize Digits ... + int digits = GetDigits(symbol); + mLength = + mLength == 0 || mLength > digits + ? digits + : MathMin(mLength, digits); + + // + // Normalize Volume ... + result = NormalizeDouble(result, mLength); + + // + double maxAvailableVolume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX); + double minAvailableVolume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN); + + // + // Validate Result ... + if (result > maxAvailableVolume) + { + result = maxAvailableVolume; + } + else if (result < minAvailableVolume) + { + result = minAvailableVolume; + } + + // + return result; +} + +// +// Normallize Price ... +double NormalizePrice( + double price, // desired Price for normalization + string symbol = NULL // Specified Symbol for Normalization +) +{ + // + double result = 0; + + // + // Mormalize Symbol ... + if (StringLen(symbol) == 0) + { + symbol = _Symbol; + } + + // + int digits = GetDigits(symbol); + result = NormalizeDouble(price, digits); + + // + return result; +} + +// +// Error Descriptions Functions ... +// + +// +// Retrieve Specified Error Code Description ... +string GetErrorDescription(int err_code) +{ + // + string result = ""; + + // + switch (err_code) + { + // + //--- Constant Description + + // + case ERR_SUCCESS: + result = "The operation completed successfully"; + break; + + // + case ERR_INTERNAL_ERROR: + result = "Unexpected internal error"; + break; + + // + case ERR_WRONG_INTERNAL_PARAMETER: + result = "Wrong parameter in the inner call of the client terminal function"; + break; + + // + case ERR_INVALID_PARAMETER: + result = "Wrong parameter when calling the system function"; + break; + + // + case ERR_NOT_ENOUGH_MEMORY: + result = "Not enough memory to perform the system function"; + break; + + // + case ERR_STRUCT_WITHOBJECTS_ORCLASS: + result = "The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes"; + break; + + // + case ERR_INVALID_ARRAY: + result = "Array of a wrong type, wrong size, or a damaged object of a dynamic array"; + break; + + // + case ERR_ARRAY_RESIZE_ERROR: + result = "Not enough memory for the relocation of an array, or an attempt to change the size of a static array"; + break; + + // + case ERR_STRING_RESIZE_ERROR: + result = "Not enough memory for the relocation of string"; + break; + + // + case ERR_NOTINITIALIZED_STRING: + result = "Not initialized string"; + break; + + // + case ERR_INVALID_DATETIME: + result = "Invalid date and/or time"; + break; + + // + case ERR_ARRAY_BAD_SIZE: + result = "Requested array size exceeds 2 GB"; + break; + + // + case ERR_INVALID_POINTER: + result = "Wrong pointer"; + break; + + // + case ERR_INVALID_POINTER_TYPE: + result = "Wrong type of pointer"; + break; + + // + case ERR_FUNCTION_NOT_ALLOWED: + result = "System function is not allowed to call"; + break; + + // + //--- Charts + + // + case ERR_CHART_WRONG_ID: + result = "Wrong chart ID"; + break; + + // + case ERR_CHART_NO_REPLY: + result = "Chart does not respond"; + break; + + // + case ERR_CHART_NOT_FOUND: + result = "Chart not found"; + break; + + // + case ERR_CHART_NO_EXPERT: + result = "No Expert Advisor in the chart that could handle the event"; + break; + + // + case ERR_CHART_CANNOT_OPEN: + result = "Chart opening error"; + break; + + // + case ERR_CHART_CANNOT_CHANGE: + result = "Failed to change chart symbol and period"; + break; + + // + case ERR_CHART_CANNOT_CREATE_TIMER: + result = "Failed to create timer"; + break; + + // + case ERR_CHART_WRONG_PROPERTY: + result = "Wrong chart property ID"; + break; + + // + case ERR_CHART_SCREENSHOT_FAILED: + result = "Error creating screenshots"; + break; + + // + case ERR_CHART_NAVIGATE_FAILED: + result = "Error navigating through chart"; + break; + + // + case ERR_CHART_TEMPLATE_FAILED: + result = "Error applying template"; + break; + + // + case ERR_CHART_WINDOW_NOT_FOUND: + result = "Subwindow containing the indicator was not found"; + break; + + // + case ERR_CHART_INDICATOR_CANNOT_ADD: + result = "Error adding an indicator to chart"; + break; + + // + case ERR_CHART_INDICATOR_CANNOT_DEL: + result = "Error deleting an indicator from the chart"; + break; + + // + case ERR_CHART_INDICATOR_NOT_FOUND: + result = "Indicator not found on the specified chart"; + break; + + // + //--- Graphical Objects + case ERR_OBJECT_ERROR: + result = "Error working with a graphical object"; + break; + + // + case ERR_OBJECT_NOT_FOUND: + result = "Graphical object was not found"; + break; + + // + case ERR_OBJECT_WRONG_PROPERTY: + result = "Wrong ID of a graphical object property"; + break; + + // + case ERR_OBJECT_GETDATE_FAILED: + result = "Unable to get date corresponding to the value"; + break; + + // + case ERR_OBJECT_GETVALUE_FAILED: + result = "Unable to get value corresponding to the date"; + break; + + // + //--- MarketInfo + + // + case ERR_MARKET_UNKNOWN_SYMBOL: + result = "Unknown symbol"; + break; + + // + case ERR_MARKET_NOT_SELECTED: + result = "Symbol is not selected in MarketWatch"; + break; + + // + case ERR_MARKET_WRONG_PROPERTY: + result = "Wrong identifier of a symbol property"; + break; + + // + case ERR_MARKET_LASTTIME_UNKNOWN: + result = "Time of the last tick is not known (no ticks)"; + break; + + // + case ERR_MARKET_SELECT_ERROR: + result = "Error adding or deleting a symbol in MarketWatch"; + break; + + // + //--- History Access + + // + case ERR_HISTORY_NOT_FOUND: + result = "Requested history not found"; + break; + + // + case ERR_HISTORY_WRONG_PROPERTY: + result = "Wrong ID of the history property"; + break; + + // + //--- Global_Variables + + // + case ERR_GLOBALVARIABLE_NOT_FOUND: + result = "Global variable of the client terminal is not found"; + break; + + // + case ERR_GLOBALVARIABLE_EXISTS: + result = "Global variable of the client terminal with the same name already exists"; + break; + + // + case ERR_MAIL_SEND_FAILED: + result = "Email sending failed"; + break; + + // + case ERR_PLAY_SOUND_FAILED: + result = "Sound playing failed"; + break; + + // + case ERR_MQL5_WRONG_PROPERTY: + result = "Wrong identifier of the program property"; + break; + + // + case ERR_TERMINAL_WRONG_PROPERTY: + result = "Wrong identifier of the terminal property"; + break; + + // + case ERR_FTP_SEND_FAILED: + result = "File sending via ftp failed"; + break; + + // + case ERR_NOTIFICATION_SEND_FAILED: + result = "Error in sending notification"; + break; + + // + //--- Custom Indicator Buffers + + // + case ERR_BUFFERS_NO_MEMORY: + result = "Not enough memory for the distribution of indicator buffers"; + break; + + // + case ERR_BUFFERS_WRONG_INDEX: + result = "Wrong indicator buffer index"; + break; + + // + //--- Custom Indicator Properties + + // + case ERR_CUSTOM_WRONG_PROPERTY: + result = "Wrong ID of the custom indicator property"; + break; + + // + //--- Account + + // + case ERR_ACCOUNT_WRONG_PROPERTY: + result = "Wrong account property ID"; + break; + + // + case ERR_TRADE_WRONG_PROPERTY: + result = "Wrong trade property ID"; + break; + + // + case ERR_TRADE_DISABLED: + result = "Trading by Expert Advisors prohibited"; + break; + + // + case ERR_TRADE_POSITION_NOT_FOUND: + result = "Position not found"; + break; + + // + case ERR_TRADE_ORDER_NOT_FOUND: + result = "Order not found"; + break; + + // + case ERR_TRADE_DEAL_NOT_FOUND: + result = "Deal not found"; + break; + + // + case ERR_TRADE_SEND_FAILED: + result = "Trade request sending failed"; + break; + + // + //--- Indicators + + // + case ERR_INDICATOR_UNKNOWN_SYMBOL: + result = "Unknown symbol"; + break; + + // + case ERR_INDICATOR_CANNOT_CREATE: + result = "Indicator cannot be created"; + break; + + // + case ERR_INDICATOR_NO_MEMORY: + result = "Not enough memory to add the indicator"; + break; + + // + case ERR_INDICATOR_CANNOT_APPLY: + result = "The indicator cannot be applied to another indicator"; + break; + + // + case ERR_INDICATOR_CANNOT_ADD: + result = "Error applying an indicator to chart"; + break; + + // + case ERR_INDICATOR_DATA_NOT_FOUND: + result = "Requested data not found"; + break; + + // + case ERR_INDICATOR_WRONG_HANDLE: + result = "Wrong indicator handle"; + break; + + // + case ERR_INDICATOR_WRONG_PARAMETERS: + result = "Wrong number of parameters when creating an indicator"; + break; + + // + case ERR_INDICATOR_PARAMETERS_MISSING: + result = "No parameters when creating an indicator"; + break; + + // + case ERR_INDICATOR_CUSTOM_NAME: + result = "The first parameter in the array must be the name of the custom indicator"; + break; + + // + case ERR_INDICATOR_PARAMETER_TYPE: + result = "Invalid parameter type in the array when creating an indicator"; + break; + + // + case ERR_INDICATOR_WRONG_INDEX: + result = "Wrong index of the requested indicator buffer"; + break; + + // + //--- Depth of Market + + // + case ERR_BOOKS_CANNOT_ADD: + result = "Depth Of Market can not be added"; + break; + + // + case ERR_BOOKS_CANNOT_DELETE: + result = "Depth Of Market can not be removed"; + break; + + // + case ERR_BOOKS_CANNOT_GET: + result = "The data from Depth Of Market can not be obtained"; + break; + + // + case ERR_BOOKS_CANNOT_SUBSCRIBE: + result = "Error in subscribing to receive new data from Depth Of Market"; + break; + + // + //--- File Operations + + // + case ERR_TOO_MANY_FILES: + result = "More than 64 files cannot be opened at the same time"; + break; + + // + case ERR_WRONG_FILENAME: + result = "Invalid file name"; + break; + + // + case ERR_TOO_LONG_FILENAME: + result = "Too long file name"; + break; + + // + case ERR_CANNOT_OPEN_FILE: + result = "File opening error"; + break; + + // + case ERR_FILE_CACHEBUFFER_ERROR: + result = "Not enough memory for cache to read"; + break; + + // + case ERR_CANNOT_DELETE_FILE: + result = "File deleting error"; + break; + + // + case ERR_INVALID_FILEHANDLE: + result = "A file with this handle was closed, or was not opening at all"; + break; + + // + case ERR_WRONG_FILEHANDLE: + result = "Wrong file handle"; + break; + + // + case ERR_FILE_NOTTOWRITE: + result = "The file must be opened for writing"; + break; + + // + case ERR_FILE_NOTTOREAD: + result = "The file must be opened for reading"; + break; + + // + case ERR_FILE_NOTBIN: + result = "The file must be opened as a binary one"; + break; + + // + case ERR_FILE_NOTTXT: + result = "The file must be opened as a text"; + break; + + // + case ERR_FILE_NOTTXTORCSV: + result = "The file must be opened as a text or CSV"; + break; + + // + case ERR_FILE_NOTCSV: + result = "The file must be opened as CSV"; + break; + + // + case ERR_FILE_READERROR: + result = "File reading error"; + break; + + // + case ERR_FILE_BINSTRINGSIZE: + result = "String size must be specified, because the file is opened as binary"; + break; + + // + case ERR_INCOMPATIBLE_FILE: + result = "A text file must be for string arrays, for other arrays - binary"; + break; + + // + case ERR_FILE_IS_DIRECTORY: + result = "This is not a file, this is a directory"; + break; + + // + case ERR_FILE_NOT_EXIST: + result = "File does not exist"; + break; + + // + case ERR_FILE_CANNOT_REWRITE: + result = "File can not be rewritten"; + break; + + // + case ERR_WRONG_DIRECTORYNAME: + result = "Wrong directory name"; + break; + + // + case ERR_DIRECTORY_NOT_EXIST: + result = "Directory does not exist"; + break; + + // + case ERR_FILE_ISNOT_DIRECTORY: + result = "This is a file, not a directory"; + break; + + // + case ERR_CANNOT_DELETE_DIRECTORY: + result = "The directory cannot be removed"; + break; + + // + case ERR_CANNOT_CLEAN_DIRECTORY: + result = "Failed to clear the directory (probably one or more files are blocked and removal operation failed)"; + break; + + // + case ERR_FILE_WRITEERROR: + result = "Failed to write a resource to a file"; + break; + + // + //--- String Casting + + // + case ERR_NO_STRING_DATE: + result = "No date in the string"; + break; + + // + case ERR_WRONG_STRING_DATE: + result = "Wrong date in the string"; + break; + + // + case ERR_WRONG_STRING_TIME: + result = "Wrong time in the string"; + break; + + // + case ERR_STRING_TIME_ERROR: + result = "Error converting string to date"; + break; + + // + case ERR_STRING_OUT_OF_MEMORY: + result = "Not enough memory for the string"; + break; + + // + case ERR_STRING_SMALL_LEN: + result = "The string length is less than expected"; + break; + + // + case ERR_STRING_TOO_BIGNUMBER: + result = "Too large number, more than ULONG_MAX"; + break; + + // + case ERR_WRONG_FORMATSTRING: + result = "Invalid format string"; + break; + + // + case ERR_TOO_MANY_FORMATTERS: + result = "Amount of format specifiers more than the parameters"; + break; + + // + case ERR_TOO_MANY_PARAMETERS: + result = "Amount of parameters more than the format specifiers"; + break; + + // + case ERR_WRONG_STRING_PARAMETER: + result = "Damaged parameter of string type"; + break; + + // + case ERR_STRINGPOS_OUTOFRANGE: + result = "Position outside the string"; + break; + + // + case ERR_STRING_ZEROADDED: + result = "0 added to the string end, a useless operation"; + break; + + // + case ERR_STRING_UNKNOWNTYPE: + result = "Unknown data type when converting to a string"; + break; + + // + case ERR_WRONG_STRING_OBJECT: + result = "Damaged string object"; + break; + + // + //--- Operations with Arrays + + // + case ERR_INCOMPATIBLE_ARRAYS: + result = "Copying incompatible arrays. String array can be copied only to a string array, and a numeric array - in numeric array only"; + break; + + // + case ERR_SMALL_ASSERIES_ARRAY: + result = "The receiving array is declared as AS_SERIES, and it is of insufficient size"; + break; + + // + case ERR_SMALL_ARRAY: + result = "Too small array, the starting position is outside the array"; + break; + + // + case ERR_ZEROSIZE_ARRAY: + result = "An array of zero length"; + break; + + // + case ERR_NUMBER_ARRAYS_ONLY: + result = "Must be a numeric array"; + break; + + // + case ERR_ONEDIM_ARRAYS_ONLY: + result = "Must be a one-dimensional array"; + break; + + // + case ERR_SERIES_ARRAY: + result = "Timeseries cannot be used"; + break; + + // + case ERR_DOUBLE_ARRAY_ONLY: + result = "Must be an array of type double"; + break; + + // + case ERR_FLOAT_ARRAY_ONLY: + result = "Must be an array of type float"; + break; + + // + case ERR_LONG_ARRAY_ONLY: + result = "Must be an array of type long"; + break; + + // + case ERR_INT_ARRAY_ONLY: + result = "Must be an array of type int"; + break; + + // + case ERR_SHORT_ARRAY_ONLY: + result = "Must be an array of type short"; + break; + + // + case ERR_CHAR_ARRAY_ONLY: + result = "Must be an array of type char"; + break; + + // + //--- Operations with OpenCL + + // + case ERR_OPENCL_NOT_SUPPORTED: + result = "OpenCL functions are not supported on this computer"; + break; + + // + case ERR_OPENCL_INTERNAL: + result = "Internal error occurred when running OpenCL"; + break; + + // + case ERR_OPENCL_INVALID_HANDLE: + result = "Invalid OpenCL handle"; + break; + + // + case ERR_OPENCL_CONTEXT_CREATE: + result = "Error creating the OpenCL context"; + break; + + // + case ERR_OPENCL_QUEUE_CREATE: + result = "Failed to create a run queue in OpenCL"; + break; + + // + case ERR_OPENCL_PROGRAM_CREATE: + result = "Error occurred when compiling an OpenCL program"; + break; + + // + case ERR_OPENCL_TOO_LONG_KERNEL_NAME: + result = "Too long kernel name (OpenCL kernel)"; + break; + + // + case ERR_OPENCL_KERNEL_CREATE: + result = "Error creating an OpenCL kernel"; + break; + + // + case ERR_OPENCL_SET_KERNEL_PARAMETER: + result = "Error occurred when setting parameters for the OpenCL kernel"; + break; + + // + case ERR_OPENCL_EXECUTE: + result = "OpenCL program runtime error"; + break; + + // + case ERR_OPENCL_WRONG_BUFFER_SIZE: + result = "Invalid size of the OpenCL buffer"; + break; + + // + case ERR_OPENCL_WRONG_BUFFER_OFFSET: + result = "Invalid offset in the OpenCL buffer"; + break; + + // + case ERR_OPENCL_BUFFER_CREATE: + result = "Failed to create and OpenCL buffer"; + break; + + // + //--- User-Defined Errors + default: + result = "UNKNOWN Erro ..."; + break; + } + + // + return result; +} + +// +// Retrieve Specified Error Code Description ... +string GetTradeServerReturnCodeDescription(int return_code) +{ + // + string result = ""; + + // + switch (return_code) + { + // + case TRADE_RETCODE_REQUOTE: + result = "Requote"; + break; + + // + case TRADE_RETCODE_REJECT: + result = "Request rejected"; + break; + + // + case TRADE_RETCODE_CANCEL: + result = "Request canceled by trader"; + break; + + // + case TRADE_RETCODE_PLACED: + result = "Order placed"; + break; + + // + case TRADE_RETCODE_DONE: + result = "Request completed"; + break; + + // + case TRADE_RETCODE_DONE_PARTIAL: + result = "Only part of the request was completed"; + break; + + // + case TRADE_RETCODE_ERROR: + result = "Request processing error"; + break; + + // + case TRADE_RETCODE_TIMEOUT: + result = "Request canceled by timeout"; + break; + + // + case TRADE_RETCODE_INVALID: + result = "Invalid request"; + break; + + // + case TRADE_RETCODE_INVALID_VOLUME: + result = "Invalid volume in the request"; + break; + + // + case TRADE_RETCODE_INVALID_PRICE: + result = "Invalid price in the request"; + break; + + // + case TRADE_RETCODE_INVALID_STOPS: + result = "Invalid stops in the request"; + break; + + // + case TRADE_RETCODE_TRADE_DISABLED: + result = "Trade is disabled"; + break; + + // + case TRADE_RETCODE_MARKET_CLOSED: + result = "Market is closed"; + break; + + // + case TRADE_RETCODE_NO_MONEY: + result = "There is not enough money to complete the request"; + break; + + // + case TRADE_RETCODE_PRICE_CHANGED: + result = "Prices changed"; + break; + + // + case TRADE_RETCODE_PRICE_OFF: + result = "There are no quotes to process the request"; + break; + + // + case TRADE_RETCODE_INVALID_EXPIRATION: + result = "Invalid order expiration date in the request"; + break; + + // + case TRADE_RETCODE_ORDER_CHANGED: + result = "Order state changed"; + break; + + // + case TRADE_RETCODE_TOO_MANY_REQUESTS: + result = "Too frequent requests"; + break; + + // + case TRADE_RETCODE_NO_CHANGES: + result = "No changes in request"; + break; + + // + case TRADE_RETCODE_SERVER_DISABLES_AT: + result = "Autotrading disabled by server"; + break; + + // + case TRADE_RETCODE_CLIENT_DISABLES_AT: + result = "Autotrading disabled by client terminal"; + break; + + // + case TRADE_RETCODE_LOCKED: + result = "Request locked for processing"; + break; + + // + case TRADE_RETCODE_FROZEN: + result = "Order or position frozen"; + break; + + // + case TRADE_RETCODE_INVALID_FILL: + result = "Invalid order filling type"; + break; + + // + case TRADE_RETCODE_CONNECTION: + result = "No connection with the trade server"; + break; + + // + case TRADE_RETCODE_ONLY_REAL: + result = "Operation is allowed only for live accounts"; + break; + + // + case TRADE_RETCODE_LIMIT_ORDERS: + result = "The number of pending orders has reached the limit"; + break; + + // + case TRADE_RETCODE_LIMIT_VOLUME: + result = "The volume of orders and positions for the symbol has reached the limit"; + break; + + // + default: + result = "Invalid return code of the trade server"; + break; + } + + // + return result; +} + +// +// Check Expert Running in Testing Mode or not ... +bool IsRunningOnTestMode() +{ + // + bool result = false; + + // + // check programm mode ... + result = MQL5InfoInteger(MQL5_TESTING); + + // + return result; +} + +// +// Date Time Manipulation Functions ... +// + +// +// Representation of Time Struct ... +// struct MqlDateTime +// { +// int year; // Year +// int mon; // Month +// int day; // Day +// int hour; // Hour +// int min; // Minutes +// int sec; // Seconds +// int day_of_week; // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) +// int day_of_year; // Day number of the year (January 1st is assigned the number value of zero) +// }; + +// +// Converts Time to Seconds ... +ulong TimeToSeconds( + datetime time // Specify time to Convert ... +) +{ + // + ulong result = (ulong)time; + + // + return result; +} +ulong TimeToSeconds( + MqlDateTime &time // Specify time to Convert ... +) +{ + // + datetime dTime = StructToTime(time); + + // + ulong result = TimeToSeconds(dTime); + + // + return result; +} + +// +// Converts Seconds To Time ... +datetime SecondsToTime( + ulong seconds // Specify Seconds to Convert ... +) +{ + // + datetime result = (datetime)seconds; + + // + return result; +} +MqlDateTime SecondsToStruct( + ulong seconds // Specify Seconds to Convert ... +) +{ + // + datetime dTime = SecondsToTime(seconds); + + // + MqlDateTime result = {}; + TimeToStruct( + dTime, + result); + + // + return result; +} + +// +// Converts Time to MilliSeconds ... +ulong TimeToMilliSeconds( + datetime time // Specify time to Convert ... +) +{ + // + ulong result = TimeToSeconds(time) * 1000; + + // + return result; +} +ulong TimeToMilliSeconds( + MqlDateTime &time // Specify time to Convert ... +) +{ + // + datetime dTime = StructToTime(time); + + // + ulong result = TimeToMilliSeconds(dTime); + + // + return result; +} + +// +// Converts MillisSeconds to Time ... +datetime MilliSecondsToTiem( + ulong milliSeconds // Specify MilliSeconds to Convert ... +) +{ + // + ulong seconds = milliSeconds / 1000; + + // + datetime result = SecondsToTime(seconds); + + // + return result; +} +MqlDateTime MilliSecondsToStruct( + ulong milliSeconds // Specify MilliSeconds to Convert ... +) +{ + // + datetime dTime = MilliSecondsToTiem(milliSeconds); + + // + MqlDateTime result = {}; + TimeToStruct( + dTime, + result); + + // + return result; +} + +// +// Retrieve DateTime Structure ... +MqlDateTime GetCurrentTime() +{ + // + MqlDateTime result = {}; + + // + TimeCurrent(result); + + // + return result; +} + +// +// Retrieve Current Time as Seconds ... +ulong GetCurrentTimeAsSeconds() +{ + // + datetime time = TimeCurrent(); + + // + ulong result = TimeToSeconds(time); + + // + return result; +} + +// +// Retrieve Current Time as MilliSeconds ... +ulong GetCurrentTimeAsMilliSeconds() +{ + // + datetime time = TimeCurrent(); + + // + ulong result = TimeToMilliSeconds(time); + + // + return result; +} + +// +// Retrieve Specified Candle Time ... +datetime GetCandleTime( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Validate and Normalize Args ... + + // + // Normalize Symbol ... + symbol = StringLen(symbol) == 0 + ? _Symbol + : symbol; + + // + // Normalize Period ... + period = period == NULL + ? _Period + : period; + + // + // Retrieve Bar Time ... + datetime result = iTime( + symbol, + period, + bar_index); + + // + return result; +} + +// +// Retrieve Specified Candle Time ... +ulong GetCandleTimeAsSeconds( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Retrieve Bar Time ... + datetime time = GetCandleTime( + symbol, + period, + bar_index); + + // + ulong result = TimeToSeconds(time); + + // + return result; +} + +// +// Retrieve Specified Candle Time ... +ulong GetCandleTimeAsMilliSeconds( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Retrieve Bar Time ... + datetime time = GetCandleTime( + symbol, + period, + bar_index); + + // + ulong result = TimeToMilliSeconds(time); + + // + return result; +} + +// +// Retrieve a Candle Time Structure ... +MqlDateTime GetCandleTimeStruct( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + MqlDateTime result = {}; + + // + // Retrieve Bar Time ... + datetime barTime = GetCandleTime( + symbol, + period, + bar_index); + + // + // Convert to Structure ... + TimeToStruct(barTime, result); + + // + return result; +} + +// +// +// + +// +// Holds Month ... +static int xMonth = -1; + +// +// Holds Day Of Week ... +static int xDayOfWeek = -1; +static int xForWeekDay = -1; + +// +// Holds Day ... +static int xDay = -1; + +// +// Holds Hour ... +static int xHour = -1; + +// +// Reset Timing Variables ... +void ResetTiming() +{ + // + xHour = -1; + xDay = -1; + xDayOfWeek = -1; + xMonth = -1; +} + +// +// Detecting New Houre ... +bool IsNewHour() +{ + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.hour != xHour; + if (result) + { + xHour = timeStruct.hour; + } + + // + return result; +} + +// +// Detecting New Day ... +bool IsNewDay() +{ + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.day_of_year != xDay; + if (result) + { + xDay = timeStruct.day_of_year; + } + + // + return result; +} + +// +// Detecting New Week ... +bool IsNewWeek() +{ + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Week ... + // Since Week Starts From Monday in Forex World ... + // we Calculate Start of Week by 1-Monday ... + result = + xDayOfWeek == -1 && + xForWeekDay == -1 + ? true + : timeStruct.day_of_week == 1 && + timeStruct.day_of_year > xForWeekDay; + + // + xForWeekDay = timeStruct.day_of_year; + xDayOfWeek = timeStruct.day_of_week; + + // + return result; +} + +// +// Detecting End Of Week ... +bool IsWeekEnd() +{ + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check WeekEnd ... + // Since Week Starts From Monday in Forex World ... + // we Calculate End of Week by 5-Friday ... + result = + xDayOfWeek != -1 && + timeStruct.day_of_week == 5 && + timeStruct.hour == 23 && + timeStruct.min == 59 && + timeStruct.sec == 59; + + // + return result; +} + +// +// Detecting New Month ... +bool IsNewMonth() +{ + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.mon != xMonth; + if (result) + { + xMonth = timeStruct.mon; + } + + // + return result; +} + +// +// Find Farest Time Frame ... +ENUM_TIMEFRAMES GetFarestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + case PERIOD_M20: + case PERIOD_M30: + result = PERIOD_H4; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + case PERIOD_H4: + result = PERIOD_H12; + break; + + // + case PERIOD_H6: + case PERIOD_H8: + case PERIOD_H12: + case PERIOD_D1: + result = PERIOD_W1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Find Medium Time Frame ... +ENUM_TIMEFRAMES GetMediestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + case PERIOD_M20: + result = PERIOD_H1; + break; + + // + case PERIOD_M30: + result = PERIOD_H2; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_H4; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_H12; + break; + + // + case PERIOD_H12: + result = PERIOD_D1; + break; + + // + case PERIOD_D1: + result = PERIOD_W1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Find Nearest Time Frame ... +ENUM_TIMEFRAMES GetNearestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + result = PERIOD_M5; + break; + + // + case PERIOD_M5: + case PERIOD_M6: + case PERIOD_M10: + case PERIOD_M12: + result = PERIOD_M15; + break; + + // + case PERIOD_M15: + case PERIOD_M20: + result = PERIOD_M30; + break; + + // + case PERIOD_M30: + result = PERIOD_H1; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_H4; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_H12; + break; + + // + case PERIOD_H12: + result = PERIOD_D1; + break; + + // + case PERIOD_D1: + result = PERIOD_W1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Get Specific Time Frame Start Candle Time ... +datetime GetPeriodStartTime( + string mSymbol = NULL, // Specified Symbol ... + ENUM_TIMEFRAMES mPeriod = NULL, // Specified Period ... + datetime mTime = NULL // Specified Bar Time ... +) +{ + // + // Normalize Arg ... + + // + if ( + mSymbol == NULL || + StringLen(mSymbol) == 0) + { + mSymbol = _Symbol; + } + + // + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + if ( + mTime < 0 || + mTime == NULL) + { + mTime = TimeCurrent(); + } + + // + int barIndex = iBarShift( + mSymbol, + mPeriod, + mTime, + false); + + // + datetime result = iTime( + mSymbol, + mPeriod, + barIndex); + + // + return result; +} + +// +// END Provided Functions ... +// diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.draw.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.draw.lib.mq5 new file mode 100644 index 00000000..ece98c83 --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.draw.lib.mq5 @@ -0,0 +1,2345 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Draw Library +// -------------------------------------- +// Name: XDraw +// Description: provides Draw abilities ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Inputs ... +// +// +// END Inputs ... +// + +// +// Include Logger Library ... +#include "x-saherelm.log.lib.mq5" +#include "x-saherelm.common.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string drawPrefix = "X-OBJ"; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// DeInitial Library if required ... +void OnDeinitDrawLibrary() +{ + RemoveDraws(); +} + +// +void DrawSignalShape( + XSignal &signal, // Specify Signal to Draw + color longColor = clrAqua, // Long Signals Color + color shortColor = clrFuchsia, // Short Signal Color + color entryColor = clrGold // Signal Entry Price Color +) +{ + // + // Draw Signal Info : + // - Draw Entry Price Line; + // - Draw SL; + // - Draw TP; + // - Risk Free; + + // + bool isLong = signal.type == X_SIGNAL_LONG; + + // + color tpColor = longColor; + color slColor = shortColor; + + // + string name = "T(" + (string)signal.ticket + ")" + "_" + "TY(" + EnumToString(signal.type) + ")"; + + // + string tpName = "TP_" + name; + if (IsDrawExists(tpName)) + { + RemoveDraw(tpName); + } + + // + string slName = "SL_" + name; + if (IsDrawExists(slName)) + { + RemoveDraw(slName); + } + + // + string riskFreeName = "RF_" + name; + if (IsDrawExists(riskFreeName)) + { + RemoveDraw(riskFreeName); + } + + // + string entryName = "Entry_" + name; + if (IsDrawExists(entryName)) + { + RemoveDraw(entryName); + } + + // + string vlName = "Time_" + name; + if (IsDrawExists(vlName)) + { + RemoveDraw(vlName); + } + + // + int signalBarIndex = iBarShift( + signal.symbol, + _Period, + signal.time); + + // + datetime time1 = iTime( + signal.symbol, + _Period, + signalBarIndex + 1); + datetime time2 = iTime( + signal.symbol, + _Period, + signalBarIndex - 1); + + // + // Entry ... + bool isTrendLineDrawn = DrawTrendLine( + 0, + entryName, + 0, + time1, + signal.entry, + time2, + signal.entry, + entryColor); + + // + // TP ... + bool isTPDrawn = false; + if (signal.tp > 0) + { + // + isTPDrawn = DrawTrendLine( + 0, + tpName, + 0, + time1, + signal.tp, + time2, + signal.tp, + tpColor, + STYLE_SOLID, + 1, + false, + true); + } + + // + // RISKFREE ... + bool isRFDrawn = false; + if (signal.riskFreeStep > 0) + { + // + double firstStepPrice = isLong ? signal.entry + PipsToPrice(signal.riskFreeStep) + : signal.entry - PipsToPrice(signal.riskFreeStep); + + // + isRFDrawn = DrawTrendLine( + 0, + riskFreeName, + 0, + time1, + firstStepPrice, + time2, + firstStepPrice, + tpColor, + STYLE_DOT, + 1, + false, + true); + } + + // + // SL ... + bool isSLDrawn = false; + if (signal.sl > 0) + { + // + isSLDrawn = DrawTrendLine( + 0, + slName, + 0, + time1, + signal.sl, + time2, + signal.sl, + slColor, + STYLE_SOLID, + 1, + false, + true); + } + + // + // Draw a Vertical Line ... + bool isVerticalLineDrawn = DrawVerticalLine( + 0, + vlName, + 0, + signal.time, + slColor); +} + +// +// remove drawn objects ... +void RemoveDraws( + string tag = NULL, + int chartId = -1, + int subWindow = -1) +{ + // + // Normalize Args ... + // + if (tag == NULL) + { + tag = drawPrefix; + } + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + if (StringFind(on, tag) >= 0) + { + ObjectDelete(chartId, on); + } + } + + // + // Redraw Chart ... + ChartRedraw(); +} + +// +bool RemoveDraw( + string name, + int chartId = -1, + int subWindow = -1) +{ + // + bool result = false; + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + string objName = ""; + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + if (StringFind(on, name) >= 0) + { + // + objName = on; + break; + } + } + + // + if (StringLen(objName) > 0) + { + result = ObjectDelete(chartId, objName); + } + + // + return result; +} + +// +// Check Object Exists ... +bool IsDrawExists( + string name, + int chartId = -1, + int subWindow = -1) +{ + // + bool result = false; + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + result = StringFind(on, name) >= 0; + if (result) + { + break; + } + } + + // + return result; +} +// +// END Provided Functions ... +// + +// +// START Regular Draws ... +// + +// +// START Arrow Functions ... +// +// +// Draw an Arrow Object on Chart ... +bool DrawArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow", // arrow name + const int subWindow = 0, // subwindow index + datetime time = 0, // anchor point time + double price = 0, // anchor point price + const uchar arrowCode = 252, // arrow code + const ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, // anchor point position + const color clr = clrAqua, // arrow color + const ENUM_LINE_STYLE style = STYLE_SOLID, // border line style + const int width = 3, // arrow size + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // Order Object ... +) +{ + // + // set anchor point coordinates if they are not set ... + ChangeArrowEmptyPoint(time, price); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create an arrow ... + if (!ObjectCreate(chartID, objName, OBJ_ARROW, subWindow, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create an arrow! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set the arrow code ... + ObjectSetInteger(chartID, objName, OBJPROP_ARROWCODE, arrowCode); + + // + // set anchor type ... + ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); + + // + // set the arrow color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set the border line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set the arrow's size ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the arrow by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is false by default, if you want making it possible to highlight and move the object + // change it to true ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Move the anchor point of Arrow ... +bool MoveArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // reset the error value + ResetLastError(); + + // + // move the anchor point ... + if (!ObjectMove(chartID, name, 0, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete an arrow ... +bool DeleteArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow" // arrow name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete an arrow ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete an arrow! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Change the arrow code ... +bool ArrowCodeChange( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + const uchar code = 252 // arrow code +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change the arrow code ... + if (!ObjectSetInteger(chartID, name, OBJPROP_ARROWCODE, code)) + { + // + string message = + __FUNCTION__ + + ": failed to change the arrow code! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Change anchor type ... +bool ArrowAnchorChange( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + const ENUM_ARROW_ANCHOR anchor = ANCHOR_TOP // anchor type +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change anchor type ... + if (!ObjectSetInteger(chartID, name, OBJPROP_ANCHOR, anchor)) + { + // + string message = + __FUNCTION__ + + ": failed to change anchor type! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Check anchor point values and set default values +// for empty ones ... +void ChangeArrowEmptyPoint( + datetime &time, + double &price) +{ + // + // if the point's time is not set, it will be on the current bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // if the point's price is not set, it will have Bid value ... + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } +} +// +// END Arrow Functions ... +// + +// +// START Horizontal Line Functions ... +// +// +// Create, Draw the horizontal line ... +bool DrawHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine", // line name + const int subWindow = 0, // subwindow index + double price = 0, // line price + const color clr = clrRed, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // if the price is not set, set it at the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a horizontal line ... + if (!ObjectCreate(chartID, objName, OBJ_HLINE, subWindow, 0, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create a horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Move horizontal line ... +bool MoveHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine", // line name + double price = 0 // line price +) +{ + // + // if the line price is not set, move it to the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move a horizontal line ... + if (!ObjectMove(chartID, name, 0, 0, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete a horizontal line ... +bool DeleteHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete a horizontal line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} +// +// END Horizontal Line Functions ... +// + +// +// START Vertical Line Functions ... +// +// +// Create the vertical line ... +bool DrawVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine", // line name + const int sub_window = 0, // subwindow index + datetime time = 0, // line time + const color clr = clrRed, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // if the line time is not set, draw it via the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a vertical line ... + if (!ObjectCreate(chartID, objName, OBJ_VLINE, sub_window, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create a vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return true; +} + +// +// Move the vertical line ... +bool MoveVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine", // line name + datetime time = 0 // line time +) +{ + // + // if line time is not set, move the line to the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the vertical line ... + if (!ObjectMove(chartID, name, 0, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to move the vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete the vertical line ... +bool DeleteVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the vertical line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete the vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} +// +// END Vertical Line Functions ... +// + +// +// START RectangleLabel Functions ... +// +// +// Create Rectangle Label Object ... +bool DrawRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int subWindow = 0, // subwindow index + const int x = 0, // X coordinate + const int y = 0, // Y coordinate + const int width = 50, // width + const int height = 18, // height + const color back_clr = clrWhiteSmoke, // background color + const ENUM_BORDER_TYPE border = BORDER_SUNKEN, // border type + const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // chart corner for anchoring + const color clr = clrRed, // flat border color (Flat) + const ENUM_LINE_STYLE style = STYLE_SOLID, // flat border style + const int lineWidth = 1, // flat border width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + //--- create a rectangle label + if (!ObjectCreate(chartID, objName, OBJ_RECTANGLE_LABEL, subWindow, 0, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create a rectangle label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set label coordinates ... + ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); + ObjectSetInteger(chartID, objName, OBJPROP_YDISTANCE, y); + + // + // set label size ... + ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); + ObjectSetInteger(chartID, objName, OBJPROP_YSIZE, height); + + // + // set background color ... + ObjectSetInteger(chartID, objName, OBJPROP_BGCOLOR, back_clr); + + // + // set border type ... + ObjectSetInteger(chartID, objName, OBJPROP_BORDER_TYPE, border); + + // + // set the chart's corner, relative to which point coordinates are defined ... + ObjectSetInteger(chartID, objName, OBJPROP_CORNER, corner); + + // + // set flat border color (in Flat mode) ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set flat border line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set flat border width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, lineWidth); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the label by mouse ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Move Rectangle Label .. +bool MoveRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int x = 0, // X coordinate + const int y = 0 // Y coordinate +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // move the rectangle label ... + if (!ObjectSetInteger(chartID, name, OBJPROP_XDISTANCE, x)) + { + // + string message = + __FUNCTION__ + + ": failed to move X coordinate of the label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + if (!ObjectSetInteger(chartID, name, OBJPROP_YDISTANCE, y)) + { + // + string message = + __FUNCTION__ + + ": failed to move Y coordinate of the label! Error code = " + + (string)GetLastError(); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete the rectangle label ... +bool DeleteRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel" // label name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the label ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a rectangle label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Change Rectangle Label Size ... +bool ChangeSizeRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int width = 50, // label width + const int height = 18 // label height +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change label size ... + if (!ObjectSetInteger(chartID, name, OBJPROP_XSIZE, width)) + { + // + string message = + __FUNCTION__ + + ": failed to change the label's width! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + if (!ObjectSetInteger(chartID, name, OBJPROP_YSIZE, height)) + { + // + string message = + __FUNCTION__ + + ": failed to change the label's height! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Change rectangle label border type ... +bool RectLabelChangeBorderType( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const ENUM_BORDER_TYPE border = BORDER_SUNKEN // border type +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change border type ... + if (!ObjectSetInteger(chartID, name, OBJPROP_BORDER_TYPE, border)) + { + // + string message = + __FUNCTION__ + + ": failed to change the border type! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} +// +// END RectangleLabel Functions ... +// + +// +// START TrendLine Funcions ... +// +// Create a trend line by the given coordinates ... +bool DrawTrendLine( + const long chartID = 0, // chart's ID + const string name = "TrendLine", // line name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrYellow, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool rayRight = false, // line's continuation to the right + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeTrendLineEmptyPoints( + time1, + price1, + time2, + price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a trend line by the given coordinates ... + if (!ObjectCreate(chartID, objName, OBJ_TREND, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create a trend line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable (true) or disable (false) the mode of continuation of the line's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Move trend line anchor point ... | +bool ChangeTrendLinePoint( + const long chartID = 0, // chart's ID + const string name = "TrendLine", // line name + const int pointindex = 0, // anchor point index + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move trend line's anchor point ... + if (!ObjectMove(chartID, name, pointindex, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// The function deletes the trend line from the chart ... +bool DeleteTrendLine( + const long chartID = 0, // chart's ID + const string name = "TrendLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete a trend line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a trend line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Check the values of trend line's anchor points and set default ... +// values for empty ones ... +void ChangeTrendLineEmptyPoints( + datetime &time1, + double &price1, + datetime &time2, + double &price2) +{ + // + // if the first point's time is not set, it will be on the current bar ... + if (!time1) + { + time1 = TimeCurrent(); + } + + // + // if the first point's price is not set, it will have Bid value ... + if (!price1) + { + price1 = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // if the second point's time is not set, it is located 9 bars left from the second one ... + if (!time2) + { + // + // array for receiving the open time of the last 10 bars ... + datetime temp[10]; + CopyTime(Symbol(), Period(), time1, 10, temp); + + // + // set the second point 9 bars left from the first one ... + time2 = temp[0]; + } + + // + // if the second point's price is not set, it is equal to the first point's one ... + if (!price2) + { + price2 = price1; + } +} +// +// END TrendLine Functions ... +// + +// +// START Text Functions ... +// +// Create and Draw a Text Object ... +bool DrawText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + const int subWindow = 0, // subwindow index + datetime time = 0, // anchor point time + double price = 0, // anchor point price + const string text = "Text", // the text itself + const string font = "Arial", // font + const int fontSize = 10, // font size + const color clr = clrRed, // color + const double angle = 0.0, // text slope + const ENUM_ANCHOR_POINT anchor = ANCHOR_CENTER, // anchor type + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // set anchor point coordinates if they are not set ... + ChangeTextEmptyPoint(time, price); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + //--- create Text object + if (!ObjectCreate(chartID, objName, OBJ_TEXT, subWindow, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Text\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set the text ... + ObjectSetString(chartID, objName, OBJPROP_TEXT, text); + + // + // set text font ... + ObjectSetString(chartID, objName, OBJPROP_FONT, font); + + // + // set font size ... + ObjectSetInteger(chartID, objName, OBJPROP_FONTSIZE, fontSize); + + // + // set the slope angle of the text ... + ObjectSetDouble(chartID, objName, OBJPROP_ANGLE, angle); + + // + // set anchor type ... + ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving the object by mouse ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Move the anchor point ... +bool MoveText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + //--- if point position is not set, move it to the current bar having Bid price + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the anchor point .. + if (!ObjectMove(chartID, name, 0, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Change the object text ... +bool ChangeText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + const string text = "Text" // text +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change object text ... + if (!ObjectSetString(chartID, name, OBJPROP_TEXT, text)) + { + // + string message = + __FUNCTION__ + + ": failed to change the text! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete Text object ... +bool DeleteText( + const long chartID = 0, // chart's ID + const string name = "Text" // object name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the object ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Text\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution + return (true); +} + +// +// Check anchor point values and set default values +// for empty ones ... +void ChangeTextEmptyPoint( + datetime &time, + double &price) +{ + // + // if the point's time is not set, it will be on the current bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // if the point's price is not set, it will have Bid value ... + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } +} +// +// END Text Functions ... +// + +// +// START Fibonacchi Functions ... +// +// +// Create Fibonacci Retracement by the given coordinates ... +bool DrawFibonacci( + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrRed, // object color + const ENUM_LINE_STYLE style = STYLE_SOLID, // object line style + const int width = 1, // object line width + const bool back = false, // in the background + const bool selection = true, // highlight to move + const bool rayRight = false, // object's continuation to the right + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + if (!ObjectCreate(chartID, objName, OBJ_FIBO, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of highlighting the channel for moving + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable (true) or disable (false) the mode of continuation of the object's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return (true); +} + +// +// Create Fibonacci Retracement by the given coordinates ... +bool DrawCustomFibonacci( + // + int levels, // number of level lines + double &values[], // values of level lines + color &colors[], // color of level lines + ENUM_LINE_STYLE &styles[], // style of level lines + int &widths[], // width of level lines + string &descriptions[], // level Descriptions + // + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrAqua, // object color + const ENUM_LINE_STYLE style = STYLE_DOT, // object line style + const int width = 1, // object line width + const bool back = false, // in the background + const bool selection = true, // highlight to move + const bool rayRight = false, // object's continuation to the right + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + if (!ObjectCreate(chartID, name, OBJ_FIBO, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of highlighting the channel for moving + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable (true) or disable (false) the mode of continuation of the object's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // Change Levels Of Fibonacci ... + bool result = FibonacciLevelsSet( + levels, + values, + colors, + styles, + widths, + descriptions, + chartID, + objName); + + // + // successful execution ... + return result; +} + +// +// Set number of levels and their parameters ... +bool FibonacciLevelsSet( + int levels, // number of level lines + double &values[], // values of level lines + color &colors[], // color of level lines + ENUM_LINE_STYLE &styles[], // style of level lines + int &widths[], // width of level lines + string &descriptions[], // level Descriptions + const long chartID = 0, // chart's ID + const string name = "Fibonacci" // object name +) +{ + // + // check array sizes ... + if ( + levels != ArraySize(colors) || + levels != ArraySize(styles) || + levels != ArraySize(widths) || + levels != ArraySize(widths)) + { + // + string message = + __FUNCTION__ + + ": array length does not correspond to the number of levels, error!"; + + // + LogMessage(message); + + // + return (false); + } + + // + // set the number of levels ... + ObjectSetInteger(chartID, name, OBJPROP_LEVELS, levels); + + // + // set the properties of levels in the loop ... + for (int i = 0; i < levels; i++) + { + // + // level value ... + ObjectSetDouble(chartID, name, OBJPROP_LEVELVALUE, i, values[i]); + + // + // level color ... + ObjectSetInteger(chartID, name, OBJPROP_LEVELCOLOR, i, colors[i]); + + // + // level style ... + ObjectSetInteger(chartID, name, OBJPROP_LEVELSTYLE, i, styles[i]); + + // + // level width ... + ObjectSetInteger(chartID, name, OBJPROP_LEVELWIDTH, i, widths[i]); + + // + // level description ... + // ObjectSetString(chartID, name, OBJPROP_LEVELTEXT, i, DoubleToString(100 * values[i], 1)); + ObjectSetString(chartID, name, OBJPROP_LEVELTEXT, i, descriptions[i]); + } + + // + // successful execution ... + return (true); +} + +// +// Move Fibonacci Retracement anchor point ... +bool FibonacciPointChange( + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int pointIndex = 0, // anchor point index + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the anchor point ... + if (!ObjectMove(chartID, name, pointIndex, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Delete Fibonacci Retracement ... +bool DeleteFibonachi( + const long chartID = 0, // chart's ID + const string name = "Fibonacci" // object name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the object ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution ... + return (true); +} + +// +// Check the values of Fibonacci Retracement anchor points and set +// default values for empty ones ... +void ChangeFibonacciEmptyPoints( + datetime &time1, + double &price1, + datetime &time2, + double &price2) +{ + // + // if the second point's time is not set, it will be on the current bar ... + if (!time2) + { + time2 = TimeCurrent(); + } + + // + // if the second point's price is not set, it will have Bid value ... + if (!price2) + { + price2 = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // if the first point's time is not set, it is located 9 bars left from the second one ... + if (!time1) + { + // + // array for receiving the open time of the last 10 bars ... + datetime temp[10]; + CopyTime(Symbol(), Period(), time2, 10, temp); + + // + // set the first point 9 bars left from the second one ... + time1 = temp[0]; + } + + // + // if the first point's price is not set, move it 200 points below the second one ... + if (!price1) + { + price1 = price2 - 200 * SymbolInfoDouble(_Symbol, SYMBOL_POINT); + } +} +// +// END Fibonacci Functions ... +// + +// +// START Event Functions ... +// + +// +// Create an Event ... +bool EventCreate( + const long chartID = 0, // chart's ID + const string name = "Event", // object name + const int subWindow = 0, // subwindow index + const string text = "Content", // event text + datetime time = 0, // anchor point time + const color clr = clrRed, // color + const int width = 1, // point width when highlighted + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + if (!time) + { + time = TimeCurrent(); + } + + // + ResetLastError(); + + // + if (!ObjectCreate(chartID, name, OBJ_EVENT, subWindow, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // set event text + ObjectSetString(chartID, name, OBJPROP_TEXT, text); + + // + // set color + ObjectSetInteger(chartID, name, OBJPROP_COLOR, clr); + + // + // set anchor point width if the object is highlighted + ObjectSetInteger(chartID, name, OBJPROP_WIDTH, width); + + // + // display in the foreground (false) or background (true) + ObjectSetInteger(chartID, name, OBJPROP_BACK, back); + + // + // enable (true) or disable (false) the mode of moving event by mouse + ObjectSetInteger(chartID, name, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, name, OBJPROP_SELECTED, selection); + + // + // hide (true) or display (false) graphical object name in the object list + ObjectSetInteger(chartID, name, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart + ObjectSetInteger(chartID, name, OBJPROP_ZORDER, zOrder); + + // + // successful execution + return (true); +} + +// +// Change Event object text +bool EventTextChange( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + const string text = "Content" // text +) +{ + // + // reset the error value + ResetLastError(); + + // + // change object text + if (!ObjectSetString(chartID, name, OBJPROP_TEXT, text)) + { + // + string message = + __FUNCTION__ + + ": failed to change the text! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution + return (true); +} + +// +// Move Event object +bool EventMove( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + datetime time = 0 // time +) +{ + // + // if time is not set, move event to the last bar + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value + ResetLastError(); + + // + // move the object + if (!ObjectMove(chartID, name, 0, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to move \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution + return (true); +} + +// +// Delete Event object +bool EventDelete( + const long chartID = 0, // chart's ID + const string name = "Event" // event name +) +{ + // + // reset the error value + ResetLastError(); + + // + // delete the object + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return (false); + } + + // + // successful execution + return (true); +} + +// +// END Event Functions ... +// + +// +// END Regular Draws ... +// + +// +// START Chart Style Drawers ... +// +// +// Apply Styles On Chart ... +void ApplyChartStyle( + int chartId = -1, // chart's ID + ENUM_CHART_MODE mode = CHART_CANDLES, // chart's mode + bool showBidLine = true, // show bid line + bool showAskLine = true, // show ask line + bool showGrid = false, // show grids on chart + bool showVolumes = false, // show volumes + bool showTradeLevels = true, // Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders) + bool autoScroll = true, // chart autoscroll + bool quickNavigation = true, // chart quick navigation state + color foreGroundColor = clrWhite, // chart's foreground color + color backGroundColor = clrBlack, // chart's background color + color upColor = clrGreen, // Up Color + color downColor = clrRed, // Down Color + color bullishColor = clrGreen, // Bullish color + color bearishColor = clrRed, // Bearish color + color gridColor = clrGray, // grid color + color bidLineColor = clrGray, // bid line color + color askLineColor = clrRed, // ask line color + color lineColor = clrLime, // line mode and doji candlestick color + color stopColor = clrGold, // Color of stop order levels (Stop Loss and Take Profit) + color volumesColor = clrGreen // volumes color +) +{ + // + // Validate Args ... + if (chartId == -1) + { + chartId = 0; + } + + // + ChartSetInteger(chartId, CHART_MODE, mode); + ChartSetInteger(chartId, CHART_SHOW_BID_LINE, showBidLine); + ChartSetInteger(chartId, CHART_SHOW_ASK_LINE, showAskLine); + ChartSetInteger(chartId, CHART_SHOW_GRID, showGrid); + ChartSetInteger(chartId, CHART_SHOW_VOLUMES, showVolumes); + ChartSetInteger(chartId, CHART_SHOW_TRADE_LEVELS, showTradeLevels); + ChartSetInteger(chartId, CHART_AUTOSCROLL, autoScroll); + ChartSetInteger(chartId, CHART_QUICK_NAVIGATION, quickNavigation); + ChartSetInteger(chartId, CHART_COLOR_FOREGROUND, foreGroundColor); + ChartSetInteger(chartId, CHART_COLOR_BACKGROUND, backGroundColor); + ChartSetInteger(chartId, CHART_COLOR_CHART_UP, upColor); + ChartSetInteger(chartId, CHART_COLOR_CHART_DOWN, downColor); + ChartSetInteger(chartId, CHART_COLOR_CANDLE_BULL, bullishColor); + ChartSetInteger(chartId, CHART_COLOR_CANDLE_BEAR, bearishColor); + ChartSetInteger(chartId, CHART_COLOR_GRID, gridColor); + ChartSetInteger(chartId, CHART_COLOR_BID, bidLineColor); + ChartSetInteger(chartId, CHART_COLOR_ASK, askLineColor); + ChartSetInteger(chartId, CHART_COLOR_STOP_LEVEL, stopColor); + ChartSetInteger(chartId, CHART_COLOR_CHART_LINE, lineColor); + ChartSetInteger(chartId, CHART_COLOR_VOLUME, volumesColor); +} +// +// END Chart Style Drawers ... +// \ No newline at end of file diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.http.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.http.lib.mq5 new file mode 100644 index 00000000..97f7ac0a --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.http.lib.mq5 @@ -0,0 +1,177 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Http Library +// ------------------------------------------ +// Name: XHttp +// Description: provide http communication +// abilities ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Model Definition ... +// +enum X_HTTP_METHOD +{ + X_HTTP_GET, + X_HTTP_POST +}; +// +// END Model Definition ... +// + +// +// START Inputs ... +// +// +// END Inputs ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Initial Library if required ... +bool OnInInitHttpLibrary() +{ + return false; +} + +// +// DeInitial Library if required ... +void OnDeinitHttpLibrary() +{ +} + +// +// Convert enum to String ... +string ToString(X_HTTP_METHOD method) +{ + // + string result = ""; + + // + switch (method) + { + // + case X_HTTP_GET: + result = "GET"; + break; + + // + case X_HTTP_POST: + result = "POST"; + break; + } + + // + return result; +} + +// +// Send Global Request ... +int SendRequest( + X_HTTP_METHOD method, // Httm Request Method + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 +) +{ + // + int result = -1; + + // + string strMethod = ToString(method); + if (StringLen(strMethod) == 0) { + return result; + } + + // + result = WebRequest( + strMethod, + url, + headers, + timeout, + payload, + response, + responseHeaders + ); + + // + return result; +} + +// +// Get Request ... +int GetRequest( + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 +) { + // + int result = SendRequest( + X_HTTP_GET, + url, + headers, + payload, + response, + responseHeaders, + timeout + ); + + // + return result; +} + +// +// Post Request ... +int PostRequest( + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 +) { + // + int result = SendRequest( + X_HTTP_POST, + url, + headers, + payload, + response, + responseHeaders, + timeout + ); + + // + return result; +} +// +// END Provided Functions ... +// diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.log.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.log.lib.mq5 new file mode 100644 index 00000000..70f1bda4 --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.log.lib.mq5 @@ -0,0 +1,261 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Logger Library +// --------------------------------------- +// Name: XLogger +// Description: provides Logging abilities ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Inputs ... +// +input group "Logging"; +input bool enableLogging = true; // Enable Logging +// +// END Inputs ... +// + +// +// Including Models ... +#include "x-saherelm.models.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string logTag = "X-Logger"; // LogTag +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Logging a Message ... +void LogMessage(string message) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, " > ", message); +} +void LogMessage(string tag, string message) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(tag, " > ", message); +} + +// +// Logging an Array ... +void LogArray(int &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} +void LogArray(double &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} +void LogArray(string &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} + +// +// Convert a Signal to String Message ... +string SignalToString(const XSignal &signal) +{ + // + string result = "\n"; + + // + result += "Signal: " + "\n"; + result += "id: " + (string)signal.id + "\n"; + result += "symbol: " + signal.symbol + "\n"; + result += "type: " + EnumToString(signal.type) + "\n"; + result += "magicNumber: " + (string)signal.magicNumber + "\n"; + result += "ticket: " + (string)signal.ticket + "\n"; + result += "entry: " + (string)signal.entry + "\n"; + result += "tp: " + (string)signal.tp + "\n"; + result += "sl: " + (string)signal.sl + "\n"; + result += "riskFreeStep: " + (string)signal.riskFreeStep + "\n"; + result += "riskFreeRate: " + (string)signal.riskFreeRate + "\n"; + result += "profit: " + (string)signal.profit + "\n"; + result += "time: " + (string)signal.time + "\n"; + result += "volume: " + (string)signal.volume + "\n"; + result += "comment: " + signal.comment + "\n"; + + // + return result; +} + +// +// Convert an Executed Signal to String Message ... +string ExecutedSignalToString(const XSignal &signal) +{ + // + string result = ""; + + // + result += (signal.type == X_SIGNAL_LONG ? "Buy" : "Sell") + " Signal Executed provided on (" + signal.symbol + " _ " + EnumToString(_Period) + ") by this comment: " + signal.comment; + + // + return result; +} + +// +// Logging Signal ... +void LogSignal(const XSignal &signal) +{ + // + string message = SignalToString(signal); + + // + LogMessage(message); +} + +// +// Log Signal Execution ... +void LogExecutedSignal(const XSignal &signal) +{ + // + string message = ExecutedSignalToString(signal); + + // + LogMessage(message); +} + +// +// Convert a Deal to String ... +string DealToString(const XDeal &deal) +{ + // + string result = "\n"; + + // + result += "Deal:" + "\n"; + result += " " + "\n"; + result += "time: " + (string)deal.time + "\n"; + result += "ticket: " + (string)deal.ticket + "\n"; + result += "order: " + (string)deal.order + "\n"; + result += "positionId: " + (string)deal.positionId + "\n"; + result += "type: " + EnumToString(deal.type) + "\n"; + result += "entry: " + EnumToString(deal.entry) + "\n"; + result += "reason: " + EnumToString(deal.reason) + "\n"; + result += "symbol: " + deal.symbol + "\n"; + result += "price: " + (string)deal.price + "\n"; + result += "profit: " + (string)deal.profit + "\n"; + result += "swap: " + (string)deal.swap + "\n"; + result += "commission: " + (string)deal.commission + "\n"; + result += "volume: " + (string)deal.volume + "\n"; + result += "comment: " + deal.comment + "\n"; + + // + return result; +} + +// +// Log Specific Deal ... +void LogDeal(const XDeal &deal) +{ + // + string message = DealToString(deal); + + // + LogMessage(message); +} + +// +// Convert an Order to String ... +string OrderToString(const XOrder &order) +{ + // + string result = "\n"; + + // + result += "Order: " + "\n"; + result += "magic: " + (string)order.magic + "\n"; + result += "positionId: " + (string)order.positionId + "\n"; + result += "symbol: " + (string)order.symbol + "\n"; + result += "ticket: " + (string)order.ticket + "\n"; + result += "timeSetup: " + (string)order.timeSetup + "\n"; + result += "timeDone: " + (string)order.timeDone + "\n"; + result += "timeExpiration: " + (string)order.timeExpiration + "\n"; + result += "priceOpen: " + (string)order.priceOpen + "\n"; + result += "priceCurrent: " + (string)order.priceCurrent + "\n"; + result += "priceStopLimit: " + (string)order.priceStopLimit + "\n"; + result += "stopLoss: " + (string)order.stopLoss + "\n"; + result += "takeProfit: " + (string)order.takeProfit + "\n"; + result += "volumeInitial: " + (string)order.volumeInitial + "\n"; + result += "volumeCurrent: " + (string)order.volumeCurrent + "\n"; + result += "comment: " + order.comment + "\n"; + result += "type: " + EnumToString(order.type) + "\n"; + result += "state: " + EnumToString(order.state) + "\n"; + result += "typeFilling: " + EnumToString(order.typeFilling) + "\n"; + result += "typeTime: " + EnumToString(order.typeTime) + "\n"; + result += "reason: " + EnumToString(order.reason) + "\n"; + + // + return result; +} + +// +// Log Specific Order ... +void LogOrder(const XOrder &order) +{ + // + string message = OrderToString(order); + + // + LogMessage(message); +} + +// +// END Provided Functions ... +// diff --git a/Projects/XUSCHF5/Libraries/x-saherelm.models.lib.mq5 b/Projects/XUSCHF5/Libraries/x-saherelm.models.lib.mq5 new file mode 100644 index 00000000..b98ae3e8 --- /dev/null +++ b/Projects/XUSCHF5/Libraries/x-saherelm.models.lib.mq5 @@ -0,0 +1,438 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Models Library +// --------------------------------------- +// Name: XModels +// Description: provides all required models ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Inputs ... +// +// +// END Inputs ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// + +// +// How To Calculate Static Volume ... +enum ENUM_STATIC_VOLUME_METHODS +{ + // + // Based On Deposit ... + X_STATIC_VOLUME_BASED_ON_DEPOSIT, + // + // Based On Balance ... + X_STATIC_VOLUME_BASED_ON_BALANCE, +}; + +// +// START Model Definitions ... +// +// +// OHCL Candel Model ... +enum ENUM_X_PRICE +{ + X_PRICE_HIGH, + X_PRICE_OPEN, + X_PRICE_CLOSE, + X_PRICE_LOW +}; + +// +// Describe an Specific Candle ... +struct XOHCL +{ + double high; + double open; + double close; + double low; +}; + +// +// Swing Types Enum ... +enum ENUM_X_SWING_TYPE +{ + X_NO_SWING = 0, + X_SWING_HIGH = 1, + X_SWING_LOW = -1, +}; + +// +// XTrader Execution Signal Result ... +enum ENUM_EXECUTION_SIGNAL_RESULT +{ + // + X_TRADER_UNKNOWN_ERROR, + X_TRADER_SUCCEED_EXECUTION, + X_TRADER_INVALID_SIGNAL_ERROR, + X_TRADER_NOT_ENOUGH_EQUITY_ERROR, + X_TRADER_MAX_TRADES_REACHED_ERROR, + X_TRADER_NOT_ENOUGH_BALANCE_ERROR, + X_TRADER_NOT_ENOUGH_MARIGIN_ERROR + // +}; + +// +// Signal Types ... +enum ENUM_X_SIGNAL_TYPE +{ + X_SIGNAL_LONG, + X_SIGNAL_SHORT, + X_SIGNAL_UNKNOWN, +}; + +// +// Signal Structure ... +struct XSignal +{ + // + // Identifier ... + ulong id; + + // + // Which Symbol used for Signal ... + string symbol; + + // + // Which Type of operations ... + ENUM_X_SIGNAL_TYPE type; + + // + // Magic Number ... + ulong magicNumber; + + // + // Ticket ... + ulong ticket; + + // + // Entry/Open Price ... + double entry; + + // + // TP ... + double tp; + + // + // SL ... + double sl; + + // + // Make Risk Free Trade on this Value if provided ... + double riskFreeStep; + + // + // a Multiplier for determines how much trade volume exit on risk free time ... + double riskFreeRate; + + // + // Trade Profit ... + double profit; + + // + // Time of Operation ... + datetime time; + + // + // Volume ... + double volume; + + // + // Comment ... + string comment; +}; + +// +// Signal Additional Info ... +struct XProvidedSignal +{ + // + // Suggested TP ... + double tp; + + // + // Suggested SL ... + double sl; + + // + // Signallers ... + string signallers[]; +}; + +// +// Model Specific Deal ... +struct XDeal +{ + // + // the ID of the Expert Advisor, that executed the deal ... + ulong magic; + + // + // the ID of position, in which the deal was involved ... + ulong positionId; + + // + // Ticket ... + ulong ticket; + + // + // the name of the deal symbol ... + string symbol; + + // + // order by which the deal is executed ... + ulong order; + + // + // the time of deal execution ... + datetime time; + + // + // Deal price ... + double price; + + // + // the financial result of the deal (in deposit currency) ... + double profit; + + // + // the amount of swap when position is closed ... + double swap; + + // + // the amount of commission of the deal ... + double commission; + + // + // the volume of deal ... + double volume; + + // + // the deal comment ... + string comment; + + // + // the deal type ... + // ------------------------------------------------------------------ + // DEAL_TYPE_BUY => Buy ... + // DEAL_TYPE_SELL => Sell ... + // DEAL_TYPE_BUY_CANCELED => Canceled buy deal ... + // There can be a situation when a previously executed buy deal is canceled. In this case, + // the type of the previously executed deal (DEAL_TYPE_BUY) is changed to DEAL_TYPE_BUY_CANCELED, + // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation ... + // + // DEAL_TYPE_SELL_CANCELED => Canceled sell deal ... + // There can be a situation when a previously executed sell deal is canceled. In this case, + // the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, + // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation + // + // DEAL_TYPE_BALANCE => Balance ... + // DEAL_TYPE_CREDIT => Credit ... + // DEAL_TYPE_CHARGE => Additional charge ... + // DEAL_TYPE_CORRECTION => Correction ... + // DEAL_TAX => Tax charges ... + // DEAL_TYPE_BONUS => Bonus ... + // DEAL_TYPE_INTEREST => Interest rate ... + // DEAL_DIVIDEND => Dividend operations... + // DEAL_DIVIDEND_FRANKED => Franked (non-taxable) dividend operations ... + // DEAL_TYPE_COMMISSION => Additional commission ... + // DEAL_TYPE_COMMISSION_DAILY => Daily commission ... + // DEAL_TYPE_COMMISSION_MONTHLY => Monthly commission ... + // DEAL_TYPE_COMMISSION_AGENT_DAILY => Daily agent commission ... + // DEAL_TYPE_COMMISSION_AGENT_MONTHLY => Monthly agent commission + ENUM_DEAL_TYPE type; + + // + // the deal direction ... + // ---------------------------------- + // DEAL_ENTRY_IN => Entry in ... + // DEAL_ENTRY_OUT => Entry out ... + // DEAL_ENTRY_INOUT => Reverse ... + // DEAL_ENTRY_OUT_BY => Close a position by an opposite one ... + ENUM_DEAL_ENTRY entry; + + // + // deal reson ... + // --------------------- + // DEAL_REASON_SL => The deal was executed as a result of Stop Loss activation ... + // DEAL_REASON_TP => The deal was executed as a result of Take Profit activation ... + // DEAL_REASON_SO => The deal was executed as a result of the Stop Out event ... + // DEAL_REASON_WEB => The deal was executed as a result of activation of an order placed from the web platform ... + // DEAL_REASON_SPLIT => The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement ... + // DEAL_REASON_CLIENT => The deal was executed as a result of activation of an order placed from a desktop terminal ... + // DEAL_REASON_MOBILE => The deal was executed as a result of activation of an order placed from a mobile application ... + // DEAL_REASON_EXPERT => The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script ... + // DEAL_REASON_VMARGIN => The deal was executed after charging the variation margin ... + // DEAL_REASON_ROLLOVER => The deal was executed due to a rollover ... + ENUM_DEAL_REASON reason; +}; + +// +// Model Specific Order ... +struct XOrder +{ + // + // the ID of expert that placed the order ... + ulong magic; + + // + // the ID of position ... + ulong positionId; + + // + // the name of order symbol ... + string symbol; + + // + // the ticket of an order, previously selected for access ... + ulong ticket; + + // + // the time of order placement ... + datetime timeSetup; + + // + // the time of order execution or cancellation ... + datetime timeDone; + + // + // the order expiration time ... + datetime timeExpiration; + + // + // the order price ... + double priceOpen; + + // + // the current price by order symbol ... + double priceCurrent; + + // + // the price of a pending order ... + double priceStopLimit; + + // + // the order's Stop Loss ... + double stopLoss; + + // + // the order's Take Profit ... + double takeProfit; + + // + // the initial volume of order ... + double volumeInitial; + + // + // the unfilled volume of order ... + double volumeCurrent; + + // + // the order comment ... + string comment; + + // + // the order type ... + // -------------------- + // ORDER_TYPE_BUY => Market Buy order ... + // ORDER_TYPE_SELL => Market Sell order ... + // ORDER_TYPE_BUY_LIMIT => Buy Limit pending order ... + // ORDER_TYPE_SELL_LIMIT => Sell Limit pending order ... + // ORDER_TYPE_BUY_STOP => Buy Stop pending order ... + // ORDER_TYPE_SELL_STOP => Sell Stop pending order ... + // ORDER_TYPE_BUY_STOP_LIMIT => Upon reaching the order price, a pending Buy Limit order is placed at the StopLimit price ... + // ORDER_TYPE_SELL_STOP_LIMIT => Upon reaching the order price, a pending Sell Limit order is placed at the StopLimit price ... + // ORDER_TYPE_CLOSE_BY => Order to close a position by an opposite one ... + ENUM_ORDER_TYPE type; + + // + // the order state ... + // -------------------------- + // ORDER_STATE_STARTED => Order checked, but not yet accepted by broker ... + // ORDER_STATE_PLACED => Order accepted ... + // ORDER_STATE_CANCELED => Order canceled by client ... + // ORDER_STATE_PARTIAL => Order partially executed ... + // ORDER_STATE_FILLED => Order fully executed ... + // ORDER_STATE_REJECTED => Order rejected ... + // ORDER_STATE_EXPIRED => Order expired ... + // ORDER_STATE_REQUEST_ADD => Order is being registered (placing to the trading system) + // ORDER_STATE_REQUEST_MODIFY => Order is being modified (changing its parameters) ... + // ORDER_STATE_REQUEST_CANCEL => Order is being deleted (deleting from the trading system) ... + ENUM_ORDER_STATE state; + + // + // the order filling type ... + // ---------------------------- + // ORDER_FILLING_FOK => Fill or Kill + // An order can be executed in the specified volume only. + // If the necessary amount of a financial instrument is currently unavailable in the market, + // the order will not be executed. + // The desired volume can be made up of several available offers. + // The possibility of using FOK orders is determined at the trade server. + // ORDER_FILLING_IOC => Immediate or Cancel + // A trader agrees to execute a deal with the volume maximally available in the market within that indicated in the order. + // If the request cannot be filled completely, an order with the available volume will be executed, + // and the remaining volume will be canceled. + // The possibility of using IOC orders is determined at the trade server. + // ORDER_FILLING_BOC => Passive (Book or Cancel) + // The BoC order assumes that the order can only be placed in the Depth of Market and cannot be immediately executed. + // If the order can be executed immediately when placed, then it is canceled. + // In fact, the BOC policy guarantees that the price of the placed order will be worse than + // the current market. BoC orders are used to implement passive trading, + // so that the order is not executed immediately when placed and does not affect current liquidity. + // Only limit and stop limit orders are supported (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT, ORDER_TYPE_BUY_STOP_LIMIT, ORDER_TYPE_SELL_STOP_LIMIT). + // ORDER_FILLING_RETURN => Return + // In case of partial filling, an order with remaining volume is not canceled but processed further. + // Return orders are not allowed in the Market Execution + // mode (market execution — SYMBOL_TRADE_EXECUTION_MARKET). + ENUM_ORDER_TYPE_FILLING typeFilling; + + // + // the type of order at the time of the expiration ... + // -------------------------------------------------------- + // ORDER_TIME_GTC => Good till cancel order ... + // ORDER_TIME_DAY => Good till current trade day order ... + // ORDER_TIME_SPECIFIED => Good till expired order ... + // ORDER_TIME_SPECIFIED_DAY => The order will be effective till 23:59:59 of the specified day. + // If this time is outside a trading session, the order expires in the nearest trading time ... + ENUM_ORDER_TYPE_TIME typeTime; + + // + // The reason for order placing ... + // -------------------------------------- + // ORDER_REASON_SL => The order was placed as a result of Stop Loss activation ... + // ORDER_REASON_TP => The order was placed as a result of Take Profit activation ... + // ORDER_REASON_SO => The order was placed as a result of the Stop Out event ... + // ORDER_REASON_WEB => The order was placed from a web platform ... + // ORDER_REASON_CLIENT => The order was placed from a desktop terminal ... + // ORDER_REASON_MOBILE => The order was placed from a mobile application ... + // ORDER_REASON_EXPERT => The order was placed from an MQL5-program, i.e. by an Expert Advisor or a script ... + ENUM_ORDER_REASON reason; +}; +// +// END Provided Functions ... +// diff --git a/Projects/XUSCHF5/Providers/.gitkeep b/Projects/XUSCHF5/Providers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/BKP/Main/Providers/x-saherelm.xuspy5.provider.indicators.lib.mq5 b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 similarity index 89% rename from BKP/Main/Providers/x-saherelm.xuspy5.provider.indicators.lib.mq5 rename to Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 index 60dbf630..d4e867fa 100644 --- a/BKP/Main/Providers/x-saherelm.xuspy5.provider.indicators.lib.mq5 +++ b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////// // -// SaherElm IT Center MQL5 XUSPY5 Signal Provider Indicators Library +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Indicators Library // ---------------------------------------------------------------- // // Maintainer: @@ -18,7 +18,7 @@ // // Include Provider Inputs ... -#include "x-saherelm.xuspy5.provider.inputs.lib.mq5" +#include "x-saherelm.xuschf5.provider.inputs.lib.mq5" // // Include Provider Class ... @@ -26,136 +26,136 @@ // // Signallers ... -input group "XUSPY5 Signallers"; +input group "XUSCHF5 Signallers"; // // XTD ... -input group "XUSPY5 XTD Signaller"; -input bool xUSPY5XTDEnableSignaller = true; // Enable Signaller -input bool xUSPY5XTDAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XTDAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XTD Signaller"; +input bool xUSCHF5XTDEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTDAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTDAllowShortSignals = true; // Enable Short Signals // // XTAM ... -input group "XUSPY5 XTAM Signaller"; -input bool xUSPY5XTAMEnableSignaller = true; // Enable Signaller -input bool xUSPY5XTAMAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XTAMAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XTAM Signaller"; +input bool xUSCHF5XTAMEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTAMAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTAMAllowShortSignals = true; // Enable Short Signals // // XSI ... -input group "XUSPY5 XSI Signaller"; -input bool xUSPY5XSIEnableSignaller = true; // Enable Signaller -input bool xUSPY5XSIAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XSIAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XSI Signaller"; +input bool xUSCHF5XSIEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XSIAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XSIAllowShortSignals = true; // Enable Short Signals // // XTSFI ... -input group "XUSPY5 XTSFI Signaller"; -input bool xUSPY5XTSFIEnableSignaller = true; // Enable Signaller -input bool xUSPY5XTSFIAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XTSFIAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XTSFI Signaller"; +input bool xUSCHF5XTSFIEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTSFIAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTSFIAllowShortSignals = true; // Enable Short Signals // // XOBDLH ... -input group "XUSPY5 XOBDLH Signaller"; -input bool xUSPY5XOBDLHEnableSignaller = true; // Enable Signaller -input bool xUSPY5XOBDLHAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XOBDLHAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XOBDLH Signaller"; +input bool xUSCHF5XOBDLHEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XOBDLHAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XOBDLHAllowShortSignals = true; // Enable Short Signals // // XCHMACC ... -input group "XUSPY5 XCHMACC Signaller"; -input bool xUSPY5XCHMACCEnableSignaller = true; // Enable Signaller -input bool xUSPY5XCHMACCAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XCHMACCAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XCHMACC Signaller"; +input bool xUSCHF5XCHMACCEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMACCAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMACCAllowShortSignals = true; // Enable Short Signals // // XCHMAMX ... -input group "XUSPY5 XCHMAMX Signaller"; -input bool xUSPY5XCHMAMXEnableSignaller = true; // Enable Signaller -input bool xUSPY5XCHMAMXAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XCHMAMXAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XCHMAMX Signaller"; +input bool xUSCHF5XCHMAMXEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMAMXAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMAMXAllowShortSignals = true; // Enable Short Signals // // XCHMAMN ... -input group "XUSPY5 XCHMAMN Signaller"; -input bool xUSPY5XCHMAMNEnableSignaller = true; // Enable Signaller -input bool xUSPY5XCHMAMNAllowLongSignals = true; // Enable Long Signals -input bool xUSPY5XCHMAMNAllowShortSignals = true; // Enable Short Signals +input group "XUSCHF5 XCHMAMN Signaller"; +input bool xUSCHF5XCHMAMNEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMAMNAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMAMNAllowShortSignals = true; // Enable Short Signals // // Check in Test Mode or not ... -bool xUSPY5IsTestMode = false; +bool xUSCHF5IsTestMode = false; // // Detect max Input Length of Indicators ... -int xUSPY5MaxLengthOfInputs = 0; +int xUSCHF5MaxLengthOfInputs = 0; // // Detect Calculated Bars ... -int xUSPY5CalculatedBars = 0; +int xUSCHF5CalculatedBars = 0; // // Check prevent Double Signalling on Same Candle ... -bool xUSPY5WaitUntilNextCandle = false; +bool xUSCHF5WaitUntilNextCandle = false; // // Signaller Variables ... // // XTD ... -bool xUSPY5MXTDEnableSignaller = xUSPY5XTDEnableSignaller; -bool xUSPY5MXTDAllowLongSignals = xUSPY5XTDAllowLongSignals; -bool xUSPY5MXTDAllowShortSignals = xUSPY5XTDAllowShortSignals; +bool xUSCHF5MXTDEnableSignaller = xUSCHF5XTDEnableSignaller; +bool xUSCHF5MXTDAllowLongSignals = xUSCHF5XTDAllowLongSignals; +bool xUSCHF5MXTDAllowShortSignals = xUSCHF5XTDAllowShortSignals; // // XTAM ... -bool xUSPY5MXTAMEnableSignaller = xUSPY5XTAMEnableSignaller; -bool xUSPY5MXTAMAllowLongSignals = xUSPY5XTAMAllowLongSignals; -bool xUSPY5MXTAMAllowShortSignals = xUSPY5XTAMAllowShortSignals; +bool xUSCHF5MXTAMEnableSignaller = xUSCHF5XTAMEnableSignaller; +bool xUSCHF5MXTAMAllowLongSignals = xUSCHF5XTAMAllowLongSignals; +bool xUSCHF5MXTAMAllowShortSignals = xUSCHF5XTAMAllowShortSignals; // // XSI ... -bool xUSPY5MXSIEnableSignaller = xUSPY5XSIEnableSignaller; -bool xUSPY5MXSIAllowLongSignals = xUSPY5XSIAllowLongSignals; -bool xUSPY5MXSIAllowShortSignals = xUSPY5XSIAllowShortSignals; +bool xUSCHF5MXSIEnableSignaller = xUSCHF5XSIEnableSignaller; +bool xUSCHF5MXSIAllowLongSignals = xUSCHF5XSIAllowLongSignals; +bool xUSCHF5MXSIAllowShortSignals = xUSCHF5XSIAllowShortSignals; // // XTSFI ... -bool xUSPY5MXTSFIEnableSignaller = xUSPY5XTSFIEnableSignaller; -bool xUSPY5MXTSFIAllowLongSignals = xUSPY5XTSFIAllowLongSignals; -bool xUSPY5MXTSFIAllowShortSignals = xUSPY5XTSFIAllowShortSignals; +bool xUSCHF5MXTSFIEnableSignaller = xUSCHF5XTSFIEnableSignaller; +bool xUSCHF5MXTSFIAllowLongSignals = xUSCHF5XTSFIAllowLongSignals; +bool xUSCHF5MXTSFIAllowShortSignals = xUSCHF5XTSFIAllowShortSignals; // // XOBDLH ... -bool xUSPY5MXOBDLHEnableSignaller = xUSPY5XOBDLHEnableSignaller; -bool xUSPY5MXOBDLHAllowLongSignals = xUSPY5XOBDLHAllowLongSignals; -bool xUSPY5MXOBDLHAllowShortSignals = xUSPY5XOBDLHAllowShortSignals; +bool xUSCHF5MXOBDLHEnableSignaller = xUSCHF5XOBDLHEnableSignaller; +bool xUSCHF5MXOBDLHAllowLongSignals = xUSCHF5XOBDLHAllowLongSignals; +bool xUSCHF5MXOBDLHAllowShortSignals = xUSCHF5XOBDLHAllowShortSignals; // // XCHMACC ... -bool xUSPY5MXCHMACCEnableSignaller = xUSPY5XCHMACCEnableSignaller; -bool xUSPY5MXCHMACCAllowLongSignals = xUSPY5XCHMACCAllowLongSignals; -bool xUSPY5MXCHMACCAllowShortSignals = xUSPY5XCHMACCAllowShortSignals; +bool xUSCHF5MXCHMACCEnableSignaller = xUSCHF5XCHMACCEnableSignaller; +bool xUSCHF5MXCHMACCAllowLongSignals = xUSCHF5XCHMACCAllowLongSignals; +bool xUSCHF5MXCHMACCAllowShortSignals = xUSCHF5XCHMACCAllowShortSignals; // // XCHMAMX ... -bool xUSPY5MXCHMAMXEnableSignaller = xUSPY5XCHMAMXEnableSignaller; -bool xUSPY5MXCHMAMXAllowLongSignals = xUSPY5XCHMAMXAllowLongSignals; -bool xUSPY5MXCHMAMXAllowShortSignals = xUSPY5XCHMAMXAllowShortSignals; +bool xUSCHF5MXCHMAMXEnableSignaller = xUSCHF5XCHMAMXEnableSignaller; +bool xUSCHF5MXCHMAMXAllowLongSignals = xUSCHF5XCHMAMXAllowLongSignals; +bool xUSCHF5MXCHMAMXAllowShortSignals = xUSCHF5XCHMAMXAllowShortSignals; // // XCHMAMN ... -bool xUSPY5MXCHMAMNEnableSignaller = xUSPY5XCHMAMNEnableSignaller; -bool xUSPY5MXCHMAMNAllowLongSignals = xUSPY5XCHMAMNAllowLongSignals; -bool xUSPY5MXCHMAMNAllowShortSignals = xUSPY5XCHMAMNAllowShortSignals; +bool xUSCHF5MXCHMAMNEnableSignaller = xUSCHF5XCHMAMNEnableSignaller; +bool xUSCHF5MXCHMAMNAllowLongSignals = xUSCHF5XCHMAMNAllowLongSignals; +bool xUSCHF5MXCHMAMNAllowShortSignals = xUSCHF5XCHMAMNAllowShortSignals; // -XCPriver *xUSPY5Provider; +XCPriver *xUSCHF5Provider; // // Validate Indicators Inputs ... -bool XUSPY5ValidateIndicatorsInputs() +bool XUSCHF5ValidateIndicatorsInputs() { // bool result = false; @@ -242,7 +242,7 @@ bool XUSPY5ValidateIndicatorsInputs() // // Make an Instance Of XCPriver Class for Use ... - xUSPY5Provider = new XCPriver( + xUSCHF5Provider = new XCPriver( // // Commons ... _Symbol, @@ -251,44 +251,44 @@ bool XUSPY5ValidateIndicatorsInputs() // Signallers ... // // XTD ... - xUSPY5MXTDEnableSignaller, - xUSPY5MXTDAllowLongSignals, - xUSPY5MXTDAllowShortSignals, + xUSCHF5MXTDEnableSignaller, + xUSCHF5MXTDAllowLongSignals, + xUSCHF5MXTDAllowShortSignals, // // XTAM ... - xUSPY5MXTAMEnableSignaller, - xUSPY5MXTAMAllowLongSignals, - xUSPY5MXTAMAllowShortSignals, + xUSCHF5MXTAMEnableSignaller, + xUSCHF5MXTAMAllowLongSignals, + xUSCHF5MXTAMAllowShortSignals, // // XSI ... - xUSPY5MXSIEnableSignaller, - xUSPY5MXSIAllowLongSignals, - xUSPY5MXSIAllowShortSignals, + xUSCHF5MXSIEnableSignaller, + xUSCHF5MXSIAllowLongSignals, + xUSCHF5MXSIAllowShortSignals, // // XTSFI ... - xUSPY5MXTSFIEnableSignaller, - xUSPY5MXTSFIAllowLongSignals, - xUSPY5MXTSFIAllowShortSignals, + xUSCHF5MXTSFIEnableSignaller, + xUSCHF5MXTSFIAllowLongSignals, + xUSCHF5MXTSFIAllowShortSignals, // // XOBDLH ... - xUSPY5MXOBDLHEnableSignaller, - xUSPY5MXOBDLHAllowLongSignals, - xUSPY5MXOBDLHAllowShortSignals, + xUSCHF5MXOBDLHEnableSignaller, + xUSCHF5MXOBDLHAllowLongSignals, + xUSCHF5MXOBDLHAllowShortSignals, // // XCHMACC ... - xUSPY5MXCHMACCEnableSignaller, - xUSPY5MXCHMACCAllowLongSignals, - xUSPY5MXCHMACCAllowShortSignals, + xUSCHF5MXCHMACCEnableSignaller, + xUSCHF5MXCHMACCAllowLongSignals, + xUSCHF5MXCHMACCAllowShortSignals, // // XCHMAMX ... - xUSPY5MXCHMAMXEnableSignaller, - xUSPY5MXCHMAMXAllowLongSignals, - xUSPY5MXCHMAMXAllowShortSignals, + xUSCHF5MXCHMAMXEnableSignaller, + xUSCHF5MXCHMAMXAllowLongSignals, + xUSCHF5MXCHMAMXAllowShortSignals, // // XCHMAMN ... - xUSPY5MXCHMAMNEnableSignaller, - xUSPY5MXCHMAMNAllowLongSignals, - xUSPY5MXCHMAMNAllowShortSignals + xUSCHF5MXCHMAMNEnableSignaller, + xUSCHF5MXCHMAMNAllowLongSignals, + xUSCHF5MXCHMAMNAllowShortSignals // ); @@ -301,14 +301,14 @@ bool XUSPY5ValidateIndicatorsInputs() // // Init Indicators ... -bool XUSPY5InitIndicators() +bool XUSCHF5InitIndicators() { // bool result = false; // // Make it Enable when we need to Log Market Conditions ... - xUSPY5IsTestMode = IsRunningOnTestMode(); + xUSCHF5IsTestMode = IsRunningOnTestMode(); // // Check and Calculate Max Length in Inputs ... @@ -316,88 +316,88 @@ bool XUSPY5InitIndicators() // // XTM ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xTMMaPeriod, - xUSPY5NumberOfItemsPerTick); + xUSCHF5NumberOfItemsPerTick); // // XAMA ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xAMALength, - xUSPY5NumberOfItemsPerTick); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5NumberOfItemsPerTick); + xUSCHF5MaxLengthOfInputs = MathMax( xAMAFastEMA, - xUSPY5NumberOfItemsPerTick); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5NumberOfItemsPerTick); + xUSCHF5MaxLengthOfInputs = MathMax( xAMASlowEMA, - xUSPY5NumberOfItemsPerTick); + xUSCHF5NumberOfItemsPerTick); // // XLH ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xLHLength, - xUSPY5NumberOfItemsPerTick); + xUSCHF5NumberOfItemsPerTick); // // XTD ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xTDLength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // XFI ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xFILength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // XRSI ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xRSILength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // XOBD ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xOBDLength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // XCHLH ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xCHLHLcLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHLHMcLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHLHScLength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // XCHMA ... - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs = MathMax( xCHMAScFastLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHMAScSlowLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHMAMcFastLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHMAMcSlowLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHMALcFastLength, - xUSPY5MaxLengthOfInputs); - xUSPY5MaxLengthOfInputs = MathMax( + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( xCHMALcSlowLength, - xUSPY5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs); // // Validate Indicators Inputs before Initialization ... - result = XUSPY5ValidateIndicatorsInputs(); + result = XUSCHF5ValidateIndicatorsInputs(); if (!result) { return result; @@ -409,58 +409,58 @@ bool XUSPY5InitIndicators() // // XTD ... bool isXTDEnable = - xUSPY5XTDEnableSignaller && - (xUSPY5XTDAllowLongSignals || - xUSPY5XTDAllowShortSignals); + xUSCHF5XTDEnableSignaller && + (xUSCHF5XTDAllowLongSignals || + xUSCHF5XTDAllowShortSignals); // // XTAM ... bool isXTAMEnable = - xUSPY5XTAMEnableSignaller && - (xUSPY5XTAMAllowLongSignals || - xUSPY5XTAMAllowShortSignals); + xUSCHF5XTAMEnableSignaller && + (xUSCHF5XTAMAllowLongSignals || + xUSCHF5XTAMAllowShortSignals); // // XSI ... bool isXSIEnable = - xUSPY5XSIEnableSignaller && - (xUSPY5XSIAllowLongSignals || - xUSPY5XSIAllowShortSignals); + xUSCHF5XSIEnableSignaller && + (xUSCHF5XSIAllowLongSignals || + xUSCHF5XSIAllowShortSignals); // // XTSFI ... bool isXTSFIEnable = - xUSPY5XTSFIEnableSignaller && - (xUSPY5XTSFIAllowLongSignals || - xUSPY5XTSFIAllowShortSignals); + xUSCHF5XTSFIEnableSignaller && + (xUSCHF5XTSFIAllowLongSignals || + xUSCHF5XTSFIAllowShortSignals); // // XOBDLH ... bool isXOBDLHEnable = - xUSPY5XOBDLHEnableSignaller && - (xUSPY5XOBDLHAllowLongSignals || - xUSPY5XOBDLHAllowShortSignals); + xUSCHF5XOBDLHEnableSignaller && + (xUSCHF5XOBDLHAllowLongSignals || + xUSCHF5XOBDLHAllowShortSignals); // // XCHMACC ... bool isXCHMACCEnable = - xUSPY5XCHMACCEnableSignaller && - (xUSPY5XCHMACCAllowLongSignals || - xUSPY5XCHMACCAllowShortSignals); + xUSCHF5XCHMACCEnableSignaller && + (xUSCHF5XCHMACCAllowLongSignals || + xUSCHF5XCHMACCAllowShortSignals); // // XCHMAMX ... bool isXCHMAMXEnable = - xUSPY5XCHMAMXEnableSignaller && - (xUSPY5XCHMAMXAllowLongSignals || - xUSPY5XCHMAMXAllowShortSignals); + xUSCHF5XCHMAMXEnableSignaller && + (xUSCHF5XCHMAMXAllowLongSignals || + xUSCHF5XCHMAMXAllowShortSignals); // // XCHMAMN ... bool isXCHMAMNEnable = - xUSPY5XCHMAMNEnableSignaller && - (xUSPY5XCHMAMNAllowLongSignals || - xUSPY5XCHMAMNAllowShortSignals); + xUSCHF5XCHMAMNEnableSignaller && + (xUSCHF5XCHMAMNAllowLongSignals || + xUSCHF5XCHMAMNAllowShortSignals); // bool hasSignaller = @@ -479,7 +479,7 @@ bool XUSPY5InitIndicators() if (!result) { // - LogMessage("XUSPY5 doesn't enable any Signaller ..."); + LogMessage("XUSCHF5 doesn't enable any Signaller ..."); // return result; @@ -578,7 +578,7 @@ bool XUSPY5InitIndicators() // // Release Indicators ... -void XUSPY5ReleaseIndicators() +void XUSCHF5ReleaseIndicators() { // // Release Handlers ... @@ -596,27 +596,27 @@ void XUSPY5ReleaseIndicators() // // Handle Reading Buffers ... -void XUSPY5HandleReadingBuffers() +void XUSCHF5HandleReadingBuffers() { // // Reading Calculated Bars for a Simple Handler ... - xUSPY5CalculatedBars = BarsCalculated(xTMHandler); + xUSCHF5CalculatedBars = BarsCalculated(xTMHandler); // // Read Indicators Buffers ... - XTMReadBuffers(xUSPY5NumberOfItemsPerTick); - XAMAReadBuffers(xUSPY5NumberOfItemsPerTick); - XLHReadBuffers(xUSPY5NumberOfItemsPerTick); - XTDReadBuffers(xUSPY5NumberOfItemsPerTick); - XFIReadBuffers(xUSPY5NumberOfItemsPerTick); - XTSReadBuffers(xUSPY5NumberOfItemsPerTick); - XRSIReadBuffers(xUSPY5NumberOfItemsPerTick); - XOBDReadBuffers(xUSPY5NumberOfItemsPerTick); - XCHMAReadBuffers(xUSPY5NumberOfItemsPerTick); - XCHLHReadBuffers(xUSPY5NumberOfItemsPerTick); + XTMReadBuffers(xUSCHF5NumberOfItemsPerTick); + XAMAReadBuffers(xUSCHF5NumberOfItemsPerTick); + XLHReadBuffers(xUSCHF5NumberOfItemsPerTick); + XTDReadBuffers(xUSCHF5NumberOfItemsPerTick); + XFIReadBuffers(xUSCHF5NumberOfItemsPerTick); + XTSReadBuffers(xUSCHF5NumberOfItemsPerTick); + XRSIReadBuffers(xUSCHF5NumberOfItemsPerTick); + XOBDReadBuffers(xUSCHF5NumberOfItemsPerTick); + XCHMAReadBuffers(xUSCHF5NumberOfItemsPerTick); + XCHLHReadBuffers(xUSCHF5NumberOfItemsPerTick); // - xUSPY5Provider.ReadConditions(); + xUSCHF5Provider.ReadConditions(); } // @@ -629,7 +629,7 @@ void XUSPY5HandleReadingBuffers() // Can Open Long Trade ... // this is a Function will Check all market Conditions and get all // Strategy requirement Verifications for Long Signals ... -bool XUSPY5CanOpenLongTrade( +bool XUSCHF5CanOpenLongTrade( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -644,7 +644,7 @@ bool XUSPY5CanOpenLongTrade( 0); // - bool hasSignal = XUSPY5HasLongSignal(info); + bool hasSignal = XUSCHF5HasLongSignal(info); // result = @@ -656,7 +656,7 @@ bool XUSPY5CanOpenLongTrade( // if (result) { - xUSPY5Provider.ClearConditions(); + xUSCHF5Provider.ClearConditions(); } // @@ -667,7 +667,7 @@ bool XUSPY5CanOpenLongTrade( // Can Close Long Trade ... // this is a Function will Check all market Conditions and get all // Strategy requirement Verifications for Long Signals ... -bool XUSPY5CanCloseLongTrade() +bool XUSCHF5CanCloseLongTrade() { // bool result = false; @@ -680,7 +680,7 @@ bool XUSPY5CanCloseLongTrade() // Can Open Short Trade ... // this is a Function will Check all market Conditions and get all // Strategy requirement Verifications for Short Signals ... -bool XUSPY5CanOpenShortTrade( +bool XUSCHF5CanOpenShortTrade( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -695,7 +695,7 @@ bool XUSPY5CanOpenShortTrade( 0); // - bool hasSignal = XUSPY5HasShortSignal(info); + bool hasSignal = XUSCHF5HasShortSignal(info); // result = @@ -707,7 +707,7 @@ bool XUSPY5CanOpenShortTrade( // if (result) { - xUSPY5Provider.ClearConditions(); + xUSCHF5Provider.ClearConditions(); } // @@ -718,7 +718,7 @@ bool XUSPY5CanOpenShortTrade( // Can Close Short Trade ... // this is a Function will Check all market Conditions and get all // Strategy requirement Verifications for Short Signals ... -bool XUSPY5CanCloseShortTrade() +bool XUSCHF5CanCloseShortTrade() { // bool result = false; @@ -741,7 +741,7 @@ bool XUSPY5CanCloseShortTrade() // // Check Market Conditions by Combination of Power of All tools for LONGs ... -bool XUSPY5HasLongSignal( +bool XUSCHF5HasLongSignal( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -750,7 +750,7 @@ bool XUSPY5HasLongSignal( // // XTD ... - bool isXTDHasSignal = XUSPY5XTDHasLongSignal(); + bool isXTDHasSignal = XUSCHF5XTDHasLongSignal(); if (isXTDHasSignal) { // @@ -761,7 +761,7 @@ bool XUSPY5HasLongSignal( // // XTAM ... - bool isXTAMHasSignal = XUSPY5XTAMHasLongSignal(); + bool isXTAMHasSignal = XUSCHF5XTAMHasLongSignal(); if (isXTAMHasSignal) { // @@ -772,7 +772,7 @@ bool XUSPY5HasLongSignal( // // XSI ... - bool isXSIHasSignal = XUSPY5XSIHasLongSignal(); + bool isXSIHasSignal = XUSCHF5XSIHasLongSignal(); if (isXSIHasSignal) { // @@ -783,7 +783,7 @@ bool XUSPY5HasLongSignal( // // XTSFI ... - bool isXTSFIHasSignal = XUSPY5XTSFIHasLongSignal(); + bool isXTSFIHasSignal = XUSCHF5XTSFIHasLongSignal(); if (isXTSFIHasSignal) { // @@ -794,7 +794,7 @@ bool XUSPY5HasLongSignal( // // XOBD XLH ... - bool isXOBDLHHasSignal = XUSPY5XOBDLHHasLongSignal(); + bool isXOBDLHHasSignal = XUSCHF5XOBDLHHasLongSignal(); if (isXOBDLHHasSignal) { // @@ -805,7 +805,7 @@ bool XUSPY5HasLongSignal( // // XCHMA Cycles Cross ... - bool isXCHMACCHasSignal = XUSPY5XCHMACCHasLongSignal(); + bool isXCHMACCHasSignal = XUSCHF5XCHMACCHasLongSignal(); if (isXCHMACCHasSignal) { // @@ -816,7 +816,7 @@ bool XUSPY5HasLongSignal( // // XCHMA Cycles Min ... - bool isXCHMAMNHasSignal = XUSPY5XCHMAMNHasLongSignal(); + bool isXCHMAMNHasSignal = XUSCHF5XCHMAMNHasLongSignal(); if (isXCHMAMNHasSignal) { // @@ -827,7 +827,7 @@ bool XUSPY5HasLongSignal( // // XCHMA Cycles Max - bool isXCHMAMXHasSignal = XUSPY5XCHMAMXHasLongSignal(); + bool isXCHMAMXHasSignal = XUSCHF5XCHMAMXHasLongSignal(); if (isXCHMAMXHasSignal) { // @@ -876,11 +876,11 @@ bool XUSPY5HasLongSignal( { // // Only Log Signals Time Market Conditions if is in Testing Mode ... - if (xUSPY5IsTestMode || xUSPY5EnableSignalAlerts) + if (xUSCHF5IsTestMode || xUSCHF5EnableSignalAlerts) { // - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); - string message = xUSPY5Provider.GenerateConditionsString(mConditions); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + string message = xUSCHF5Provider.GenerateConditionsString(mConditions); // LogMessage( @@ -897,7 +897,7 @@ bool XUSPY5HasLongSignal( // // Check Market Conditions by Combination of Power of All tools for SHORTs ... -bool XUSPY5HasShortSignal( +bool XUSCHF5HasShortSignal( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -906,7 +906,7 @@ bool XUSPY5HasShortSignal( // // XTD ... - bool isXTDHasSignal = XUSPY5XTDHasShortSignal(); + bool isXTDHasSignal = XUSCHF5XTDHasShortSignal(); if (isXTDHasSignal) { // @@ -917,7 +917,7 @@ bool XUSPY5HasShortSignal( // // XTAM ... - bool isXTAMHasSignal = XUSPY5XTAMHasShortSignal(); + bool isXTAMHasSignal = XUSCHF5XTAMHasShortSignal(); if (isXTAMHasSignal) { // @@ -928,7 +928,7 @@ bool XUSPY5HasShortSignal( // // XSI ... - bool isXSIHasSignal = XUSPY5XSIHasShortSignal(); + bool isXSIHasSignal = XUSCHF5XSIHasShortSignal(); if (isXSIHasSignal) { // @@ -939,7 +939,7 @@ bool XUSPY5HasShortSignal( // // XTSFI ... - bool isXTSFIHasSignal = XUSPY5XTSFIHasShortSignal(); + bool isXTSFIHasSignal = XUSCHF5XTSFIHasShortSignal(); if (isXTSFIHasSignal) { // @@ -950,7 +950,7 @@ bool XUSPY5HasShortSignal( // // XOBD XLH ... - bool isXOBDLHHasSignal = XUSPY5XOBDLHHasShortSignal(); + bool isXOBDLHHasSignal = XUSCHF5XOBDLHHasShortSignal(); if (isXOBDLHHasSignal) { // @@ -961,7 +961,7 @@ bool XUSPY5HasShortSignal( // // XCHMA Cycles Cross ... - bool isXCHMACCHasSignal = XUSPY5XCHMACCHasShortSignal(); + bool isXCHMACCHasSignal = XUSCHF5XCHMACCHasShortSignal(); if (isXCHMACCHasSignal) { // @@ -972,7 +972,7 @@ bool XUSPY5HasShortSignal( // // XCHMA Cycles Min ... - bool isXCHMAMNHasSignal = XUSPY5XCHMAMNHasShortSignal(); + bool isXCHMAMNHasSignal = XUSCHF5XCHMAMNHasShortSignal(); if (isXCHMAMNHasSignal) { // @@ -983,7 +983,7 @@ bool XUSPY5HasShortSignal( // // XCHMA Cycles Max - bool isXCHMAMXHasSignal = XUSPY5XCHMAMXHasShortSignal(); + bool isXCHMAMXHasSignal = XUSCHF5XCHMAMXHasShortSignal(); if (isXCHMAMXHasSignal) { // @@ -1032,11 +1032,11 @@ bool XUSPY5HasShortSignal( { // // Only Log Signals Time Market Conditions if is in Testing Mode ... - if (xUSPY5IsTestMode || xUSPY5EnableSignalAlerts) + if (xUSCHF5IsTestMode || xUSCHF5EnableSignalAlerts) { // - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); - string message = xUSPY5Provider.GenerateConditionsString(mConditions); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + string message = xUSCHF5Provider.GenerateConditionsString(mConditions); // LogMessage( @@ -1063,438 +1063,438 @@ bool XUSPY5HasShortSignal( // // Disbale All Signallers Longs ... -void XUSPY5DisableLongSignallers() +void XUSCHF5DisableLongSignallers() { // // XTD ... - if (xUSPY5MXTDEnableSignaller) + if (xUSCHF5MXTDEnableSignaller) { // - xUSPY5Provider.DisbaleXTDLongs(); - xUSPY5MXTDAllowLongSignals = false; + xUSCHF5Provider.DisbaleXTDLongs(); + xUSCHF5MXTDAllowLongSignals = false; } // // XTAM ... - if (xUSPY5MXTAMEnableSignaller) + if (xUSCHF5MXTAMEnableSignaller) { // - xUSPY5Provider.DisbaleXTAMLongs(); - xUSPY5MXTAMAllowLongSignals = false; + xUSCHF5Provider.DisbaleXTAMLongs(); + xUSCHF5MXTAMAllowLongSignals = false; } // // XSI ... - if (xUSPY5MXSIEnableSignaller) + if (xUSCHF5MXSIEnableSignaller) { // - xUSPY5Provider.DisbaleXSILongs(); - xUSPY5MXSIAllowLongSignals = false; + xUSCHF5Provider.DisbaleXSILongs(); + xUSCHF5MXSIAllowLongSignals = false; } // // XTSFI ... - if (xUSPY5MXTSFIEnableSignaller) + if (xUSCHF5MXTSFIEnableSignaller) { // - xUSPY5Provider.DisbaleXTSFILongs(); - xUSPY5MXTSFIAllowLongSignals = false; + xUSCHF5Provider.DisbaleXTSFILongs(); + xUSCHF5MXTSFIAllowLongSignals = false; } // // XOBDLH ... - if (xUSPY5MXOBDLHEnableSignaller) + if (xUSCHF5MXOBDLHEnableSignaller) { // - xUSPY5Provider.DisbaleXOBDLHLongs(); - xUSPY5MXOBDLHAllowLongSignals = false; + xUSCHF5Provider.DisbaleXOBDLHLongs(); + xUSCHF5MXOBDLHAllowLongSignals = false; } // // XCHMACC ... - if (xUSPY5MXCHMACCEnableSignaller) + if (xUSCHF5MXCHMACCEnableSignaller) { // - xUSPY5Provider.DisbaleXCHMACCLongs(); - xUSPY5MXCHMACCAllowLongSignals = false; + xUSCHF5Provider.DisbaleXCHMACCLongs(); + xUSCHF5MXCHMACCAllowLongSignals = false; } // // XCHMAMX ... - if (xUSPY5MXCHMAMXEnableSignaller) + if (xUSCHF5MXCHMAMXEnableSignaller) { // - xUSPY5Provider.DisbaleXCHMAMXLongs(); - xUSPY5MXCHMAMXAllowLongSignals = false; + xUSCHF5Provider.DisbaleXCHMAMXLongs(); + xUSCHF5MXCHMAMXAllowLongSignals = false; } // // XCHMAMN ... - if (xUSPY5MXCHMAMNEnableSignaller) + if (xUSCHF5MXCHMAMNEnableSignaller) { // - xUSPY5Provider.DisbaleXCHMAMNLongs(); - xUSPY5MXCHMAMNAllowLongSignals = false; + xUSCHF5Provider.DisbaleXCHMAMNLongs(); + xUSCHF5MXCHMAMNAllowLongSignals = false; } } // // Enable All Signallers Longs ... // Only if they are Configured as Enable at Settings ... -void XUSPY5EnableLongSignallers() +void XUSCHF5EnableLongSignallers() { // // XTD ... - if (xUSPY5MXTDEnableSignaller) + if (xUSCHF5MXTDEnableSignaller) { // - xUSPY5MXTDAllowLongSignals = - xUSPY5XTDAllowLongSignals + xUSCHF5MXTDAllowLongSignals = + xUSCHF5XTDAllowLongSignals ? true - : xUSPY5MXTDAllowLongSignals; + : xUSCHF5MXTDAllowLongSignals; // - if (xUSPY5MXTDAllowLongSignals) + if (xUSCHF5MXTDAllowLongSignals) { - xUSPY5Provider.EnableXTDLongs(); + xUSCHF5Provider.EnableXTDLongs(); } } // // XTAM ... - if (xUSPY5MXTAMEnableSignaller) + if (xUSCHF5MXTAMEnableSignaller) { // - xUSPY5MXTAMAllowLongSignals = - xUSPY5XTAMAllowLongSignals + xUSCHF5MXTAMAllowLongSignals = + xUSCHF5XTAMAllowLongSignals ? true - : xUSPY5MXTAMAllowLongSignals; + : xUSCHF5MXTAMAllowLongSignals; // - if (xUSPY5MXTAMAllowLongSignals) + if (xUSCHF5MXTAMAllowLongSignals) { - xUSPY5Provider.EnableXTAMLongs(); + xUSCHF5Provider.EnableXTAMLongs(); } } // // XSI ... - if (xUSPY5MXSIEnableSignaller) + if (xUSCHF5MXSIEnableSignaller) { // - xUSPY5MXSIAllowLongSignals = - xUSPY5XSIAllowLongSignals + xUSCHF5MXSIAllowLongSignals = + xUSCHF5XSIAllowLongSignals ? true - : xUSPY5MXSIAllowLongSignals; + : xUSCHF5MXSIAllowLongSignals; // - if (xUSPY5MXSIAllowLongSignals) + if (xUSCHF5MXSIAllowLongSignals) { - xUSPY5Provider.EnableXSILongs(); + xUSCHF5Provider.EnableXSILongs(); } } // // XTSFI ... - if (xUSPY5MXTSFIEnableSignaller) + if (xUSCHF5MXTSFIEnableSignaller) { // - xUSPY5MXTSFIAllowLongSignals = - xUSPY5XTSFIAllowLongSignals + xUSCHF5MXTSFIAllowLongSignals = + xUSCHF5XTSFIAllowLongSignals ? true - : xUSPY5MXTSFIAllowLongSignals; + : xUSCHF5MXTSFIAllowLongSignals; // - if (xUSPY5MXTSFIAllowLongSignals) + if (xUSCHF5MXTSFIAllowLongSignals) { - xUSPY5Provider.EnableXTSFILongs(); + xUSCHF5Provider.EnableXTSFILongs(); } } // // XOBDLH ... - if (xUSPY5MXOBDLHEnableSignaller) + if (xUSCHF5MXOBDLHEnableSignaller) { // - xUSPY5MXOBDLHAllowLongSignals = - xUSPY5XOBDLHAllowLongSignals + xUSCHF5MXOBDLHAllowLongSignals = + xUSCHF5XOBDLHAllowLongSignals ? true - : xUSPY5MXOBDLHAllowLongSignals; + : xUSCHF5MXOBDLHAllowLongSignals; // - if (xUSPY5MXOBDLHAllowLongSignals) + if (xUSCHF5MXOBDLHAllowLongSignals) { - xUSPY5Provider.EnableXOBDLHLongs(); + xUSCHF5Provider.EnableXOBDLHLongs(); } } // // XCHMACC ... - if (xUSPY5MXCHMACCEnableSignaller) + if (xUSCHF5MXCHMACCEnableSignaller) { // - xUSPY5MXCHMACCAllowLongSignals = - xUSPY5XCHMACCAllowLongSignals + xUSCHF5MXCHMACCAllowLongSignals = + xUSCHF5XCHMACCAllowLongSignals ? true - : xUSPY5MXCHMACCAllowLongSignals; + : xUSCHF5MXCHMACCAllowLongSignals; // - if (xUSPY5MXCHMACCAllowLongSignals) + if (xUSCHF5MXCHMACCAllowLongSignals) { - xUSPY5Provider.EnableXCHMACCLongs(); + xUSCHF5Provider.EnableXCHMACCLongs(); } } // // XCHMAMX ... - if (xUSPY5MXCHMAMXEnableSignaller) + if (xUSCHF5MXCHMAMXEnableSignaller) { // - xUSPY5MXCHMAMXAllowLongSignals = - xUSPY5XCHMAMXAllowLongSignals + xUSCHF5MXCHMAMXAllowLongSignals = + xUSCHF5XCHMAMXAllowLongSignals ? true - : xUSPY5MXCHMAMXAllowLongSignals; + : xUSCHF5MXCHMAMXAllowLongSignals; // - if (xUSPY5MXCHMAMXAllowLongSignals) + if (xUSCHF5MXCHMAMXAllowLongSignals) { - xUSPY5Provider.EnableXCHMAMXLongs(); + xUSCHF5Provider.EnableXCHMAMXLongs(); } } // // XCHMAMN ... - if (xUSPY5MXCHMAMNEnableSignaller) + if (xUSCHF5MXCHMAMNEnableSignaller) { // - xUSPY5MXCHMAMNAllowLongSignals = - xUSPY5XCHMAMNAllowLongSignals + xUSCHF5MXCHMAMNAllowLongSignals = + xUSCHF5XCHMAMNAllowLongSignals ? true - : xUSPY5MXCHMAMNAllowLongSignals; + : xUSCHF5MXCHMAMNAllowLongSignals; // - if (xUSPY5MXCHMAMNAllowLongSignals) + if (xUSCHF5MXCHMAMNAllowLongSignals) { - xUSPY5Provider.EnableXCHMAMNLongs(); + xUSCHF5Provider.EnableXCHMAMNLongs(); } } } // // Disable All Signallers Shorts ... -void XUSPY5DisableShortSignallers() +void XUSCHF5DisableShortSignallers() { // // XTD ... - if (xUSPY5MXTDEnableSignaller) + if (xUSCHF5MXTDEnableSignaller) { // - xUSPY5Provider.DisableXTDShorts(); - xUSPY5MXTDAllowShortSignals = false; + xUSCHF5Provider.DisableXTDShorts(); + xUSCHF5MXTDAllowShortSignals = false; } // // XTAM ... - if (xUSPY5MXTAMEnableSignaller) + if (xUSCHF5MXTAMEnableSignaller) { // - xUSPY5Provider.DisableXTAMShorts(); - xUSPY5MXTAMAllowShortSignals = false; + xUSCHF5Provider.DisableXTAMShorts(); + xUSCHF5MXTAMAllowShortSignals = false; } // // XSI ... - if (xUSPY5MXSIEnableSignaller) + if (xUSCHF5MXSIEnableSignaller) { // - xUSPY5Provider.DisableXSIShorts(); - xUSPY5MXSIAllowShortSignals = false; + xUSCHF5Provider.DisableXSIShorts(); + xUSCHF5MXSIAllowShortSignals = false; } // // XTSFI ... - if (xUSPY5MXTSFIEnableSignaller) + if (xUSCHF5MXTSFIEnableSignaller) { // - xUSPY5Provider.DisableXTSFIShorts(); - xUSPY5MXTSFIAllowShortSignals = false; + xUSCHF5Provider.DisableXTSFIShorts(); + xUSCHF5MXTSFIAllowShortSignals = false; } // // XOBDLH ... - if (xUSPY5MXOBDLHEnableSignaller) + if (xUSCHF5MXOBDLHEnableSignaller) { // - xUSPY5Provider.DisableXOBDLHShorts(); - xUSPY5MXOBDLHAllowShortSignals = false; + xUSCHF5Provider.DisableXOBDLHShorts(); + xUSCHF5MXOBDLHAllowShortSignals = false; } // // XCHMACC ... - if (xUSPY5MXCHMACCEnableSignaller) + if (xUSCHF5MXCHMACCEnableSignaller) { // - xUSPY5Provider.DisableXCHMACCShorts(); - xUSPY5MXCHMACCAllowShortSignals = false; + xUSCHF5Provider.DisableXCHMACCShorts(); + xUSCHF5MXCHMACCAllowShortSignals = false; } // // XCHMAMX ... - if (xUSPY5MXCHMAMXEnableSignaller) + if (xUSCHF5MXCHMAMXEnableSignaller) { // - xUSPY5Provider.DisableXCHMAMXShorts(); - xUSPY5MXCHMAMXAllowShortSignals = false; + xUSCHF5Provider.DisableXCHMAMXShorts(); + xUSCHF5MXCHMAMXAllowShortSignals = false; } // // XCHMAMN ... - if (xUSPY5MXCHMAMNEnableSignaller) + if (xUSCHF5MXCHMAMNEnableSignaller) { // - xUSPY5Provider.DisableXCHMAMNShorts(); - xUSPY5MXCHMAMNAllowShortSignals = false; + xUSCHF5Provider.DisableXCHMAMNShorts(); + xUSCHF5MXCHMAMNAllowShortSignals = false; } } // // Enable All Signallers Shorts ... // Only if they are Configured as Enable at Settings ... -void XUSPY5EnableShortSignallers() +void XUSCHF5EnableShortSignallers() { // // XTD ... - if (xUSPY5MXTDEnableSignaller) + if (xUSCHF5MXTDEnableSignaller) { // - xUSPY5MXTDAllowShortSignals = - xUSPY5XTDAllowShortSignals + xUSCHF5MXTDAllowShortSignals = + xUSCHF5XTDAllowShortSignals ? true - : xUSPY5MXTDAllowShortSignals; + : xUSCHF5MXTDAllowShortSignals; // - if (xUSPY5MXTDAllowShortSignals) + if (xUSCHF5MXTDAllowShortSignals) { - xUSPY5Provider.EnableXTDShorts(); + xUSCHF5Provider.EnableXTDShorts(); } } // // XTAM ... - if (xUSPY5MXTAMEnableSignaller) + if (xUSCHF5MXTAMEnableSignaller) { // - xUSPY5MXTAMAllowShortSignals = - xUSPY5XTAMAllowShortSignals + xUSCHF5MXTAMAllowShortSignals = + xUSCHF5XTAMAllowShortSignals ? true - : xUSPY5MXTAMAllowShortSignals; + : xUSCHF5MXTAMAllowShortSignals; // - if (xUSPY5MXTAMAllowShortSignals) + if (xUSCHF5MXTAMAllowShortSignals) { - xUSPY5Provider.EnableXTAMShorts(); + xUSCHF5Provider.EnableXTAMShorts(); } } // // XSI ... - if (xUSPY5MXSIEnableSignaller) + if (xUSCHF5MXSIEnableSignaller) { // - xUSPY5MXSIAllowShortSignals = - xUSPY5XSIAllowShortSignals + xUSCHF5MXSIAllowShortSignals = + xUSCHF5XSIAllowShortSignals ? true - : xUSPY5MXSIAllowShortSignals; + : xUSCHF5MXSIAllowShortSignals; // - if (xUSPY5MXSIAllowShortSignals) + if (xUSCHF5MXSIAllowShortSignals) { - xUSPY5Provider.EnableXSIShorts(); + xUSCHF5Provider.EnableXSIShorts(); } } // // XTSFI ... - if (xUSPY5MXTSFIEnableSignaller) + if (xUSCHF5MXTSFIEnableSignaller) { // - xUSPY5MXTSFIAllowShortSignals = - xUSPY5XTSFIAllowShortSignals + xUSCHF5MXTSFIAllowShortSignals = + xUSCHF5XTSFIAllowShortSignals ? true - : xUSPY5MXTSFIAllowShortSignals; + : xUSCHF5MXTSFIAllowShortSignals; // - if (xUSPY5MXTSFIAllowShortSignals) + if (xUSCHF5MXTSFIAllowShortSignals) { - xUSPY5Provider.EnableXTSFIShorts(); + xUSCHF5Provider.EnableXTSFIShorts(); } } // // XOBDLH ... - if (xUSPY5MXOBDLHEnableSignaller) + if (xUSCHF5MXOBDLHEnableSignaller) { // - xUSPY5MXOBDLHAllowShortSignals = - xUSPY5XOBDLHAllowShortSignals + xUSCHF5MXOBDLHAllowShortSignals = + xUSCHF5XOBDLHAllowShortSignals ? true - : xUSPY5MXOBDLHAllowShortSignals; + : xUSCHF5MXOBDLHAllowShortSignals; // - if (xUSPY5MXOBDLHAllowShortSignals) + if (xUSCHF5MXOBDLHAllowShortSignals) { - xUSPY5Provider.EnableXOBDLHShorts(); + xUSCHF5Provider.EnableXOBDLHShorts(); } } // // XCHMACC ... - if (xUSPY5MXCHMACCEnableSignaller) + if (xUSCHF5MXCHMACCEnableSignaller) { // - xUSPY5MXCHMACCAllowShortSignals = - xUSPY5XCHMACCAllowShortSignals + xUSCHF5MXCHMACCAllowShortSignals = + xUSCHF5XCHMACCAllowShortSignals ? true - : xUSPY5MXCHMACCAllowShortSignals; + : xUSCHF5MXCHMACCAllowShortSignals; // - if (xUSPY5MXCHMACCAllowShortSignals) + if (xUSCHF5MXCHMACCAllowShortSignals) { - xUSPY5Provider.EnableXCHMACCShorts(); + xUSCHF5Provider.EnableXCHMACCShorts(); } } // // XCHMAMX ... - if (xUSPY5MXCHMAMXEnableSignaller) + if (xUSCHF5MXCHMAMXEnableSignaller) { // - xUSPY5MXCHMAMXAllowShortSignals = - xUSPY5XCHMAMXAllowShortSignals + xUSCHF5MXCHMAMXAllowShortSignals = + xUSCHF5XCHMAMXAllowShortSignals ? true - : xUSPY5MXCHMAMXAllowShortSignals; + : xUSCHF5MXCHMAMXAllowShortSignals; // - if (xUSPY5MXCHMAMXAllowShortSignals) + if (xUSCHF5MXCHMAMXAllowShortSignals) { - xUSPY5Provider.EnableXCHMAMXShorts(); + xUSCHF5Provider.EnableXCHMAMXShorts(); } } // // XCHMAMN ... - if (xUSPY5MXCHMAMNEnableSignaller) + if (xUSCHF5MXCHMAMNEnableSignaller) { // - xUSPY5MXCHMAMNAllowShortSignals = - xUSPY5XCHMAMNAllowShortSignals + xUSCHF5MXCHMAMNAllowShortSignals = + xUSCHF5XCHMAMNAllowShortSignals ? true - : xUSPY5MXCHMAMNAllowShortSignals; + : xUSCHF5MXCHMAMNAllowShortSignals; // - if (xUSPY5MXCHMAMNAllowShortSignals) + if (xUSCHF5MXCHMAMNAllowShortSignals) { - xUSPY5Provider.EnableXCHMAMNShorts(); + xUSCHF5Provider.EnableXCHMAMNShorts(); } } } @@ -1505,29 +1505,29 @@ void XUSPY5EnableShortSignallers() // // XTD Long Signal Checking ... -bool XUSPY5XTDHasLongSignal() +bool XUSCHF5XTDHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTDEnableSignaller || - !xUSPY5MXTDAllowLongSignals) + if (!xUSCHF5MXTDEnableSignaller || + !xUSCHF5MXTDAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTDHasLongConditions() + xUSCHF5Provider.XTDHasLongConditions() // && // @@ -1995,29 +1995,29 @@ bool XUSPY5XTDHasLongSignal() // // XTD Short Signal Checking ... -bool XUSPY5XTDHasShortSignal() +bool XUSCHF5XTDHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTDEnableSignaller || - !xUSPY5MXTDAllowShortSignals) + if (!xUSCHF5MXTDEnableSignaller || + !xUSCHF5MXTDAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTDHasShortConditions() + xUSCHF5Provider.XTDHasShortConditions() // && // @@ -2303,29 +2303,29 @@ bool XUSPY5XTDHasShortSignal() // // XTAM Long Signal Checking ... -bool XUSPY5XTAMHasLongSignal() +bool XUSCHF5XTAMHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTAMEnableSignaller || - !xUSPY5MXTAMAllowLongSignals) + if (!xUSCHF5MXTAMEnableSignaller || + !xUSCHF5MXTAMAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTAMHasLongConditions() + xUSCHF5Provider.XTAMHasLongConditions() // && // @@ -2611,29 +2611,29 @@ bool XUSPY5XTAMHasLongSignal() // // XTAM Short Signal Checking ... -bool XUSPY5XTAMHasShortSignal() +bool XUSCHF5XTAMHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTAMEnableSignaller || - !xUSPY5MXTAMAllowShortSignals) + if (!xUSCHF5MXTAMEnableSignaller || + !xUSCHF5MXTAMAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTAMHasShortConditions() + xUSCHF5Provider.XTAMHasShortConditions() // && // @@ -2919,29 +2919,29 @@ bool XUSPY5XTAMHasShortSignal() // // XSI Long Signal Checking ... -bool XUSPY5XSIHasLongSignal() +bool XUSCHF5XSIHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXSIEnableSignaller || - !xUSPY5MXSIAllowLongSignals) + if (!xUSCHF5MXSIEnableSignaller || + !xUSCHF5MXSIAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XSIHasLongConditions() + xUSCHF5Provider.XSIHasLongConditions() // && // @@ -3227,29 +3227,29 @@ bool XUSPY5XSIHasLongSignal() // // XSI Short Signal Checking ... -bool XUSPY5XSIHasShortSignal() +bool XUSCHF5XSIHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXSIEnableSignaller || - !xUSPY5MXSIAllowShortSignals) + if (!xUSCHF5MXSIEnableSignaller || + !xUSCHF5MXSIAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XSIHasShortConditions() + xUSCHF5Provider.XSIHasShortConditions() // && // @@ -3535,29 +3535,29 @@ bool XUSPY5XSIHasShortSignal() // // XTSFI Long Signal Checking ... -bool XUSPY5XTSFIHasLongSignal() +bool XUSCHF5XTSFIHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTSFIEnableSignaller || - !xUSPY5MXTSFIAllowLongSignals) + if (!xUSCHF5MXTSFIEnableSignaller || + !xUSCHF5MXTSFIAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTSFIHasLongConditions() + xUSCHF5Provider.XTSFIHasLongConditions() // && // @@ -3843,29 +3843,29 @@ bool XUSPY5XTSFIHasLongSignal() // // XTSFI Short Signal Checking ... -bool XUSPY5XTSFIHasShortSignal() +bool XUSCHF5XTSFIHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXTSFIEnableSignaller || - !xUSPY5MXTSFIAllowShortSignals) + if (!xUSCHF5MXTSFIEnableSignaller || + !xUSCHF5MXTSFIAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XTSFIHasShortConditions() + xUSCHF5Provider.XTSFIHasShortConditions() // && // @@ -4151,29 +4151,29 @@ bool XUSPY5XTSFIHasShortSignal() // // XOBDLH Long Signal Checking ... -bool XUSPY5XOBDLHHasLongSignal() +bool XUSCHF5XOBDLHHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXOBDLHEnableSignaller || - !xUSPY5MXOBDLHAllowLongSignals) + if (!xUSCHF5MXOBDLHEnableSignaller || + !xUSCHF5MXOBDLHAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XOBDLHHasLongConditions() + xUSCHF5Provider.XOBDLHHasLongConditions() // && // @@ -4459,29 +4459,29 @@ bool XUSPY5XOBDLHHasLongSignal() // // XOBDLH Short Signal Checking ... -bool XUSPY5XOBDLHHasShortSignal() +bool XUSCHF5XOBDLHHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXOBDLHEnableSignaller || - !xUSPY5MXOBDLHAllowShortSignals) + if (!xUSCHF5MXOBDLHEnableSignaller || + !xUSCHF5MXOBDLHAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XOBDLHHasShortConditions() + xUSCHF5Provider.XOBDLHHasShortConditions() // && // @@ -4767,29 +4767,29 @@ bool XUSPY5XOBDLHHasShortSignal() // // XCHMACC Long Signal Checking ... -bool XUSPY5XCHMACCHasLongSignal() +bool XUSCHF5XCHMACCHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMACCEnableSignaller || - !xUSPY5MXCHMACCAllowLongSignals) + if (!xUSCHF5MXCHMACCEnableSignaller || + !xUSCHF5MXCHMACCAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMACCHasLongConditions() + xUSCHF5Provider.XCHMACCHasLongConditions() // && // @@ -5075,29 +5075,29 @@ bool XUSPY5XCHMACCHasLongSignal() // // XCHMACC Short Signal Checking ... -bool XUSPY5XCHMACCHasShortSignal() +bool XUSCHF5XCHMACCHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMACCEnableSignaller || - !xUSPY5MXCHMACCAllowShortSignals) + if (!xUSCHF5MXCHMACCEnableSignaller || + !xUSCHF5MXCHMACCAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMACCHasShortConditions() + xUSCHF5Provider.XCHMACCHasShortConditions() // && // @@ -5383,29 +5383,29 @@ bool XUSPY5XCHMACCHasShortSignal() // // XCHMAMN Long Signal Checking ... -bool XUSPY5XCHMAMNHasLongSignal() +bool XUSCHF5XCHMAMNHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMAMNEnableSignaller || - !xUSPY5MXCHMAMNAllowLongSignals) + if (!xUSCHF5MXCHMAMNEnableSignaller || + !xUSCHF5MXCHMAMNAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMAMNHasLongConditions() + xUSCHF5Provider.XCHMAMNHasLongConditions() // && // @@ -5691,29 +5691,29 @@ bool XUSPY5XCHMAMNHasLongSignal() // // XCHMAMN Short Signal Checking ... -bool XUSPY5XCHMAMNHasShortSignal() +bool XUSCHF5XCHMAMNHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMAMNEnableSignaller || - !xUSPY5MXCHMAMNAllowShortSignals) + if (!xUSCHF5MXCHMAMNEnableSignaller || + !xUSCHF5MXCHMAMNAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMAMNHasShortConditions() + xUSCHF5Provider.XCHMAMNHasShortConditions() // && // @@ -5999,29 +5999,29 @@ bool XUSPY5XCHMAMNHasShortSignal() // // XCHMAMX Long Signal Checking ... -bool XUSPY5XCHMAMXHasLongSignal() +bool XUSCHF5XCHMAMXHasLongSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMAMXEnableSignaller || - !xUSPY5MXCHMAMXAllowLongSignals) + if (!xUSCHF5MXCHMAMXEnableSignaller || + !xUSCHF5MXCHMAMXAllowLongSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMAMXHasLongConditions() + xUSCHF5Provider.XCHMAMXHasLongConditions() // && // @@ -6307,29 +6307,29 @@ bool XUSPY5XCHMAMXHasLongSignal() // // XCHMAMX Short Signal Checking ... -bool XUSPY5XCHMAMXHasShortSignal() +bool XUSCHF5XCHMAMXHasShortSignal() { // bool result = false; // // Validate Args ... - if (!xUSPY5MXCHMAMXEnableSignaller || - !xUSPY5MXCHMAMXAllowShortSignals) + if (!xUSCHF5MXCHMAMXEnableSignaller || + !xUSCHF5MXCHMAMXAllowShortSignals) { return result; } // // Retrieve Market Condition ... - XMarketConditions mConditions = xUSPY5Provider.GetLastMarketCondition(); + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); // // Start Analysing Market based On Conditions ... result = // // Base Condition: - xUSPY5Provider.XCHMAMXHasShortConditions() + xUSCHF5Provider.XCHMAMXHasShortConditions() // && // diff --git a/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 new file mode 100644 index 00000000..d901c24e --- /dev/null +++ b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 @@ -0,0 +1,283 @@ +/////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Library Inputs +// ----------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Include Logger ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Include Classes ... +#include "../Classes/x-saherelm.class.lib.mq5" + +// +input group "XUSCHF5 Provider"; + +// +// Commonly Used Configurations ... +input group "XUSCHF5 Common"; +// +// Provider ... +input bool xUSCHF5EnableProvider = true; // Enable Provider +input int xUSCHF5NumberOfItemsPerTick = 30; // Number Of items Readed In Each Tick +// +// Alerts ... +input bool xUSCHF5EnableAlerts = true; // Enable Events Alert +input bool xUSCHF5EnableHourlyAlerts = false; // Send Alert on each new Hour +input bool xUSCHF5EnableDailyAlerts = false; // Send Alert on each new Day +input bool xUSCHF5EnableWeeklyAlerts = false; // Send Alert on each new Week +input bool xUSCHF5EnableMonthlyAlerts = true; // Send Alert on each new Month +// +// Reports ... +input bool xUSCHF5EnableDailyReports = false; // Send Report on each new Day +input bool xUSCHF5EnableWeeklyReports = false; // Send Report on each new Week +input bool xUSCHF5EnableMonthlyReports = true; // Send Report on each new Month + +// +// Trader and Expert Specific Configurations ... +input group "XUSCHF5 Trader"; +input int xUSCHF5MagicNumber = 16940561; // Trader MagicNumber +input int xUSCHF5Slippage = 10; // Trader Slippage + +// +// Trades Management Configurations ... +input group "XUSCHF5 Trade Management"; +input bool xUSCHF5AllowLongTrades = true; // Allow Long Trades +input bool xUSCHF5AllowShortTrades = true; // Allow Short Trades + +// +// Risk Management Configurations ... +input group "XUSCHF5 Risk Management"; +// +// Trade Count ... +input int xUSCHF5MaxAllowedTrades = 10; // Max Allowed Trades at Same Time +input ENUM_X_CROSS_SIGNAL_METHOD xUSCHF5CrossSignalsMethod = X_CROSS_SIGNAL_REGULAR; // Handle Cross Signals Method +// +// Max Allowed Trade Age ... +input int xUSCHF5MaxAllowedTradeAge = 2000; // Detect Long Time Trades +input ENUM_X_GUARD_ACTIONS xUSCHF5OldTradesAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1; // What to do with Old Trades +// +// Trade Volume Specific Configurations ... +input double xUSCHF5StaticVolumeFactor = 0.0002; // Static Volume baesd on Balance +input ENUM_STATIC_VOLUME_METHODS xUSCHF5StaticVolumeMethod = X_STATIC_VOLUME_BASED_ON_BALANCE; // How to Calculate Static Volume +input double xUSCHF5VolumeMultiplier = 0; // Volume Increase Multiplier +input double xUSCHF5ApplyVolumeMultiplierFactor = 0; // Apply Volume Multiplier Rate based on Balance +input double xUSCHF5MaxSupportedVolumePerTradeFactor = 0; // Max Supported Volume Per Trade Factor based on Balance +input double xUSCHF5IncreasedMaxSupportedVolumeRate = 0; // Increase Max Supported Volume based on Balance +// +// Trade Profits ... +input double xUSCHF5MinRewardInPips = 6; // Minimum Reward Per Trade in Pips +input double xUSCHF5RiskFreeStepInPips = 0; // Make Trades Risk Free Steps in Pips +input double xUSCHF5RiskFreeRate = 0; // Volume Multiplier for Risk Free Trades +// +// Guard Riskable Money and Profits ... +input double xUSCHF5CriticalDrawDownFactor = 0.30; // Critical Allowed Drawdown Factor based on Balance +input ENUM_X_GUARD_ACTIONS xUSCHF5CriticalGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5; // Specify Guard Action on Critical Drawdown +input double xUSCHF5MaxAllowedDrawDownFactor = 0.40; // Max Allowed Drawdown Factor based on Balance +input ENUM_X_GUARD_ACTIONS xUSCHF5MaxAllowedGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10; // Specify Guard Action on Max Allowed Drawdown +input int xUSCHF5GuardStopoutFiredAfterTouches = 5; // Guard Stopout all Trades if Max Allowed Drawdown touched + +// +// Account Conditions for Trading ... +input double xUSCHF5BalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades +input double xUSCHF5FreeMarginFactorForOpenTrades = 0.8; // Minimum Free Margin for Open Trades + +// +// May be Used Later as Input Params ... +bool xUSCHF5UseVirtualTPSl = false; // Use Virtual TP SL +bool xUSCHF5EnableSignalAlerts = false; // Send Signal Alert + +// +// Validate Inputs before Initialization ... +bool XUSCHF5ValidateInputs() +{ + // + bool result = false; + + // + // Implement Other Verifications ... + + // + // Check Trading Availability ... + bool isTradeAvailable = xUSCHF5AllowLongTrades || xUSCHF5AllowShortTrades; + if (!isTradeAvailable) + { + LogMessage("XUSCHF5 => Warning: Trading disabled ..."); + } + + // + // Chekc Number of reading items per tick ... + result = xUSCHF5NumberOfItemsPerTick >= 5; + if (!result) + { + // + LogMessage("XUSCHF5 invalid Number of items Reading Per Tick ..."); + + // + return result; + } + + // + // Check Max Allowed Trades Count ... + result = isTradeAvailable && xUSCHF5MaxAllowedTrades >= 1; + if (!result) + { + // + LogMessage("XUSCHF5 Number of Trades not valid ..."); + + // + return result; + } + + // + // Check Free Margin ... + result = + isTradeAvailable && + xUSCHF5FreeMarginFactorForOpenTrades > 0 && + xUSCHF5FreeMarginFactorForOpenTrades < 1; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Free Margin ..."); + + // + return result; + } + + // + // Check min Balance for Open Trades ... + result = + isTradeAvailable && + xUSCHF5BalanceFactorForOpenTrades > 0 && + xUSCHF5BalanceFactorForOpenTrades < 1; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Min Balance for Open Trades ..."); + + // + return result; + } + + // + // Check Min Reward Per Trade ... + result = xUSCHF5MinRewardInPips > 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Min Reward Per Trade ..."); + + // + return result; + } + + // + // Check Trades Volume ... + result = xUSCHF5StaticVolumeFactor > 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Static Volume ..."); + + // + return result; + } + + // + // Check Volume Multiplier ... + result = xUSCHF5VolumeMultiplier >= 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Volume Multiplier ..."); + + // + return result; + } + + // + result = + xUSCHF5CriticalDrawDownFactor == 0 || (xUSCHF5CriticalDrawDownFactor > 0 && + xUSCHF5CriticalDrawDownFactor < 1); + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Critical DrawDown Factor ..."); + + // + return result; + } + + // + result = + xUSCHF5MaxAllowedDrawDownFactor == 0 || (xUSCHF5MaxAllowedDrawDownFactor > 0 && + xUSCHF5MaxAllowedDrawDownFactor < 1); + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Max Allowed DrawDown Factor ..."); + + // + return result; + } + + // + // Check Guard Actions ... + // + result = + xUSCHF5CriticalDrawDownFactor > 0 && + xUSCHF5CriticalDrawDownFactor < 1 && + xUSCHF5MaxAllowedDrawDownFactor > 0 && + xUSCHF5MaxAllowedDrawDownFactor < 1; + if (!result) + { + // + LogMessage("XUSCHF5 For Critical Drawdown, you have to Specify Max Drawdown also ..."); + + // + return result; + } + + // + result = xUSCHF5CriticalDrawDownFactor > 0 && xUSCHF5CriticalDrawDownFactor < xUSCHF5MaxAllowedDrawDownFactor; + if (!result) + { + // + LogMessage("XUSCHF5 Critical Drawdown must Smaller than Max Drawdown ..."); + + // + return result; + } + + // + if (xUSCHF5CriticalDrawDownFactor > 0 && xUSCHF5CriticalGuardAction == X_GUARD_DO_NOTHING) + { + LogMessage("XUSCHF5 IMPORTANT you Specified Critical Drawdown, but there is no any Guard Action ..."); + } + + // + if (xUSCHF5MaxAllowedDrawDownFactor > 0 && xUSCHF5MaxAllowedGuardAction == X_GUARD_DO_NOTHING) + { + LogMessage("XUSCHF5 IMPORTANT you Specified Max Allowed Drawdown, but there is no any Guard Action ..."); + } + + // + result = true; + + // + return result; +} \ No newline at end of file diff --git a/BKP/Main/Providers/x-saherelm.xuspy5.provider.lib.mq5 b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.lib.mq5 similarity index 60% rename from BKP/Main/Providers/x-saherelm.xuspy5.provider.lib.mq5 rename to Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.lib.mq5 index 797bf5d2..46e26734 100644 --- a/BKP/Main/Providers/x-saherelm.xuspy5.provider.lib.mq5 +++ b/Projects/XUSCHF5/Providers/x-saherelm.xuschf5.provider.lib.mq5 @@ -1,9 +1,9 @@ //////////////////////////////////////////////////////////// // -// SaherElm IT Center MQL5 XUSPY5 Signal Provider Library +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Library // -------------------------------------------------------- -// Name: XUSPY5SignalProvider -// Description: XUSPY5 based signal provider ... +// Name: XUSCHF5SignalProvider +// Description: XUSCHF5 based signal provider ... // // // Maintainer: @@ -19,13 +19,13 @@ #property version "1.00" #property strict -#define XUSPY5ProviderName "XUSPY5" +#define XUSCHF5ProviderName "XUSCHF5" // // START Inputs ... // -#include "x-saherelm.xuspy5.provider.inputs.lib.mq5"; +#include "x-saherelm.xuschf5.provider.inputs.lib.mq5"; // // END Inputs ... @@ -56,42 +56,42 @@ // // -XCGuard *xUSPY5Guard; -XCTrade *xUSPY5Trader; -XCReporter *xUSPY5Reporter; -XCCollector *xUSPY5Collector; -XCAccountInfo *xUSPY5AccountInfo; -XCVolumeManager *xUSPY5VolumeManager; +XCGuard *xUSCHF5Guard; +XCTrade *xUSCHF5Trader; +XCReporter *xUSCHF5Reporter; +XCCollector *xUSCHF5Collector; +XCAccountInfo *xUSCHF5AccountInfo; +XCVolumeManager *xUSCHF5VolumeManager; // -#include "x-saherelm.xuspy5.provider.indicators.lib.mq5" +#include "x-saherelm.xuschf5.provider.indicators.lib.mq5" // // Controlling Variables ... -bool xUSPY5MEnableProvider = false; -bool xUSPY5MAllowLongTrades = false; -bool xUSPY5MAllowShortTrades = false; +bool xUSCHF5MEnableProvider = false; +bool xUSCHF5MAllowLongTrades = false; +bool xUSCHF5MAllowShortTrades = false; // -double xUSPY5Deposit = 0; -double xUSPY5Balance = 0; -double xUSPY5MinReward = 0; -double xUSPY5FreeMargin = 0; -double xUSPY5BalanceForOpenTrades = 0; -double xUSPY5FreeMarginForOpenTrades = 0; +double xUSCHF5Deposit = 0; +double xUSCHF5Balance = 0; +double xUSCHF5MinReward = 0; +double xUSCHF5FreeMargin = 0; +double xUSCHF5BalanceForOpenTrades = 0; +double xUSCHF5FreeMarginForOpenTrades = 0; // // Guard ... -double xUSPY5CriticalDrawDown = 0; -double xUSPY5MaxAllowedDrawDown = 0; +double xUSCHF5CriticalDrawDown = 0; +double xUSCHF5MaxAllowedDrawDown = 0; // -double xUSPY5MaxDrawUp = 0; -double xUSPY5MaxDrawDown = 0; +double xUSCHF5MaxDrawUp = 0; +double xUSCHF5MaxDrawDown = 0; // int NOT_ENOUGH_MONEY_ERROR = 4756; -const string XUSPY5_SUPPORT_ID = "SP"; +const string XUSCHF5_SUPPORT_ID = "SP"; // // END Global Definitions: Variables, Properties and etc ... @@ -103,26 +103,26 @@ const string XUSPY5_SUPPORT_ID = "SP"; // // Initial Library if required ... -bool XUSPY5InitSignalProviderLibrary() +bool XUSCHF5InitSignalProviderLibrary() { // bool result = false; // - if (!xUSPY5EnableProvider) + if (!xUSCHF5EnableProvider) { return result; } // // Controlling Variables ... - xUSPY5MEnableProvider = xUSPY5EnableProvider; - xUSPY5MAllowLongTrades = xUSPY5AllowLongTrades; - xUSPY5MAllowShortTrades = xUSPY5AllowShortTrades; + xUSCHF5MEnableProvider = xUSCHF5EnableProvider; + xUSCHF5MAllowLongTrades = xUSCHF5AllowLongTrades; + xUSCHF5MAllowShortTrades = xUSCHF5AllowShortTrades; // // Validate Inputs ... - result = XUSPY5ValidateInputs(); + result = XUSCHF5ValidateInputs(); if (!result) { return result; @@ -130,113 +130,113 @@ bool XUSPY5InitSignalProviderLibrary() // // Init Indicators ... - result = XUSPY5InitIndicators(); + result = XUSCHF5InitIndicators(); if (!result) { return result; } // - xUSPY5Reporter = new XCReporter(); - xUSPY5Collector = new XCCollector(); - xUSPY5AccountInfo = new XCAccountInfo(); + xUSCHF5Reporter = new XCReporter(); + xUSCHF5Collector = new XCCollector(); + xUSCHF5AccountInfo = new XCAccountInfo(); // // Calculate Account Deposit ... - xUSPY5Deposit = xUSPY5AccountInfo.GetInitialBalance(); + xUSCHF5Deposit = xUSCHF5AccountInfo.GetInitialBalance(); // // Prepare Min Reward ... - if (xUSPY5MinRewardInPips > 0) + if (xUSCHF5MinRewardInPips > 0) { - xUSPY5MinReward = PipsToPrice(xUSPY5MinRewardInPips); + xUSCHF5MinReward = PipsToPrice(xUSCHF5MinRewardInPips); } // // Calculate Min Balance for Trades ... - if (xUSPY5BalanceFactorForOpenTrades > 0) + if (xUSCHF5BalanceFactorForOpenTrades > 0) { - xUSPY5BalanceForOpenTrades = xUSPY5BalanceFactorForOpenTrades * xUSPY5Deposit; + xUSCHF5BalanceForOpenTrades = xUSCHF5BalanceFactorForOpenTrades * xUSCHF5Deposit; } // // Claculate Min Free Marging for Trades ... - if (xUSPY5FreeMarginFactorForOpenTrades > 0) + if (xUSCHF5FreeMarginFactorForOpenTrades > 0) { - xUSPY5FreeMarginForOpenTrades = xUSPY5FreeMarginFactorForOpenTrades * xUSPY5Deposit; + xUSCHF5FreeMarginForOpenTrades = xUSCHF5FreeMarginFactorForOpenTrades * xUSCHF5Deposit; } // // Calculate Init Time Critical DrawDown Value ... - if (xUSPY5CriticalDrawDownFactor > 0) + if (xUSCHF5CriticalDrawDownFactor > 0) { - xUSPY5CriticalDrawDown = xUSPY5CriticalDrawDownFactor * xUSPY5Deposit; + xUSCHF5CriticalDrawDown = xUSCHF5CriticalDrawDownFactor * xUSCHF5Deposit; } // // Calculate Init Time Max Allowed DrawDown Value ... - if (xUSPY5MaxAllowedDrawDownFactor > 0) + if (xUSCHF5MaxAllowedDrawDownFactor > 0) { - xUSPY5MaxAllowedDrawDown = xUSPY5MaxAllowedDrawDownFactor * xUSPY5Deposit; + xUSCHF5MaxAllowedDrawDown = xUSCHF5MaxAllowedDrawDownFactor * xUSCHF5Deposit; } // // Instant Volume Manager ... - xUSPY5VolumeManager = new XCVolumeManager( - xUSPY5StaticVolumeFactor, - xUSPY5StaticVolumeMethod, - xUSPY5VolumeMultiplier, - xUSPY5ApplyVolumeMultiplierFactor, - xUSPY5MaxSupportedVolumePerTradeFactor, - xUSPY5IncreasedMaxSupportedVolumeRate); + xUSCHF5VolumeManager = new XCVolumeManager( + xUSCHF5StaticVolumeFactor, + xUSCHF5StaticVolumeMethod, + xUSCHF5VolumeMultiplier, + xUSCHF5ApplyVolumeMultiplierFactor, + xUSCHF5MaxSupportedVolumePerTradeFactor, + xUSCHF5IncreasedMaxSupportedVolumeRate); // // Make XCTrader instance ... - xUSPY5Trader = new XCTrade( - XUSPY5ProviderName, + xUSCHF5Trader = new XCTrade( + XUSCHF5ProviderName, _Symbol, - xUSPY5Slippage, - xUSPY5MagicNumber, - xUSPY5UseVirtualTPSl, - xUSPY5MaxAllowedTrades, - xUSPY5FreeMarginForOpenTrades, - xUSPY5BalanceForOpenTrades); + xUSCHF5Slippage, + xUSCHF5MagicNumber, + xUSCHF5UseVirtualTPSl, + xUSCHF5MaxAllowedTrades, + xUSCHF5FreeMarginForOpenTrades, + xUSCHF5BalanceForOpenTrades); // // Instantiate Account Guard ... - xUSPY5Guard = new XCGuard( + xUSCHF5Guard = new XCGuard( // // Old Trades ... - xUSPY5MaxAllowedTradeAge, - xUSPY5OldTradesAction, + xUSCHF5MaxAllowedTradeAge, + xUSCHF5OldTradesAction, // // Critical DrawDown ... - xUSPY5CriticalDrawDownFactor, - xUSPY5CriticalGuardAction, + xUSCHF5CriticalDrawDownFactor, + xUSCHF5CriticalGuardAction, // // Max Allowed DrawDown ... - xUSPY5MaxAllowedDrawDownFactor, - xUSPY5MaxAllowedGuardAction, - xUSPY5GuardStopoutFiredAfterTouches, + xUSCHF5MaxAllowedDrawDownFactor, + xUSCHF5MaxAllowedGuardAction, + xUSCHF5GuardStopoutFiredAfterTouches, // - // xUSPY5GuardSupportMethod + // xUSCHF5GuardSupportMethod X_SUPPORT_DO_NOTHING // ); // // Reset Calculations Buffers and Variables ... - XUSPY5ResetCollectors(); + XUSCHF5ResetCollectors(); // - XUSPY5UpdateReports(); + XUSCHF5UpdateReports(); // result = true; // // Logging State ... - XUSPY5IssueInitializationSucceedAlert(); + XUSCHF5IssueInitializationSucceedAlert(); // return result; @@ -244,65 +244,65 @@ bool XUSPY5InitSignalProviderLibrary() // // DeInitial Library if required ... -void XUSPY5DeinitSignalProviderLibrary(const int reason) +void XUSCHF5DeinitSignalProviderLibrary(const int reason) { // // Release Handlers ... - XUSPY5ReleaseIndicators(); + XUSCHF5ReleaseIndicators(); // // Logging State ... - XUSPY5IssueDeinitializationSucceedAlert(); + XUSCHF5IssueDeinitializationSucceedAlert(); } // // this is a Globally Function which do all of // checkings and positions handling ... -void XUSPY5SignalProviderHandleTick() +void XUSCHF5SignalProviderHandleTick() { // // Check Provider is Enable or Not ... - if (!xUSPY5MEnableProvider) + if (!xUSCHF5MEnableProvider) { return; } // - XUSPY5SignalProviderDoControlState(); + XUSCHF5SignalProviderDoControlState(); // // Reading Indicator Buffers ... - XUSPY5HandleReadingBuffers(); - if (xUSPY5CalculatedBars < xUSPY5MaxLengthOfInputs) + XUSCHF5HandleReadingBuffers(); + if (xUSCHF5CalculatedBars < xUSCHF5MaxLengthOfInputs) { return; } // // Handle Open Trades ... - XUSPY5HandleOpenTrades(); + XUSCHF5HandleOpenTrades(); // // Handle Close Trades ... - XUSPY5HandleCloseTrades(); + XUSCHF5HandleCloseTrades(); // // DrawDown and DrawUp ... - XUSPY5HandleCalculateDrawDownUp(); + XUSCHF5HandleCalculateDrawDownUp(); } // // Do Control Checks here ... -void XUSPY5SignalProviderDoControlState() +void XUSCHF5SignalProviderDoControlState() { // // Update account Balance ... - xUSPY5Balance = xUSPY5AccountInfo.GetBalance(); - xUSPY5FreeMargin = xUSPY5AccountInfo.GetFreeMargin(); + xUSCHF5Balance = xUSCHF5AccountInfo.GetBalance(); + xUSCHF5FreeMargin = xUSCHF5AccountInfo.GetFreeMargin(); // // Check Provider is Enable or Not ... - if (!xUSPY5MEnableProvider) + if (!xUSCHF5MEnableProvider) { return; } @@ -312,10 +312,10 @@ void XUSPY5SignalProviderDoControlState() // TODO: add Guard Result here ... string guardMessage = ""; XGuardHandlerResult guardHandlerResult; - bool isGuarded = xUSPY5Guard.Guard( + bool isGuarded = xUSCHF5Guard.Guard( guardHandlerResult, guardMessage, - xUSPY5Trader, + xUSCHF5Trader, _Period); if (isGuarded) { @@ -331,7 +331,7 @@ void XUSPY5SignalProviderDoControlState() XSignal iSignal = guardHandlerResult.criticals[i]; // - XUSPY5OnGuard( + XUSCHF5OnGuard( iSignal, X_GUARDED_CRITICAL, guardMessage); @@ -350,7 +350,7 @@ void XUSPY5SignalProviderDoControlState() XSignal iSignal = guardHandlerResult.maxes[i]; // - XUSPY5OnGuard( + XUSCHF5OnGuard( iSignal, X_GUARDED_MAX, guardMessage, @@ -370,7 +370,7 @@ void XUSPY5SignalProviderDoControlState() XSignal iSignal = guardHandlerResult.olds[i]; // - XUSPY5OnGuard( + XUSCHF5OnGuard( iSignal, X_GUARDED_OLD, guardMessage); @@ -381,9 +381,9 @@ void XUSPY5SignalProviderDoControlState() // // Signal Protection ... XSignal protectSupports[]; - bool isSupported = xUSPY5Guard.ProtectSignals( + bool isSupported = xUSCHF5Guard.ProtectSignals( protectSupports, - xUSPY5Trader); + xUSCHF5Trader); if (isSupported) { // @@ -393,7 +393,7 @@ void XUSPY5SignalProviderDoControlState() // // Handling Signals ... XTraderHandlerResult signalHandlerResult; - xUSPY5Trader.HandleSignals( + xUSCHF5Trader.HandleSignals( signalHandlerResult, false // Ignore Risk Free Trdaes ); @@ -408,7 +408,7 @@ void XUSPY5SignalProviderDoControlState() { // XSignal iSignal = signalHandlerResult.sl[i]; - XUSPY5OnSL(iSignal); + XUSCHF5OnSL(iSignal); } } @@ -422,7 +422,7 @@ void XUSPY5SignalProviderDoControlState() { // XSignal iSignal = signalHandlerResult.tp[i]; - XUSPY5OnTP(iSignal); + XUSCHF5OnTP(iSignal); } } @@ -436,18 +436,18 @@ void XUSPY5SignalProviderDoControlState() { // XSignal iSignal = signalHandlerResult.rf[i]; - XUSPY5OnRF(iSignal); + XUSCHF5OnRF(iSignal); } } } // // Handle Trades when OnTrade Event Hnadler Calls ... -void XUSPY5SignalProviderHandleTrade() +void XUSCHF5SignalProviderHandleTrade() { // // Check Provider Enabled ... - if (!xUSPY5MEnableProvider) + if (!xUSCHF5MEnableProvider) { return; } @@ -455,7 +455,7 @@ void XUSPY5SignalProviderHandleTrade() // // Handle OnTrade Event ... XOnTradeHandlerResult result = {}; - xUSPY5Trader.HandleOnTradeEvent( + xUSCHF5Trader.HandleOnTradeEvent( result); // @@ -463,27 +463,27 @@ void XUSPY5SignalProviderHandleTrade() if (result.hasNewDeal) { // - XDeal last = xUSPY5Trader.GetLastDeal(); + XDeal last = xUSCHF5Trader.GetLastDeal(); // if (last.reason == DEAL_REASON_SL) { - xUSPY5Reporter.AddTradeSLInReports(); + xUSCHF5Reporter.AddTradeSLInReports(); } else if (last.reason == DEAL_REASON_TP) { - xUSPY5Reporter.AddTradeTPInReports(); + xUSCHF5Reporter.AddTradeTPInReports(); } } } // // Handle Open Trades ... -void XUSPY5HandleOpenTrades() +void XUSCHF5HandleOpenTrades() { // // Check Can Trade ... - bool canTrade = xUSPY5MAllowLongTrades || xUSPY5MAllowShortTrades; + bool canTrade = xUSCHF5MAllowLongTrades || xUSCHF5MAllowShortTrades; if (!canTrade) { return; @@ -491,8 +491,8 @@ void XUSPY5HandleOpenTrades() // // Check Max Open Trades ... - int openSignals = xUSPY5Trader.Count(); - bool canOpenPositions = openSignals < xUSPY5MaxAllowedTrades; + int openSignals = xUSCHF5Trader.Count(); + bool canOpenPositions = openSignals < xUSCHF5MaxAllowedTrades; if (!canOpenPositions) { return; @@ -502,8 +502,8 @@ void XUSPY5HandleOpenTrades() // Check Signals Exists ... XProvidedSignal longSignalInfo; XProvidedSignal shortSignalInfo; - bool hasLongSignal = XUSPY5CanOpenLongTrade(longSignalInfo); - bool hasShortSignal = XUSPY5CanOpenShortTrade(shortSignalInfo); + bool hasLongSignal = XUSCHF5CanOpenLongTrade(longSignalInfo); + bool hasShortSignal = XUSCHF5CanOpenShortTrade(shortSignalInfo); if (!hasLongSignal && !hasShortSignal) { return; @@ -511,20 +511,20 @@ void XUSPY5HandleOpenTrades() // // Update Reports ... - XUSPY5UpdateReports(); + XUSCHF5UpdateReports(); // - xUSPY5WaitUntilNextCandle = true; + xUSCHF5WaitUntilNextCandle = true; // // Open Long Trades ... if ( // hasLongSignal && - xUSPY5MAllowLongTrades) + xUSCHF5MAllowLongTrades) { // - bool isOpened = XUSPY5OpenLongPosition(longSignalInfo); + bool isOpened = XUSCHF5OpenLongPosition(longSignalInfo); } // @@ -532,29 +532,29 @@ void XUSPY5HandleOpenTrades() if ( // hasShortSignal && - xUSPY5MAllowShortTrades) + xUSCHF5MAllowShortTrades) { // - bool isOpened = XUSPY5OpenShortPosition(shortSignalInfo); + bool isOpened = XUSCHF5OpenShortPosition(shortSignalInfo); } } // // Handle Close Trades ... -void XUSPY5HandleCloseTrades() +void XUSCHF5HandleCloseTrades() { // // Force Close Long Trades ... bool isClosedLongTrades = false; - bool canCloseLongTrades = XUSPY5CanCloseLongTrade(); - if (xUSPY5MAllowLongTrades && canCloseLongTrades) + bool canCloseLongTrades = XUSCHF5CanCloseLongTrade(); + if (xUSCHF5MAllowLongTrades && canCloseLongTrades) { // ENUM_X_SIGNAL_TYPE type = X_SIGNAL_LONG; // XSignal closed[]; - xUSPY5Trader.CloseSignals( + xUSCHF5Trader.CloseSignals( closed, type); @@ -568,7 +568,7 @@ void XUSPY5HandleCloseTrades() { // XSignal iSignal = closed[i]; - XUSPY5OnFC(iSignal); + XUSCHF5OnFC(iSignal); } } } @@ -576,15 +576,15 @@ void XUSPY5HandleCloseTrades() // // Force Close Short Trades ... bool isClosedShortTrades = false; - bool canCloseShortTrades = XUSPY5CanCloseShortTrade(); - if (xUSPY5MAllowShortTrades && canCloseShortTrades) + bool canCloseShortTrades = XUSCHF5CanCloseShortTrade(); + if (xUSCHF5MAllowShortTrades && canCloseShortTrades) { // ENUM_X_SIGNAL_TYPE type = X_SIGNAL_SHORT; // XSignal closed[]; - xUSPY5Trader.CloseSignals( + xUSCHF5Trader.CloseSignals( closed, type); @@ -598,7 +598,7 @@ void XUSPY5HandleCloseTrades() { // XSignal iSignal = closed[i]; - XUSPY5OnFC(iSignal); + XUSCHF5OnFC(iSignal); } } } @@ -606,7 +606,7 @@ void XUSPY5HandleCloseTrades() // // Open Long Position ... -bool XUSPY5OpenLongPosition( +bool XUSCHF5OpenLongPosition( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -619,14 +619,14 @@ bool XUSPY5OpenLongPosition( double sl = info.sl > 0 ? info.sl : 0; // entry - (200 * _Point); // info.sl > 0 ? info.sl : 0; - double tp = info.tp > 0 ? info.tp : entry + xUSPY5MinReward; - double riskFreeRate = xUSPY5RiskFreeRate; - double riskFreeStep = xUSPY5RiskFreeStepInPips; - double volume = XUSPY5CalculateVolume(ArraySize(info.signallers)); + double tp = info.tp > 0 ? info.tp : entry + xUSCHF5MinReward; + double riskFreeRate = xUSCHF5RiskFreeRate; + double riskFreeStep = xUSCHF5RiskFreeStepInPips; + double volume = XUSCHF5CalculateVolume(ArraySize(info.signallers)); // XSignal signal = {}; - signal = xUSPY5Trader.GenerateSignal( + signal = xUSCHF5Trader.GenerateSignal( X_SIGNAL_LONG, tp, sl, @@ -635,20 +635,20 @@ bool XUSPY5OpenLongPosition( riskFreeRate); bool isValidSignal = IsValid( signal, - xUSPY5MagicNumber); + xUSCHF5MagicNumber); if (!isValidSignal) { return result; } // - int signalsCount = xUSPY5Trader.Count(); + int signalsCount = xUSCHF5Trader.Count(); bool isCross = signalsCount >= 1; if (isCross) { // // Handle Cross Signals ... - XUSPY5HnadleCrossSignal(signal); + XUSCHF5HnadleCrossSignal(signal); } // @@ -661,7 +661,7 @@ bool XUSPY5OpenLongPosition( ( // isCross && - xUSPY5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING + xUSCHF5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING // ); if (!canExecuteSignal) @@ -671,7 +671,7 @@ bool XUSPY5OpenLongPosition( // // Execute Signal ... - ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSPY5Trader.ExecuteSignal( + ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSCHF5Trader.ExecuteSignal( signal, false, // Ignore Number of Trades ... true // Check Account Conditions ... @@ -688,16 +688,16 @@ bool XUSPY5OpenLongPosition( ); // - XSignal tSignal = xUSPY5Trader.GetSignal(signal.ticket); + XSignal tSignal = xUSCHF5Trader.GetSignal(signal.ticket); // - XUSPY5OnSignal( + XUSCHF5OnSignal( tSignal, providers); } else { - XUSPY5IssueSignalExecutionError(executionResult); + XUSCHF5IssueSignalExecutionError(executionResult); } // @@ -706,7 +706,7 @@ bool XUSPY5OpenLongPosition( // // Open Short Position ... -bool XUSPY5OpenShortPosition( +bool XUSCHF5OpenShortPosition( XProvidedSignal &info // Retrieve Signal Additional Info on this Object ) { @@ -719,14 +719,14 @@ bool XUSPY5OpenShortPosition( double sl = info.sl > 0 ? info.sl : 0; // entry + (200 * _Point); // info.sl > 0 ? info.sl : 0; - double tp = info.tp > 0 ? info.tp : entry - xUSPY5MinReward; - double riskFreeRate = xUSPY5RiskFreeRate; - double riskFreeStep = xUSPY5RiskFreeStepInPips; - double volume = XUSPY5CalculateVolume(ArraySize(info.signallers)); + double tp = info.tp > 0 ? info.tp : entry - xUSCHF5MinReward; + double riskFreeRate = xUSCHF5RiskFreeRate; + double riskFreeStep = xUSCHF5RiskFreeStepInPips; + double volume = XUSCHF5CalculateVolume(ArraySize(info.signallers)); // XSignal signal = {}; - signal = xUSPY5Trader.GenerateSignal( + signal = xUSCHF5Trader.GenerateSignal( X_SIGNAL_SHORT, tp, sl, @@ -735,20 +735,20 @@ bool XUSPY5OpenShortPosition( riskFreeRate); bool isValidSignal = IsValid( signal, - xUSPY5MagicNumber); + xUSCHF5MagicNumber); if (!isValidSignal) { return result; } // - int signalsCount = xUSPY5Trader.Count(); + int signalsCount = xUSCHF5Trader.Count(); bool isCross = signalsCount >= 1; if (isCross) { // // Handle Cross Signals ... - XUSPY5HnadleCrossSignal(signal); + XUSCHF5HnadleCrossSignal(signal); } // @@ -761,7 +761,7 @@ bool XUSPY5OpenShortPosition( ( // isCross && - xUSPY5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING + xUSCHF5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING // ); if (!canExecuteSignal) @@ -771,7 +771,7 @@ bool XUSPY5OpenShortPosition( // // Execute Signal ... - ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSPY5Trader.ExecuteSignal( + ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSCHF5Trader.ExecuteSignal( signal, false, // Ignore Number of Trades ... true // Check Account Conditions ... @@ -786,16 +786,16 @@ bool XUSPY5OpenShortPosition( ); // - XSignal tSignal = xUSPY5Trader.GetSignal(signal.ticket); + XSignal tSignal = xUSCHF5Trader.GetSignal(signal.ticket); // - XUSPY5OnSignal( + XUSCHF5OnSignal( tSignal, providers); } else { - XUSPY5IssueSignalExecutionError(executionResult); + XUSCHF5IssueSignalExecutionError(executionResult); } // @@ -804,20 +804,20 @@ bool XUSPY5OpenShortPosition( // // Apply Cross Signal Actions ... -void XUSPY5HnadleCrossSignal( +void XUSCHF5HnadleCrossSignal( XSignal &signal // Specified Signal ... ) { // // Check Cross Signal Handling Enabled ... - if (xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_DO_NOTHING) + if (xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DO_NOTHING) { return; } // // First We have to Change Cross Signals Comment ... - string comment = xUSPY5Trader.GenerateSignalComment( + string comment = xUSCHF5Trader.GenerateSignalComment( signal, true); @@ -826,21 +826,21 @@ void XUSPY5HnadleCrossSignal( // // If Every thing is Regular, prevent any changes here ... - if (xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_REGULAR) + if (xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_REGULAR) { return; } // // Retrieve Max in Drawdown Signal ... - XSignal maxInDDSignal = xUSPY5Trader.GetMaxInDrawdownSignal(); + XSignal maxInDDSignal = xUSCHF5Trader.GetMaxInDrawdownSignal(); // // Validate Signal ... bool isValidSignal = maxInDDSignal.ticket > 0 && maxInDDSignal.symbol == signal.symbol && - IsValid(maxInDDSignal, xUSPY5MagicNumber); + IsValid(maxInDDSignal, xUSCHF5MagicNumber); if (!isValidSignal) { return; @@ -856,14 +856,14 @@ void XUSPY5HnadleCrossSignal( isDirectional ? ( // - xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR || - xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR_INDIRECTION_IMPORTANT + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR || + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR_INDIRECTION_IMPORTANT // ) : ( // - xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_INDIRECTION_REGULAR || - xUSPY5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_IMPORTANT_INDIRECTION_REGULAR + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_INDIRECTION_REGULAR || + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_IMPORTANT_INDIRECTION_REGULAR // ); if (isRegular) @@ -882,11 +882,11 @@ void XUSPY5HnadleCrossSignal( // // Calculate Usefull data ... -void XUSPY5HandleCalculateDrawDownUp() +void XUSCHF5HandleCalculateDrawDownUp() { // XSignal signals[]; - xUSPY5Trader.GetSignals(signals); + xUSCHF5Trader.GetSignals(signals); int signalsCount = ArraySize(signals); if (signalsCount <= 0) { @@ -897,7 +897,7 @@ void XUSPY5HandleCalculateDrawDownUp() double profit = 0; double volume = 0; XCollector collector = {}; - double maxAllowedVolume = xUSPY5VolumeManager.GetMaxAllowedVolume(); + double maxAllowedVolume = xUSCHF5VolumeManager.GetMaxAllowedVolume(); for (int i = 0; i < signalsCount; i++) { // @@ -918,11 +918,11 @@ void XUSPY5HandleCalculateDrawDownUp() if (profit < 0) { // - xUSPY5MaxDrawDown = - xUSPY5MaxDrawDown == 0 || - xUSPY5MaxDrawDown > MathAbs(profit) + xUSCHF5MaxDrawDown = + xUSCHF5MaxDrawDown == 0 || + xUSCHF5MaxDrawDown > MathAbs(profit) ? MathAbs(profit) - : xUSPY5MaxDrawDown; + : xUSCHF5MaxDrawDown; // // Update Buffers ... @@ -933,29 +933,29 @@ void XUSPY5HandleCalculateDrawDownUp() // collector.time = time; collector.volume = volume; - collector.maxDrawDown = xUSPY5MaxDrawDown; + collector.maxDrawDown = xUSCHF5MaxDrawDown; collector.maxAllowedVolume = maxAllowedVolume; - collector.minBalanceForOpenTrade = xUSPY5Trader.GetMinBalanceForOpenTrades(); + collector.minBalanceForOpenTrade = xUSCHF5Trader.GetMinBalanceForOpenTrades(); } else { // - xUSPY5MaxDrawUp = - xUSPY5MaxDrawUp == 0 || - xUSPY5MaxDrawUp < profit + xUSCHF5MaxDrawUp = + xUSCHF5MaxDrawUp == 0 || + xUSCHF5MaxDrawUp < profit ? profit - : xUSPY5MaxDrawUp; + : xUSCHF5MaxDrawUp; } // // Update Collector ... - xUSPY5Collector.Add(collector); + xUSCHF5Collector.Add(collector); // // Update Reports ... - xUSPY5Reporter.UpdateMaxDrawUpInReports(xUSPY5MaxDrawUp); - xUSPY5Reporter.UpdateMaxDrawDownInReports(xUSPY5MaxDrawDown); - xUSPY5Reporter.UpdateMaxSameTimeTradesInReports(signalsCount); + xUSCHF5Reporter.UpdateMaxDrawUpInReports(xUSCHF5MaxDrawUp); + xUSCHF5Reporter.UpdateMaxDrawDownInReports(xUSCHF5MaxDrawDown); + xUSCHF5Reporter.UpdateMaxSameTimeTradesInReports(signalsCount); } // @@ -964,116 +964,116 @@ void XUSPY5HandleCalculateDrawDownUp() // // Runs When a Signal Successfully Executed ... -void XUSPY5OnSignal( +void XUSCHF5OnSignal( XSignal &signal, // Specified Signal string &providers[] // Signal Providers ) { // // Issue Propper Alert ... - XUSPY5IssueSignalExecutionAlert( + XUSCHF5IssueSignalExecutionAlert( signal, providers); // // Add Signal To Supports on Guard ... - xUSPY5Guard.AddSupport(signal); + xUSCHF5Guard.AddSupport(signal); // // Update Reports ... - xUSPY5Reporter.AddSignalToReports( + xUSCHF5Reporter.AddSignalToReports( signal, providers); } // // Runs when a Position Got Take Profit ... -void XUSPY5OnTP( +void XUSCHF5OnTP( XSignal &signal // Specified Signal ) { // // Issue Propper Alert ... - XUSPY5IssueTPAlert(signal); + XUSCHF5IssueTPAlert(signal); // // Remove Signal From Guard Protector ... - xUSPY5Guard.Remove(signal.ticket); - xUSPY5Guard.RemoveSupport(signal.ticket); + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); // // Update Reports ... - xUSPY5Reporter.AddTradeTPInReports(); - XUSPY5UpdateReports(); + xUSCHF5Reporter.AddTradeTPInReports(); + XUSCHF5UpdateReports(); } // // Runs when a Position Got Stop Loss ... -void XUSPY5OnSL( +void XUSCHF5OnSL( XSignal &signal // Specified Signal ) { // // Issue Propper Alert ... - XUSPY5IssueSLAlert(signal); + XUSCHF5IssueSLAlert(signal); // // Remove Signal From Guard Protector ... - xUSPY5Guard.Remove(signal.ticket); - xUSPY5Guard.RemoveSupport(signal.ticket); + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); // // Update Reports ... - xUSPY5Reporter.AddTradeSLInReports(); - XUSPY5UpdateReports(); + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); } // // Runs when a Position Risk Free ... -void XUSPY5OnRF( +void XUSCHF5OnRF( XSignal &signal // Specified Signal ) { // // Issue Propper Alert ... - XUSPY5IssueRFAlert(signal); + XUSCHF5IssueRFAlert(signal); // // Remove Signal From Guard Protector ... // since RiskFree Signals has SL ... - xUSPY5Guard.Remove(signal.ticket); - xUSPY5Guard.RemoveSupport(signal.ticket); + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); // // Update Reports ... - xUSPY5Reporter.AddTradeSLInReports(); - XUSPY5UpdateReports(); + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); } // // Runs when a Position Force Closed ... -void XUSPY5OnFC( +void XUSCHF5OnFC( XSignal &signal // Specified Signal ) { // // Issue Propper Alert ... - XUSPY5IssueFCAlert(signal); + XUSCHF5IssueFCAlert(signal); // // Remove Signal From Guard Protector ... - xUSPY5Guard.Remove(signal.ticket); - xUSPY5Guard.RemoveSupport(signal.ticket); + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); // // Update Reports ... - xUSPY5Reporter.AddTradeSLInReports(); - XUSPY5UpdateReports(); + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); } // // Runs when a Position Guarded ... -void XUSPY5OnGuard( +void XUSCHF5OnGuard( XSignal &signal, // Specified Signal ENUM_X_GUARD_REASONS reason, // Reason of Guard Applied string message, // Guard Returned Message @@ -1088,17 +1088,17 @@ void XUSPY5OnGuard( LogMessage(message); // - xUSPY5MEnableProvider = false; + xUSCHF5MEnableProvider = false; } // // Issue Propper Alert ... - XUSPY5IssueGuardAlert(signal, reason, isStopOut); + XUSCHF5IssueGuardAlert(signal, reason, isStopOut); // // Update Reports ... - xUSPY5Reporter.AddTradeSLInReports(); - XUSPY5UpdateReports(); + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); } // @@ -1119,16 +1119,16 @@ void XUSPY5OnGuard( // // Calculating Volume for Tradings ... -double XUSPY5CalculateVolume( +double XUSCHF5CalculateVolume( double forceMultiplier = 0 // some times we get more than one signal at the same time, here we increase volume using this ... ) { // // Check Open Trades ... - int openSignals = xUSPY5Trader.Count(); + int openSignals = xUSCHF5Trader.Count(); // - double result = xUSPY5VolumeManager.CalculateVolume( + double result = xUSCHF5VolumeManager.CalculateVolume( openSignals, _Symbol); @@ -1153,20 +1153,20 @@ double XUSPY5CalculateVolume( // // Update Report Info ... -void XUSPY5UpdateReports() +void XUSCHF5UpdateReports() { // - double staticVolume = xUSPY5VolumeManager.GetStaticVolume(); - string staticVolumeCalculationMethod = EnumToString(xUSPY5StaticVolumeMethod); - double maxAllowedVolume = xUSPY5VolumeManager.GetMaxAllowedVolume(); - double volumeIncreaseMultiplier = xUSPY5VolumeManager.GetVolumeMultiplier(); - double balanceGowingToApplyMultiplier = xUSPY5VolumeManager.GetIncreaseMultiplierBalance(); + double staticVolume = xUSCHF5VolumeManager.GetStaticVolume(); + string staticVolumeCalculationMethod = EnumToString(xUSCHF5StaticVolumeMethod); + double maxAllowedVolume = xUSCHF5VolumeManager.GetMaxAllowedVolume(); + double volumeIncreaseMultiplier = xUSCHF5VolumeManager.GetVolumeMultiplier(); + double balanceGowingToApplyMultiplier = xUSCHF5VolumeManager.GetIncreaseMultiplierBalance(); - double balanceGrowingToIncreaseMaxAllowedVolume = xUSPY5VolumeManager.GetIncreaseMaxAllowedVolumeBalance(); + double balanceGrowingToIncreaseMaxAllowedVolume = xUSCHF5VolumeManager.GetIncreaseMaxAllowedVolumeBalance(); // // Update Reports Volume Info ... - xUSPY5Reporter.UpdateReportsVolumeInfo( + xUSCHF5Reporter.UpdateReportsVolumeInfo( staticVolume, staticVolumeCalculationMethod, maxAllowedVolume, @@ -1176,24 +1176,24 @@ void XUSPY5UpdateReports() // // Calculate Max Allowed Drawdown ... - double minBalanceForTradeBasedOnBalance = xUSPY5Trader.GetMinBalanceForOpenTrades(); - xUSPY5Reporter.UpdateMinBalanceForOpenTradesInReports(minBalanceForTradeBasedOnBalance); + double minBalanceForTradeBasedOnBalance = xUSCHF5Trader.GetMinBalanceForOpenTrades(); + xUSCHF5Reporter.UpdateMinBalanceForOpenTradesInReports(minBalanceForTradeBasedOnBalance); } // -// Reset XUSPY5 Info Buffers ... -void XUSPY5ResetCollectors() +// Reset XUSCHF5 Info Buffers ... +void XUSCHF5ResetCollectors() { // // Reset Calculations Buffers and Variables ... - xUSPY5MaxDrawUp = 0; - xUSPY5MaxDrawDown = 0; + xUSCHF5MaxDrawUp = 0; + xUSCHF5MaxDrawDown = 0; // - xUSPY5Trader.Reset(); - xUSPY5Reporter.Reset(); - xUSPY5Collector.Reset(); - xUSPY5VolumeManager.ResetForceVolumeMultiplier(); + xUSCHF5Trader.Reset(); + xUSCHF5Reporter.Reset(); + xUSCHF5Collector.Reset(); + xUSCHF5VolumeManager.ResetForceVolumeMultiplier(); } // @@ -1206,7 +1206,7 @@ void XUSPY5ResetCollectors() // // Send Alert ... -void XUSPY5IssueAlert(string message) +void XUSCHF5IssueAlert(string message) { // // Validate Args ... @@ -1216,7 +1216,7 @@ void XUSPY5IssueAlert(string message) } // - if (xUSPY5EnableAlerts) + if (xUSCHF5EnableAlerts) { SendAlert(message); } @@ -1228,7 +1228,7 @@ void XUSPY5IssueAlert(string message) // // Send Take Profit Alert on Specific Signal ... -void XUSPY5IssueTPAlert( +void XUSCHF5IssueTPAlert( XSignal &signal // Specified Signal ) { @@ -1236,15 +1236,15 @@ void XUSPY5IssueTPAlert( string message = ""; // - message = xUSPY5Trader.GenerateSignalTPComment(signal); + message = xUSCHF5Trader.GenerateSignalTPComment(signal); // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Stop Loss Alert on Specific Signal ... -void XUSPY5IssueSLAlert( +void XUSCHF5IssueSLAlert( XSignal &signal // Specified Signal ) { @@ -1252,15 +1252,15 @@ void XUSPY5IssueSLAlert( string message = ""; // - message = xUSPY5Trader.GenerateSignalSLComment(signal); + message = xUSCHF5Trader.GenerateSignalSLComment(signal); // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Force Close Alert on Specific Signal ... -void XUSPY5IssueFCAlert( +void XUSCHF5IssueFCAlert( XSignal &signal // Specified Signal ) { @@ -1268,15 +1268,15 @@ void XUSPY5IssueFCAlert( string message = ""; // - message = xUSPY5Trader.GenerateSignalForceCloseComment(signal); + message = xUSCHF5Trader.GenerateSignalForceCloseComment(signal); // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Risk Free Alert on Specific Signal ... -void XUSPY5IssueRFAlert( +void XUSCHF5IssueRFAlert( XSignal &signal // Specified Signal ) { @@ -1284,15 +1284,15 @@ void XUSPY5IssueRFAlert( string message = ""; // - message = xUSPY5Trader.GenerateSignalRFComment(signal, 0); + message = xUSCHF5Trader.GenerateSignalRFComment(signal, 0); // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Guard Alert on Specific Signal ... -void XUSPY5IssueGuardAlert( +void XUSCHF5IssueGuardAlert( XSignal &signal, // Specified Signal ENUM_X_GUARD_REASONS reason, // Specified Guard Reason bool isStopOut = false // Specified StopOut Fired or not @@ -1302,41 +1302,41 @@ void XUSPY5IssueGuardAlert( string message = ""; // - message = xUSPY5Guard.GenerateGuardedSignalComment( + message = xUSCHF5Guard.GenerateGuardedSignalComment( signal, reason); // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Initialization Succeed Alert ... -void XUSPY5IssueInitializationSucceedAlert() +void XUSCHF5IssueInitializationSucceedAlert() { // - string message = "Initializion of (" + XUSPY5ProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ..."; - XUSPY5IssueAlert(message); + string message = "Initializion of (" + XUSCHF5ProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ..."; + XUSCHF5IssueAlert(message); } // // Send De Initialization Succeed Alert ... -void XUSPY5IssueDeinitializationSucceedAlert() +void XUSCHF5IssueDeinitializationSucceedAlert() { // - string message = "De Initializion of (" + XUSPY5ProviderName + " Provider" + ") Succeeded ..."; - XUSPY5IssueAlert(message); + string message = "De Initializion of (" + XUSCHF5ProviderName + " Provider" + ") Succeeded ..."; + XUSCHF5IssueAlert(message); } // // Send Signal Successfully Execution Alert ... -void XUSPY5IssueSignalExecutionAlert( +void XUSCHF5IssueSignalExecutionAlert( XSignal &signal, // Specified Signal string &providers[] // Signal Providers ) { // - string message = xUSPY5Trader.ToString(signal); + string message = xUSCHF5Trader.ToString(signal); // string providersMsg = ToString(providers); @@ -1346,12 +1346,12 @@ void XUSPY5IssueSignalExecutionAlert( } // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // // Send Signal Execution Alert ... -void XUSPY5IssueSignalExecutionError(int error) +void XUSCHF5IssueSignalExecutionError(int error) { // string message = GetSignalExecutionError(error); @@ -1361,7 +1361,7 @@ void XUSPY5IssueSignalExecutionError(int error) } // - XUSPY5IssueAlert(message); + XUSCHF5IssueAlert(message); } // diff --git a/Projects/XUSCHF5/Settings/.gitkeep b/Projects/XUSCHF5/Settings/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Projects/XUSCHF5/Settings/longs.vbb.set b/Projects/XUSCHF5/Settings/longs.vbb.set new file mode 100644 index 00000000..d87ce948 Binary files /dev/null and b/Projects/XUSCHF5/Settings/longs.vbb.set differ diff --git a/Projects/XUSCHF5/Templates/.gitkeep b/Projects/XUSCHF5/Templates/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 b/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 new file mode 100644 index 00000000..d4e867fa --- /dev/null +++ b/Providers/x-saherelm.xuschf5.provider.indicators.lib.mq5 @@ -0,0 +1,6618 @@ +/////////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Indicators Library +// ---------------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Include Provider Inputs ... +#include "x-saherelm.xuschf5.provider.inputs.lib.mq5" + +// +// Include Provider Class ... +#include "../Classes/x-saherelm.provider.lib.mq5" + +// +// Signallers ... +input group "XUSCHF5 Signallers"; + +// +// XTD ... +input group "XUSCHF5 XTD Signaller"; +input bool xUSCHF5XTDEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTDAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTDAllowShortSignals = true; // Enable Short Signals + +// +// XTAM ... +input group "XUSCHF5 XTAM Signaller"; +input bool xUSCHF5XTAMEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTAMAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTAMAllowShortSignals = true; // Enable Short Signals + +// +// XSI ... +input group "XUSCHF5 XSI Signaller"; +input bool xUSCHF5XSIEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XSIAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XSIAllowShortSignals = true; // Enable Short Signals + +// +// XTSFI ... +input group "XUSCHF5 XTSFI Signaller"; +input bool xUSCHF5XTSFIEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XTSFIAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XTSFIAllowShortSignals = true; // Enable Short Signals + +// +// XOBDLH ... +input group "XUSCHF5 XOBDLH Signaller"; +input bool xUSCHF5XOBDLHEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XOBDLHAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XOBDLHAllowShortSignals = true; // Enable Short Signals + +// +// XCHMACC ... +input group "XUSCHF5 XCHMACC Signaller"; +input bool xUSCHF5XCHMACCEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMACCAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMACCAllowShortSignals = true; // Enable Short Signals + +// +// XCHMAMX ... +input group "XUSCHF5 XCHMAMX Signaller"; +input bool xUSCHF5XCHMAMXEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMAMXAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMAMXAllowShortSignals = true; // Enable Short Signals + +// +// XCHMAMN ... +input group "XUSCHF5 XCHMAMN Signaller"; +input bool xUSCHF5XCHMAMNEnableSignaller = true; // Enable Signaller +input bool xUSCHF5XCHMAMNAllowLongSignals = true; // Enable Long Signals +input bool xUSCHF5XCHMAMNAllowShortSignals = true; // Enable Short Signals + +// +// Check in Test Mode or not ... +bool xUSCHF5IsTestMode = false; + +// +// Detect max Input Length of Indicators ... +int xUSCHF5MaxLengthOfInputs = 0; + +// +// Detect Calculated Bars ... +int xUSCHF5CalculatedBars = 0; + +// +// Check prevent Double Signalling on Same Candle ... +bool xUSCHF5WaitUntilNextCandle = false; + +// +// Signaller Variables ... +// +// XTD ... +bool xUSCHF5MXTDEnableSignaller = xUSCHF5XTDEnableSignaller; +bool xUSCHF5MXTDAllowLongSignals = xUSCHF5XTDAllowLongSignals; +bool xUSCHF5MXTDAllowShortSignals = xUSCHF5XTDAllowShortSignals; + +// +// XTAM ... +bool xUSCHF5MXTAMEnableSignaller = xUSCHF5XTAMEnableSignaller; +bool xUSCHF5MXTAMAllowLongSignals = xUSCHF5XTAMAllowLongSignals; +bool xUSCHF5MXTAMAllowShortSignals = xUSCHF5XTAMAllowShortSignals; + +// +// XSI ... +bool xUSCHF5MXSIEnableSignaller = xUSCHF5XSIEnableSignaller; +bool xUSCHF5MXSIAllowLongSignals = xUSCHF5XSIAllowLongSignals; +bool xUSCHF5MXSIAllowShortSignals = xUSCHF5XSIAllowShortSignals; + +// +// XTSFI ... +bool xUSCHF5MXTSFIEnableSignaller = xUSCHF5XTSFIEnableSignaller; +bool xUSCHF5MXTSFIAllowLongSignals = xUSCHF5XTSFIAllowLongSignals; +bool xUSCHF5MXTSFIAllowShortSignals = xUSCHF5XTSFIAllowShortSignals; + +// +// XOBDLH ... +bool xUSCHF5MXOBDLHEnableSignaller = xUSCHF5XOBDLHEnableSignaller; +bool xUSCHF5MXOBDLHAllowLongSignals = xUSCHF5XOBDLHAllowLongSignals; +bool xUSCHF5MXOBDLHAllowShortSignals = xUSCHF5XOBDLHAllowShortSignals; + +// +// XCHMACC ... +bool xUSCHF5MXCHMACCEnableSignaller = xUSCHF5XCHMACCEnableSignaller; +bool xUSCHF5MXCHMACCAllowLongSignals = xUSCHF5XCHMACCAllowLongSignals; +bool xUSCHF5MXCHMACCAllowShortSignals = xUSCHF5XCHMACCAllowShortSignals; + +// +// XCHMAMX ... +bool xUSCHF5MXCHMAMXEnableSignaller = xUSCHF5XCHMAMXEnableSignaller; +bool xUSCHF5MXCHMAMXAllowLongSignals = xUSCHF5XCHMAMXAllowLongSignals; +bool xUSCHF5MXCHMAMXAllowShortSignals = xUSCHF5XCHMAMXAllowShortSignals; + +// +// XCHMAMN ... +bool xUSCHF5MXCHMAMNEnableSignaller = xUSCHF5XCHMAMNEnableSignaller; +bool xUSCHF5MXCHMAMNAllowLongSignals = xUSCHF5XCHMAMNAllowLongSignals; +bool xUSCHF5MXCHMAMNAllowShortSignals = xUSCHF5XCHMAMNAllowShortSignals; + +// +XCPriver *xUSCHF5Provider; + +// +// Validate Indicators Inputs ... +bool XUSCHF5ValidateIndicatorsInputs() +{ + // + bool result = false; + + // + // XTM ... + result = XTMValidateInputs(); + if (!result) + { + return result; + } + + // + // XAMA ... + result = XAMAValidateInputs(); + if (!result) + { + return result; + } + + // + // XTD ... + result = XTDValidateInputs(); + if (!result) + { + return result; + } + + // + // XFI ... + result = XFIValidateInputs(); + if (!result) + { + return result; + } + + // + // XTS ... + result = XTSValidateInputs(); + if (!result) + { + return result; + } + + // + // XOBD ... + result = XOBDValidateInputs(); + if (!result) + { + return result; + } + + // + // XLH ... + result = XLHValidateInputs(); + if (!result) + { + return result; + } + + // + // XRSI ... + result = XRSIValidateInputs(); + if (!result) + { + return result; + } + + // + // XCHLH ... + result = XCHLHValidateInputs(); + if (!result) + { + return result; + } + + // + // XCHMA ... + result = XCHMAValidateInputs(); + if (!result) + { + return result; + } + + // + // Make an Instance Of XCPriver Class for Use ... + xUSCHF5Provider = new XCPriver( + // + // Commons ... + _Symbol, + _Period, + // + // Signallers ... + // + // XTD ... + xUSCHF5MXTDEnableSignaller, + xUSCHF5MXTDAllowLongSignals, + xUSCHF5MXTDAllowShortSignals, + // + // XTAM ... + xUSCHF5MXTAMEnableSignaller, + xUSCHF5MXTAMAllowLongSignals, + xUSCHF5MXTAMAllowShortSignals, + // + // XSI ... + xUSCHF5MXSIEnableSignaller, + xUSCHF5MXSIAllowLongSignals, + xUSCHF5MXSIAllowShortSignals, + // + // XTSFI ... + xUSCHF5MXTSFIEnableSignaller, + xUSCHF5MXTSFIAllowLongSignals, + xUSCHF5MXTSFIAllowShortSignals, + // + // XOBDLH ... + xUSCHF5MXOBDLHEnableSignaller, + xUSCHF5MXOBDLHAllowLongSignals, + xUSCHF5MXOBDLHAllowShortSignals, + // + // XCHMACC ... + xUSCHF5MXCHMACCEnableSignaller, + xUSCHF5MXCHMACCAllowLongSignals, + xUSCHF5MXCHMACCAllowShortSignals, + // + // XCHMAMX ... + xUSCHF5MXCHMAMXEnableSignaller, + xUSCHF5MXCHMAMXAllowLongSignals, + xUSCHF5MXCHMAMXAllowShortSignals, + // + // XCHMAMN ... + xUSCHF5MXCHMAMNEnableSignaller, + xUSCHF5MXCHMAMNAllowLongSignals, + xUSCHF5MXCHMAMNAllowShortSignals + // + ); + + // + result = true; + + // + return result; +} + +// +// Init Indicators ... +bool XUSCHF5InitIndicators() +{ + // + bool result = false; + + // + // Make it Enable when we need to Log Market Conditions ... + xUSCHF5IsTestMode = IsRunningOnTestMode(); + + // + // Check and Calculate Max Length in Inputs ... + // + + // + // XTM ... + xUSCHF5MaxLengthOfInputs = MathMax( + xTMMaPeriod, + xUSCHF5NumberOfItemsPerTick); + + // + // XAMA ... + xUSCHF5MaxLengthOfInputs = MathMax( + xAMALength, + xUSCHF5NumberOfItemsPerTick); + xUSCHF5MaxLengthOfInputs = MathMax( + xAMAFastEMA, + xUSCHF5NumberOfItemsPerTick); + xUSCHF5MaxLengthOfInputs = MathMax( + xAMASlowEMA, + xUSCHF5NumberOfItemsPerTick); + + // + // XLH ... + xUSCHF5MaxLengthOfInputs = MathMax( + xLHLength, + xUSCHF5NumberOfItemsPerTick); + + // + // XTD ... + xUSCHF5MaxLengthOfInputs = MathMax( + xTDLength, + xUSCHF5MaxLengthOfInputs); + + // + // XFI ... + xUSCHF5MaxLengthOfInputs = MathMax( + xFILength, + xUSCHF5MaxLengthOfInputs); + + // + // XRSI ... + xUSCHF5MaxLengthOfInputs = MathMax( + xRSILength, + xUSCHF5MaxLengthOfInputs); + + // + // XOBD ... + xUSCHF5MaxLengthOfInputs = MathMax( + xOBDLength, + xUSCHF5MaxLengthOfInputs); + + // + // XCHLH ... + xUSCHF5MaxLengthOfInputs = MathMax( + xCHLHLcLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHLHMcLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHLHScLength, + xUSCHF5MaxLengthOfInputs); + + // + // XCHMA ... + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMAScFastLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMAScSlowLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMAMcFastLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMAMcSlowLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMALcFastLength, + xUSCHF5MaxLengthOfInputs); + xUSCHF5MaxLengthOfInputs = MathMax( + xCHMALcSlowLength, + xUSCHF5MaxLengthOfInputs); + + // + // Validate Indicators Inputs before Initialization ... + result = XUSCHF5ValidateIndicatorsInputs(); + if (!result) + { + return result; + } + + // + // Validate Signallers ... + + // + // XTD ... + bool isXTDEnable = + xUSCHF5XTDEnableSignaller && + (xUSCHF5XTDAllowLongSignals || + xUSCHF5XTDAllowShortSignals); + + // + // XTAM ... + bool isXTAMEnable = + xUSCHF5XTAMEnableSignaller && + (xUSCHF5XTAMAllowLongSignals || + xUSCHF5XTAMAllowShortSignals); + + // + // XSI ... + bool isXSIEnable = + xUSCHF5XSIEnableSignaller && + (xUSCHF5XSIAllowLongSignals || + xUSCHF5XSIAllowShortSignals); + + // + // XTSFI ... + bool isXTSFIEnable = + xUSCHF5XTSFIEnableSignaller && + (xUSCHF5XTSFIAllowLongSignals || + xUSCHF5XTSFIAllowShortSignals); + + // + // XOBDLH ... + bool isXOBDLHEnable = + xUSCHF5XOBDLHEnableSignaller && + (xUSCHF5XOBDLHAllowLongSignals || + xUSCHF5XOBDLHAllowShortSignals); + + // + // XCHMACC ... + bool isXCHMACCEnable = + xUSCHF5XCHMACCEnableSignaller && + (xUSCHF5XCHMACCAllowLongSignals || + xUSCHF5XCHMACCAllowShortSignals); + + // + // XCHMAMX ... + bool isXCHMAMXEnable = + xUSCHF5XCHMAMXEnableSignaller && + (xUSCHF5XCHMAMXAllowLongSignals || + xUSCHF5XCHMAMXAllowShortSignals); + + // + // XCHMAMN ... + bool isXCHMAMNEnable = + xUSCHF5XCHMAMNEnableSignaller && + (xUSCHF5XCHMAMNAllowLongSignals || + xUSCHF5XCHMAMNAllowShortSignals); + + // + bool hasSignaller = + // + isXTDEnable || + isXTAMEnable || + isXSIEnable || + isXTSFIEnable || + isXOBDLHEnable || + isXCHMACCEnable || + isXCHMAMXEnable || + isXCHMAMNEnable + // + ; + result = hasSignaller; + if (!result) + { + // + LogMessage("XUSCHF5 doesn't enable any Signaller ..."); + + // + return result; + } + + // + // Initialize Indicator/Oscillator Handlers ... + ResetLastError(); + + // + // XTM Init ... + result = XTMInitHandlers(); + if (!result) + { + return result; + } + + // + // XAMA Init ... + result = XAMAInitHandlers(); + if (!result) + { + return result; + } + + // + // XLH Init ... + result = XLHInitHandlers(); + if (!result) + { + return result; + } + + // + // XTD Init ... + result = XTDInitHandlers(); + if (!result) + { + return result; + } + + // + // XFI Init ... + result = XFIInitHandlers(); + if (!result) + { + return result; + } + + // + // XTS Init ... + result = XTSInitHandlers(); + if (!result) + { + return result; + } + + // + // XRSI Init ... + result = XRSIInitHandlers(); + if (!result) + { + return result; + } + + // + // XOBD Init ... + result = XOBDInitHandlers(); + if (!result) + { + return result; + } + + // + // XCLH Init ... + result = XCHLHInitHandlers(); + if (!result) + { + return result; + } + + // + // XCHMA Init ... + result = XCHMAInitHandlers(); + if (!result) + { + return result; + } + + // + result = true; + + // + return result; +} + +// +// Release Indicators ... +void XUSCHF5ReleaseIndicators() +{ + // + // Release Handlers ... + XTMReleaseHandlers(); + XAMAReleaseHandlers(); + XLHReleaseHandlers(); + XTDReleaseHandlers(); + XFIReleaseHandlers(); + XTSReleaseHandlers(); + XRSIReleaseHandlers(); + XOBDReleaseHandlers(); + XCHMAReleaseHandlers(); + XCHLHReleaseHandlers(); +} + +// +// Handle Reading Buffers ... +void XUSCHF5HandleReadingBuffers() +{ + // + // Reading Calculated Bars for a Simple Handler ... + xUSCHF5CalculatedBars = BarsCalculated(xTMHandler); + + // + // Read Indicators Buffers ... + XTMReadBuffers(xUSCHF5NumberOfItemsPerTick); + XAMAReadBuffers(xUSCHF5NumberOfItemsPerTick); + XLHReadBuffers(xUSCHF5NumberOfItemsPerTick); + XTDReadBuffers(xUSCHF5NumberOfItemsPerTick); + XFIReadBuffers(xUSCHF5NumberOfItemsPerTick); + XTSReadBuffers(xUSCHF5NumberOfItemsPerTick); + XRSIReadBuffers(xUSCHF5NumberOfItemsPerTick); + XOBDReadBuffers(xUSCHF5NumberOfItemsPerTick); + XCHMAReadBuffers(xUSCHF5NumberOfItemsPerTick); + XCHLHReadBuffers(xUSCHF5NumberOfItemsPerTick); + + // + xUSCHF5Provider.ReadConditions(); +} + +// +// +// START Combination Functions ... +// +// + +// +// Can Open Long Trade ... +// this is a Function will Check all market Conditions and get all +// Strategy requirement Verifications for Long Signals ... +bool XUSCHF5CanOpenLongTrade( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + info.tp = 0; + info.sl = 0; + ArrayResize( + info.signallers, + 0); + + // + bool hasSignal = XUSCHF5HasLongSignal(info); + + // + result = + // + hasSignal + // + ; + + // + if (result) + { + xUSCHF5Provider.ClearConditions(); + } + + // + return result; +} + +// +// Can Close Long Trade ... +// this is a Function will Check all market Conditions and get all +// Strategy requirement Verifications for Long Signals ... +bool XUSCHF5CanCloseLongTrade() +{ + // + bool result = false; + + // + return result; +} + +// +// Can Open Short Trade ... +// this is a Function will Check all market Conditions and get all +// Strategy requirement Verifications for Short Signals ... +bool XUSCHF5CanOpenShortTrade( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + info.tp = 0; + info.sl = 0; + ArrayResize( + info.signallers, + 0); + + // + bool hasSignal = XUSCHF5HasShortSignal(info); + + // + result = + // + hasSignal + // + ; + + // + if (result) + { + xUSCHF5Provider.ClearConditions(); + } + + // + return result; +} + +// +// Can Close Short Trade ... +// this is a Function will Check all market Conditions and get all +// Strategy requirement Verifications for Short Signals ... +bool XUSCHF5CanCloseShortTrade() +{ + // + bool result = false; + + // + return result; +} + +// +// +// END Combination Functions ... +// +// + +// +// +// START Combination Signaling ... +// +// + +// +// Check Market Conditions by Combination of Power of All tools for LONGs ... +bool XUSCHF5HasLongSignal( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + // XTD ... + bool isXTDHasSignal = XUSCHF5XTDHasLongSignal(); + if (isXTDHasSignal) + { + // + Add( + EnumToString(XTD), + info.signallers); + } + + // + // XTAM ... + bool isXTAMHasSignal = XUSCHF5XTAMHasLongSignal(); + if (isXTAMHasSignal) + { + // + Add( + EnumToString(XTAM), + info.signallers); + } + + // + // XSI ... + bool isXSIHasSignal = XUSCHF5XSIHasLongSignal(); + if (isXSIHasSignal) + { + // + Add( + EnumToString(XSI), + info.signallers); + } + + // + // XTSFI ... + bool isXTSFIHasSignal = XUSCHF5XTSFIHasLongSignal(); + if (isXTSFIHasSignal) + { + // + Add( + EnumToString(XTSFI), + info.signallers); + } + + // + // XOBD XLH ... + bool isXOBDLHHasSignal = XUSCHF5XOBDLHHasLongSignal(); + if (isXOBDLHHasSignal) + { + // + Add( + EnumToString(XOBDLH), + info.signallers); + } + + // + // XCHMA Cycles Cross ... + bool isXCHMACCHasSignal = XUSCHF5XCHMACCHasLongSignal(); + if (isXCHMACCHasSignal) + { + // + Add( + EnumToString(XCHMACC), + info.signallers); + } + + // + // XCHMA Cycles Min ... + bool isXCHMAMNHasSignal = XUSCHF5XCHMAMNHasLongSignal(); + if (isXCHMAMNHasSignal) + { + // + Add( + EnumToString(XCHMAMN), + info.signallers); + } + + // + // XCHMA Cycles Max + bool isXCHMAMXHasSignal = XUSCHF5XCHMAMXHasLongSignal(); + if (isXCHMAMXHasSignal) + { + // + Add( + EnumToString(XCHMAMX), + info.signallers); + } + + // + result = + // + isXTDHasSignal + // + || + // + isXTAMHasSignal + // + || + // + isXSIHasSignal + // + || + // + isXTSFIHasSignal + // + || + // + isXOBDLHHasSignal + // + || + // + isXCHMACCHasSignal + // + || + // + isXCHMAMNHasSignal + // + || + // + isXCHMAMXHasSignal + // + ; + + // + if (result) + { + // + // Only Log Signals Time Market Conditions if is in Testing Mode ... + if (xUSCHF5IsTestMode || xUSCHF5EnableSignalAlerts) + { + // + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + string message = xUSCHF5Provider.GenerateConditionsString(mConditions); + + // + LogMessage( + "Long Signal Provided by: \n" + + info.signallers[ArraySize(info.signallers) - 1] + "\n" + + "Pusher: " + (string)ArraySize(info.signallers) + "\n" + + "Market Conditions: " + message); + } + } + + // + return result; +} + +// +// Check Market Conditions by Combination of Power of All tools for SHORTs ... +bool XUSCHF5HasShortSignal( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + // XTD ... + bool isXTDHasSignal = XUSCHF5XTDHasShortSignal(); + if (isXTDHasSignal) + { + // + Add( + EnumToString(XTD), + info.signallers); + } + + // + // XTAM ... + bool isXTAMHasSignal = XUSCHF5XTAMHasShortSignal(); + if (isXTAMHasSignal) + { + // + Add( + EnumToString(XTAM), + info.signallers); + } + + // + // XSI ... + bool isXSIHasSignal = XUSCHF5XSIHasShortSignal(); + if (isXSIHasSignal) + { + // + Add( + EnumToString(XSI), + info.signallers); + } + + // + // XTSFI ... + bool isXTSFIHasSignal = XUSCHF5XTSFIHasShortSignal(); + if (isXTSFIHasSignal) + { + // + Add( + EnumToString(XTSFI), + info.signallers); + } + + // + // XOBD XLH ... + bool isXOBDLHHasSignal = XUSCHF5XOBDLHHasShortSignal(); + if (isXOBDLHHasSignal) + { + // + Add( + EnumToString(XOBDLH), + info.signallers); + } + + // + // XCHMA Cycles Cross ... + bool isXCHMACCHasSignal = XUSCHF5XCHMACCHasShortSignal(); + if (isXCHMACCHasSignal) + { + // + Add( + EnumToString(XCHMACC), + info.signallers); + } + + // + // XCHMA Cycles Min ... + bool isXCHMAMNHasSignal = XUSCHF5XCHMAMNHasShortSignal(); + if (isXCHMAMNHasSignal) + { + // + Add( + EnumToString(XCHMAMN), + info.signallers); + } + + // + // XCHMA Cycles Max + bool isXCHMAMXHasSignal = XUSCHF5XCHMAMXHasShortSignal(); + if (isXCHMAMXHasSignal) + { + // + Add( + EnumToString(XCHMAMX), + info.signallers); + } + + // + result = + // + isXTDHasSignal + // + || + // + isXTAMHasSignal + // + || + // + isXSIHasSignal + // + || + // + isXTSFIHasSignal + // + || + // + isXOBDLHHasSignal + // + || + // + isXCHMACCHasSignal + // + || + // + isXCHMAMNHasSignal + // + || + // + isXCHMAMXHasSignal + // + ; + + // + if (result) + { + // + // Only Log Signals Time Market Conditions if is in Testing Mode ... + if (xUSCHF5IsTestMode || xUSCHF5EnableSignalAlerts) + { + // + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + string message = xUSCHF5Provider.GenerateConditionsString(mConditions); + + // + LogMessage( + "Short Signal Provided by: \n" + + info.signallers[ArraySize(info.signallers) - 1] + "\n" + + "Pusher: " + (string)ArraySize(info.signallers) + "\n" + + "Market Conditions: " + message); + } + } + + // + return result; +} + +// +// +// END Combination Signaling ... +// +// + +// +// START Signal Providers ... +// + +// +// Disbale All Signallers Longs ... +void XUSCHF5DisableLongSignallers() +{ + // + // XTD ... + if (xUSCHF5MXTDEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXTDLongs(); + xUSCHF5MXTDAllowLongSignals = false; + } + + // + // XTAM ... + if (xUSCHF5MXTAMEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXTAMLongs(); + xUSCHF5MXTAMAllowLongSignals = false; + } + + // + // XSI ... + if (xUSCHF5MXSIEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXSILongs(); + xUSCHF5MXSIAllowLongSignals = false; + } + + // + // XTSFI ... + if (xUSCHF5MXTSFIEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXTSFILongs(); + xUSCHF5MXTSFIAllowLongSignals = false; + } + + // + // XOBDLH ... + if (xUSCHF5MXOBDLHEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXOBDLHLongs(); + xUSCHF5MXOBDLHAllowLongSignals = false; + } + + // + // XCHMACC ... + if (xUSCHF5MXCHMACCEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXCHMACCLongs(); + xUSCHF5MXCHMACCAllowLongSignals = false; + } + + // + // XCHMAMX ... + if (xUSCHF5MXCHMAMXEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXCHMAMXLongs(); + xUSCHF5MXCHMAMXAllowLongSignals = false; + } + + // + // XCHMAMN ... + if (xUSCHF5MXCHMAMNEnableSignaller) + { + // + xUSCHF5Provider.DisbaleXCHMAMNLongs(); + xUSCHF5MXCHMAMNAllowLongSignals = false; + } +} + +// +// Enable All Signallers Longs ... +// Only if they are Configured as Enable at Settings ... +void XUSCHF5EnableLongSignallers() +{ + // + // XTD ... + if (xUSCHF5MXTDEnableSignaller) + { + // + xUSCHF5MXTDAllowLongSignals = + xUSCHF5XTDAllowLongSignals + ? true + : xUSCHF5MXTDAllowLongSignals; + + // + if (xUSCHF5MXTDAllowLongSignals) + { + xUSCHF5Provider.EnableXTDLongs(); + } + } + + // + // XTAM ... + if (xUSCHF5MXTAMEnableSignaller) + { + // + xUSCHF5MXTAMAllowLongSignals = + xUSCHF5XTAMAllowLongSignals + ? true + : xUSCHF5MXTAMAllowLongSignals; + + // + if (xUSCHF5MXTAMAllowLongSignals) + { + xUSCHF5Provider.EnableXTAMLongs(); + } + } + + // + // XSI ... + if (xUSCHF5MXSIEnableSignaller) + { + // + xUSCHF5MXSIAllowLongSignals = + xUSCHF5XSIAllowLongSignals + ? true + : xUSCHF5MXSIAllowLongSignals; + + // + if (xUSCHF5MXSIAllowLongSignals) + { + xUSCHF5Provider.EnableXSILongs(); + } + } + + // + // XTSFI ... + if (xUSCHF5MXTSFIEnableSignaller) + { + // + xUSCHF5MXTSFIAllowLongSignals = + xUSCHF5XTSFIAllowLongSignals + ? true + : xUSCHF5MXTSFIAllowLongSignals; + + // + if (xUSCHF5MXTSFIAllowLongSignals) + { + xUSCHF5Provider.EnableXTSFILongs(); + } + } + + // + // XOBDLH ... + if (xUSCHF5MXOBDLHEnableSignaller) + { + // + xUSCHF5MXOBDLHAllowLongSignals = + xUSCHF5XOBDLHAllowLongSignals + ? true + : xUSCHF5MXOBDLHAllowLongSignals; + + // + if (xUSCHF5MXOBDLHAllowLongSignals) + { + xUSCHF5Provider.EnableXOBDLHLongs(); + } + } + + // + // XCHMACC ... + if (xUSCHF5MXCHMACCEnableSignaller) + { + // + xUSCHF5MXCHMACCAllowLongSignals = + xUSCHF5XCHMACCAllowLongSignals + ? true + : xUSCHF5MXCHMACCAllowLongSignals; + + // + if (xUSCHF5MXCHMACCAllowLongSignals) + { + xUSCHF5Provider.EnableXCHMACCLongs(); + } + } + + // + // XCHMAMX ... + if (xUSCHF5MXCHMAMXEnableSignaller) + { + // + xUSCHF5MXCHMAMXAllowLongSignals = + xUSCHF5XCHMAMXAllowLongSignals + ? true + : xUSCHF5MXCHMAMXAllowLongSignals; + + // + if (xUSCHF5MXCHMAMXAllowLongSignals) + { + xUSCHF5Provider.EnableXCHMAMXLongs(); + } + } + + // + // XCHMAMN ... + if (xUSCHF5MXCHMAMNEnableSignaller) + { + // + xUSCHF5MXCHMAMNAllowLongSignals = + xUSCHF5XCHMAMNAllowLongSignals + ? true + : xUSCHF5MXCHMAMNAllowLongSignals; + + // + if (xUSCHF5MXCHMAMNAllowLongSignals) + { + xUSCHF5Provider.EnableXCHMAMNLongs(); + } + } +} + +// +// Disable All Signallers Shorts ... +void XUSCHF5DisableShortSignallers() +{ + // + // XTD ... + if (xUSCHF5MXTDEnableSignaller) + { + // + xUSCHF5Provider.DisableXTDShorts(); + xUSCHF5MXTDAllowShortSignals = false; + } + + // + // XTAM ... + if (xUSCHF5MXTAMEnableSignaller) + { + // + xUSCHF5Provider.DisableXTAMShorts(); + xUSCHF5MXTAMAllowShortSignals = false; + } + + // + // XSI ... + if (xUSCHF5MXSIEnableSignaller) + { + // + xUSCHF5Provider.DisableXSIShorts(); + xUSCHF5MXSIAllowShortSignals = false; + } + + // + // XTSFI ... + if (xUSCHF5MXTSFIEnableSignaller) + { + // + xUSCHF5Provider.DisableXTSFIShorts(); + xUSCHF5MXTSFIAllowShortSignals = false; + } + + // + // XOBDLH ... + if (xUSCHF5MXOBDLHEnableSignaller) + { + // + xUSCHF5Provider.DisableXOBDLHShorts(); + xUSCHF5MXOBDLHAllowShortSignals = false; + } + + // + // XCHMACC ... + if (xUSCHF5MXCHMACCEnableSignaller) + { + // + xUSCHF5Provider.DisableXCHMACCShorts(); + xUSCHF5MXCHMACCAllowShortSignals = false; + } + + // + // XCHMAMX ... + if (xUSCHF5MXCHMAMXEnableSignaller) + { + // + xUSCHF5Provider.DisableXCHMAMXShorts(); + xUSCHF5MXCHMAMXAllowShortSignals = false; + } + + // + // XCHMAMN ... + if (xUSCHF5MXCHMAMNEnableSignaller) + { + // + xUSCHF5Provider.DisableXCHMAMNShorts(); + xUSCHF5MXCHMAMNAllowShortSignals = false; + } +} + +// +// Enable All Signallers Shorts ... +// Only if they are Configured as Enable at Settings ... +void XUSCHF5EnableShortSignallers() +{ + // + // XTD ... + if (xUSCHF5MXTDEnableSignaller) + { + // + xUSCHF5MXTDAllowShortSignals = + xUSCHF5XTDAllowShortSignals + ? true + : xUSCHF5MXTDAllowShortSignals; + + // + if (xUSCHF5MXTDAllowShortSignals) + { + xUSCHF5Provider.EnableXTDShorts(); + } + } + + // + // XTAM ... + if (xUSCHF5MXTAMEnableSignaller) + { + // + xUSCHF5MXTAMAllowShortSignals = + xUSCHF5XTAMAllowShortSignals + ? true + : xUSCHF5MXTAMAllowShortSignals; + + // + if (xUSCHF5MXTAMAllowShortSignals) + { + xUSCHF5Provider.EnableXTAMShorts(); + } + } + + // + // XSI ... + if (xUSCHF5MXSIEnableSignaller) + { + // + xUSCHF5MXSIAllowShortSignals = + xUSCHF5XSIAllowShortSignals + ? true + : xUSCHF5MXSIAllowShortSignals; + + // + if (xUSCHF5MXSIAllowShortSignals) + { + xUSCHF5Provider.EnableXSIShorts(); + } + } + + // + // XTSFI ... + if (xUSCHF5MXTSFIEnableSignaller) + { + // + xUSCHF5MXTSFIAllowShortSignals = + xUSCHF5XTSFIAllowShortSignals + ? true + : xUSCHF5MXTSFIAllowShortSignals; + + // + if (xUSCHF5MXTSFIAllowShortSignals) + { + xUSCHF5Provider.EnableXTSFIShorts(); + } + } + + // + // XOBDLH ... + if (xUSCHF5MXOBDLHEnableSignaller) + { + // + xUSCHF5MXOBDLHAllowShortSignals = + xUSCHF5XOBDLHAllowShortSignals + ? true + : xUSCHF5MXOBDLHAllowShortSignals; + + // + if (xUSCHF5MXOBDLHAllowShortSignals) + { + xUSCHF5Provider.EnableXOBDLHShorts(); + } + } + + // + // XCHMACC ... + if (xUSCHF5MXCHMACCEnableSignaller) + { + // + xUSCHF5MXCHMACCAllowShortSignals = + xUSCHF5XCHMACCAllowShortSignals + ? true + : xUSCHF5MXCHMACCAllowShortSignals; + + // + if (xUSCHF5MXCHMACCAllowShortSignals) + { + xUSCHF5Provider.EnableXCHMACCShorts(); + } + } + + // + // XCHMAMX ... + if (xUSCHF5MXCHMAMXEnableSignaller) + { + // + xUSCHF5MXCHMAMXAllowShortSignals = + xUSCHF5XCHMAMXAllowShortSignals + ? true + : xUSCHF5MXCHMAMXAllowShortSignals; + + // + if (xUSCHF5MXCHMAMXAllowShortSignals) + { + xUSCHF5Provider.EnableXCHMAMXShorts(); + } + } + + // + // XCHMAMN ... + if (xUSCHF5MXCHMAMNEnableSignaller) + { + // + xUSCHF5MXCHMAMNAllowShortSignals = + xUSCHF5XCHMAMNAllowShortSignals + ? true + : xUSCHF5MXCHMAMNAllowShortSignals; + + // + if (xUSCHF5MXCHMAMNAllowShortSignals) + { + xUSCHF5Provider.EnableXCHMAMNShorts(); + } + } +} + +// +// +// + +// +// XTD Long Signal Checking ... +bool XUSCHF5XTDHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTDEnableSignaller || + !xUSCHF5MXTDAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTDHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + // + // Check if MC Fast Under Slow ... + ((mConditions.isXCHMAMCFastUnderSlow || + mConditions.isXCHMAMCFastCrossedUnderSlow) && + ( + // + (mConditions.isXCHMAMCVale && + mConditions.isXCHMAMCTrendsUp) + // + || + // + (mConditions.isXCHMAMCVale && + mConditions.isXTSCurrentMax && + mConditions.isXTDBearishVale && + mConditions.isXCHLHMCLCLLSame && + mConditions.isXTDSignalCrossedOverBear && + mConditions.isXTSCurrentCrossedOverFarest && + mConditions.isXTSCurrentCrossedOverMediest) + // + ) + // + ) + // + || + // + ((mConditions.isXCHMAMCTrendsDown && + mConditions.isXCHMAMCFastOverSlow) && + ( + // + (mConditions.isXTMBullish && + mConditions.isXAMABullish && + mConditions.isXCHLHMCLCHHSame && + mConditions.isXTSCurrentUnderFarest && + mConditions.isXTDSignalCrossedOverBear) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + // + ((mConditions.isXCHMAMCTrendsDown && + mConditions.isXCHMAMCFastOverSlow) && + ( + // + (mConditions.isXTMNeutural && + mConditions.isXCHMALCPeak && + mConditions.isXTSCurrentMax && + mConditions.isXTDBearishVale && + mConditions.isXTDSignalCrossedOverBear && + mConditions.isXTSCurrentCrossedOverNearest) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + // + // Check if MC Fast Under Slow ... + ((mConditions.isXCHMAMCFastUnderSlow || + mConditions.isXCHMAMCFastCrossedUnderSlow) && + ( + // + (mConditions.isXCHMAMCVale && + mConditions.isXCHMAMCTrendsUp) + // + ) + // + ) + // + || + // + ((mConditions.isXCHMAMCTrendsDown && + mConditions.isXCHMAMCFastOverSlow) && + ( + // + (mConditions.isXCHMALCPeak && + mConditions.isXTSCurrentMin && + mConditions.isXTDBearishVale && + mConditions.isXCHLHMCLCHHSame && + mConditions.isXTSCurrentUnderFarest && + mConditions.isXTDSignalCrossedOverBear) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + // + // Check if MC Fast Under Slow ... + ((mConditions.isXCHMAMCFastUnderSlow || + mConditions.isXCHMAMCFastCrossedUnderSlow) && + ( + // + (mConditions.isXCHMAMCVale && + mConditions.isXCHMAMCTrendsUp) + // + || + // + (mConditions.isXCHMAMCVale && + mConditions.isXTMNeutural && + mConditions.isXCHMALCVale && + mConditions.isXTSCurrentMax && + mConditions.isXTDSignalCrossedOverBear && + mConditions.isXTSCurrentCrossedOverNearest) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + // + // Check LC Fast Over Slow ... + ((mConditions.isXCHMALCFastOverSlow || + mConditions.isXCHMALCFastCrossedOverSlow) && + ( + // + (mConditions.isXCHMALCPeak && + mConditions.isXCHMALCTrendsDown) + // + ) + // + ) + // + || + // + // Check if MC Fast Under Slow ... + ((mConditions.isXCHMAMCFastUnderSlow || + mConditions.isXCHMAMCFastCrossedUnderSlow) && + ( + // + (mConditions.isXCHMAMCVale && + mConditions.isXCHMAMCTrendsUp) + // + || + // + (mConditions.isXTMBullish && + mConditions.isXAMABullish && + mConditions.isXCHMAMCVale && + mConditions.isXCHMALCPeak && + mConditions.isXTDBearishVale && + mConditions.isXTSCurrentUnderFarest && + mConditions.isXTDSignalCrossedOverBear && + mConditions.isXLHPriceCrossedOverSignal) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + // + // Check LC Fast Over Slow ... + ((mConditions.isXCHMALCFastOverSlow || + mConditions.isXCHMALCFastCrossedOverSlow) && + ( + // + (mConditions.isXCHMALCPeak && + mConditions.isXCHMALCTrendsDown) + // + || + // + (mConditions.isXTMBullish && + mConditions.isXAMABullish && + mConditions.isXTSCurrentUnderNearest && + mConditions.isXTDSignalCrossedOverBear && + mConditions.isXTSCurrentCrossedUnderNearest) + // + ) + // + ) + // + || + // + // Check LC Fast Under Slow ... + ((mConditions.isXCHMALCFastUnderSlow || + mConditions.isXCHMALCFastCrossedUnderSlow) && + ( + // + (mConditions.isXCHLHSameHHs && + mConditions.isXTSCurrentMax && + mConditions.isXLHHighAttachedHH && + mConditions.isXTDSignalCrossedOverBear) + // + ) + // + ) + // + ) + // + ) + // + || + // + // XTD Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XTD Short Signal Checking ... +bool XUSCHF5XTDHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTDEnableSignaller || + !xUSCHF5MXTDAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTDHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTD Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTD Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XTAM Long Signal Checking ... +bool XUSCHF5XTAMHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTAMEnableSignaller || + !xUSCHF5MXTAMAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTAMHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XTAM Short Signal Checking ... +bool XUSCHF5XTAMHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTAMEnableSignaller || + !xUSCHF5MXTAMAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTAMHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTAM Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTAM Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XSI Long Signal Checking ... +bool XUSCHF5XSIHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXSIEnableSignaller || + !xUSCHF5MXSIAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XSIHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XSI Short Signal Checking ... +bool XUSCHF5XSIHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXSIEnableSignaller || + !xUSCHF5MXSIAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XSIHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XSI Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XSI Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XTSFI Long Signal Checking ... +bool XUSCHF5XTSFIHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTSFIEnableSignaller || + !xUSCHF5MXTSFIAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTSFIHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XTSFI Short Signal Checking ... +bool XUSCHF5XTSFIHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXTSFIEnableSignaller || + !xUSCHF5MXTSFIAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XTSFIHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XTSFI Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XTSFI Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XOBDLH Long Signal Checking ... +bool XUSCHF5XOBDLHHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXOBDLHEnableSignaller || + !xUSCHF5MXOBDLHAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XOBDLHHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XOBDLH Short Signal Checking ... +bool XUSCHF5XOBDLHHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXOBDLHEnableSignaller || + !xUSCHF5MXOBDLHAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XOBDLHHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XOBDLH Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XOBDLH Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMACC Long Signal Checking ... +bool XUSCHF5XCHMACCHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMACCEnableSignaller || + !xUSCHF5MXCHMACCAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMACCHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMACC Short Signal Checking ... +bool XUSCHF5XCHMACCHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMACCEnableSignaller || + !xUSCHF5MXCHMACCAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMACCHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMACC Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMACC Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMAMN Long Signal Checking ... +bool XUSCHF5XCHMAMNHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMAMNEnableSignaller || + !xUSCHF5MXCHMAMNAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMAMNHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMAMN Short Signal Checking ... +bool XUSCHF5XCHMAMNHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMAMNEnableSignaller || + !xUSCHF5MXCHMAMNAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMAMNHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMN Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMN Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMAMX Long Signal Checking ... +bool XUSCHF5XCHMAMXHasLongSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMAMXEnableSignaller || + !xUSCHF5MXCHMAMXAllowLongSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMAMXHasLongConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Long ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Long ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Long ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Long ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Long ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// XCHMAMX Short Signal Checking ... +bool XUSCHF5XCHMAMXHasShortSignal() +{ + // + bool result = false; + + // + // Validate Args ... + if (!xUSCHF5MXCHMAMXEnableSignaller || + !xUSCHF5MXCHMAMXAllowShortSignals) + { + return result; + } + + // + // Retrieve Market Condition ... + XMarketConditions mConditions = xUSCHF5Provider.GetLastMarketCondition(); + + // + // Start Analysing Market based On Conditions ... + result = + // + // Base Condition: + xUSCHF5Provider.XCHMAMXHasShortConditions() + // + && + // + // Exceptions: + // there some commonly Exceptions which makes our choice incorrect, + // here we are combined knownly Exceptions ... + !( + // + // for Exception we used XLH Conditions as follow ... + // + // Check Conditions if Price In Signal Range ... + (mConditions.isXLHPriceInSignalRange && + // + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Short ... + // PriceInSignalRange ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceInSignalRange ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceInSignalRange ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceInSignalRange ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Under Signal ... + ( + // + ((mConditions.isXLHPriceUnderSignal || + mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Short ... + // PriceUnderSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceUnderSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceUnderSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceUnderSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is Over Signal ... + ( + // + ((mConditions.isXLHPriceOverSignal || + mConditions.isXLHPriceCrossedOverSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Short ... + // PriceOverSignal ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceOverSignal ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceOverSignal ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceOverSignal ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + || + // + // Check Conditions if Price is not has clear state ... + ( + // + ((!mConditions.isXLHPriceOverSignal && + !mConditions.isXLHPriceUnderSignal && + !mConditions.isXLHPriceInSignalRange && + !mConditions.isXLHPriceCrossedOverSignal && + !mConditions.isXLHPriceCrossedUnderSignal) && + ( + // + // Next Step is to Check LL and HH Same Style ... + // + // XCHMAMX Short ... + // PriceFree ... + // Check if Both LL and HH Same In Length ... + ((mConditions.isXLHLLSameInLength && + mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceFree ... + // Check If LL Same In Length ... + ((mConditions.isXLHLLSameInLength && + !mConditions.isXLHHHSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceFree ... + // Check If HH is Same In Length ... + ((mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + || + // + // XCHMAMX Short ... + // PriceFree ... + // Not Same LL or HH in Lenght ... + ((!mConditions.isXLHHHSameInLength && + !mConditions.isXLHLLSameInLength) && + // + ( + false) + // + ) + // + ) + // + ) + // + ) + // + ) + // + ; + + // + return result; +} + +// +// END Signal Providers ... +// diff --git a/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 b/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 new file mode 100644 index 00000000..d901c24e --- /dev/null +++ b/Providers/x-saherelm.xuschf5.provider.inputs.lib.mq5 @@ -0,0 +1,283 @@ +/////////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Library Inputs +// ----------------------------------------------------------- +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Include Logger ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Include Classes ... +#include "../Classes/x-saherelm.class.lib.mq5" + +// +input group "XUSCHF5 Provider"; + +// +// Commonly Used Configurations ... +input group "XUSCHF5 Common"; +// +// Provider ... +input bool xUSCHF5EnableProvider = true; // Enable Provider +input int xUSCHF5NumberOfItemsPerTick = 30; // Number Of items Readed In Each Tick +// +// Alerts ... +input bool xUSCHF5EnableAlerts = true; // Enable Events Alert +input bool xUSCHF5EnableHourlyAlerts = false; // Send Alert on each new Hour +input bool xUSCHF5EnableDailyAlerts = false; // Send Alert on each new Day +input bool xUSCHF5EnableWeeklyAlerts = false; // Send Alert on each new Week +input bool xUSCHF5EnableMonthlyAlerts = true; // Send Alert on each new Month +// +// Reports ... +input bool xUSCHF5EnableDailyReports = false; // Send Report on each new Day +input bool xUSCHF5EnableWeeklyReports = false; // Send Report on each new Week +input bool xUSCHF5EnableMonthlyReports = true; // Send Report on each new Month + +// +// Trader and Expert Specific Configurations ... +input group "XUSCHF5 Trader"; +input int xUSCHF5MagicNumber = 16940561; // Trader MagicNumber +input int xUSCHF5Slippage = 10; // Trader Slippage + +// +// Trades Management Configurations ... +input group "XUSCHF5 Trade Management"; +input bool xUSCHF5AllowLongTrades = true; // Allow Long Trades +input bool xUSCHF5AllowShortTrades = true; // Allow Short Trades + +// +// Risk Management Configurations ... +input group "XUSCHF5 Risk Management"; +// +// Trade Count ... +input int xUSCHF5MaxAllowedTrades = 10; // Max Allowed Trades at Same Time +input ENUM_X_CROSS_SIGNAL_METHOD xUSCHF5CrossSignalsMethod = X_CROSS_SIGNAL_REGULAR; // Handle Cross Signals Method +// +// Max Allowed Trade Age ... +input int xUSCHF5MaxAllowedTradeAge = 2000; // Detect Long Time Trades +input ENUM_X_GUARD_ACTIONS xUSCHF5OldTradesAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_1; // What to do with Old Trades +// +// Trade Volume Specific Configurations ... +input double xUSCHF5StaticVolumeFactor = 0.0002; // Static Volume baesd on Balance +input ENUM_STATIC_VOLUME_METHODS xUSCHF5StaticVolumeMethod = X_STATIC_VOLUME_BASED_ON_BALANCE; // How to Calculate Static Volume +input double xUSCHF5VolumeMultiplier = 0; // Volume Increase Multiplier +input double xUSCHF5ApplyVolumeMultiplierFactor = 0; // Apply Volume Multiplier Rate based on Balance +input double xUSCHF5MaxSupportedVolumePerTradeFactor = 0; // Max Supported Volume Per Trade Factor based on Balance +input double xUSCHF5IncreasedMaxSupportedVolumeRate = 0; // Increase Max Supported Volume based on Balance +// +// Trade Profits ... +input double xUSCHF5MinRewardInPips = 6; // Minimum Reward Per Trade in Pips +input double xUSCHF5RiskFreeStepInPips = 0; // Make Trades Risk Free Steps in Pips +input double xUSCHF5RiskFreeRate = 0; // Volume Multiplier for Risk Free Trades +// +// Guard Riskable Money and Profits ... +input double xUSCHF5CriticalDrawDownFactor = 0.30; // Critical Allowed Drawdown Factor based on Balance +input ENUM_X_GUARD_ACTIONS xUSCHF5CriticalGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_5; // Specify Guard Action on Critical Drawdown +input double xUSCHF5MaxAllowedDrawDownFactor = 0.40; // Max Allowed Drawdown Factor based on Balance +input ENUM_X_GUARD_ACTIONS xUSCHF5MaxAllowedGuardAction = X_GUARD_PARTIAL_CLOSE_MAX_IN_DD_10; // Specify Guard Action on Max Allowed Drawdown +input int xUSCHF5GuardStopoutFiredAfterTouches = 5; // Guard Stopout all Trades if Max Allowed Drawdown touched + +// +// Account Conditions for Trading ... +input double xUSCHF5BalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades +input double xUSCHF5FreeMarginFactorForOpenTrades = 0.8; // Minimum Free Margin for Open Trades + +// +// May be Used Later as Input Params ... +bool xUSCHF5UseVirtualTPSl = false; // Use Virtual TP SL +bool xUSCHF5EnableSignalAlerts = false; // Send Signal Alert + +// +// Validate Inputs before Initialization ... +bool XUSCHF5ValidateInputs() +{ + // + bool result = false; + + // + // Implement Other Verifications ... + + // + // Check Trading Availability ... + bool isTradeAvailable = xUSCHF5AllowLongTrades || xUSCHF5AllowShortTrades; + if (!isTradeAvailable) + { + LogMessage("XUSCHF5 => Warning: Trading disabled ..."); + } + + // + // Chekc Number of reading items per tick ... + result = xUSCHF5NumberOfItemsPerTick >= 5; + if (!result) + { + // + LogMessage("XUSCHF5 invalid Number of items Reading Per Tick ..."); + + // + return result; + } + + // + // Check Max Allowed Trades Count ... + result = isTradeAvailable && xUSCHF5MaxAllowedTrades >= 1; + if (!result) + { + // + LogMessage("XUSCHF5 Number of Trades not valid ..."); + + // + return result; + } + + // + // Check Free Margin ... + result = + isTradeAvailable && + xUSCHF5FreeMarginFactorForOpenTrades > 0 && + xUSCHF5FreeMarginFactorForOpenTrades < 1; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Free Margin ..."); + + // + return result; + } + + // + // Check min Balance for Open Trades ... + result = + isTradeAvailable && + xUSCHF5BalanceFactorForOpenTrades > 0 && + xUSCHF5BalanceFactorForOpenTrades < 1; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Min Balance for Open Trades ..."); + + // + return result; + } + + // + // Check Min Reward Per Trade ... + result = xUSCHF5MinRewardInPips > 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Min Reward Per Trade ..."); + + // + return result; + } + + // + // Check Trades Volume ... + result = xUSCHF5StaticVolumeFactor > 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Static Volume ..."); + + // + return result; + } + + // + // Check Volume Multiplier ... + result = xUSCHF5VolumeMultiplier >= 0; + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Volume Multiplier ..."); + + // + return result; + } + + // + result = + xUSCHF5CriticalDrawDownFactor == 0 || (xUSCHF5CriticalDrawDownFactor > 0 && + xUSCHF5CriticalDrawDownFactor < 1); + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Critical DrawDown Factor ..."); + + // + return result; + } + + // + result = + xUSCHF5MaxAllowedDrawDownFactor == 0 || (xUSCHF5MaxAllowedDrawDownFactor > 0 && + xUSCHF5MaxAllowedDrawDownFactor < 1); + if (!result) + { + // + LogMessage("XUSCHF5 Invalid Max Allowed DrawDown Factor ..."); + + // + return result; + } + + // + // Check Guard Actions ... + // + result = + xUSCHF5CriticalDrawDownFactor > 0 && + xUSCHF5CriticalDrawDownFactor < 1 && + xUSCHF5MaxAllowedDrawDownFactor > 0 && + xUSCHF5MaxAllowedDrawDownFactor < 1; + if (!result) + { + // + LogMessage("XUSCHF5 For Critical Drawdown, you have to Specify Max Drawdown also ..."); + + // + return result; + } + + // + result = xUSCHF5CriticalDrawDownFactor > 0 && xUSCHF5CriticalDrawDownFactor < xUSCHF5MaxAllowedDrawDownFactor; + if (!result) + { + // + LogMessage("XUSCHF5 Critical Drawdown must Smaller than Max Drawdown ..."); + + // + return result; + } + + // + if (xUSCHF5CriticalDrawDownFactor > 0 && xUSCHF5CriticalGuardAction == X_GUARD_DO_NOTHING) + { + LogMessage("XUSCHF5 IMPORTANT you Specified Critical Drawdown, but there is no any Guard Action ..."); + } + + // + if (xUSCHF5MaxAllowedDrawDownFactor > 0 && xUSCHF5MaxAllowedGuardAction == X_GUARD_DO_NOTHING) + { + LogMessage("XUSCHF5 IMPORTANT you Specified Max Allowed Drawdown, but there is no any Guard Action ..."); + } + + // + result = true; + + // + return result; +} \ No newline at end of file diff --git a/Providers/x-saherelm.xuschf5.provider.lib.mq5 b/Providers/x-saherelm.xuschf5.provider.lib.mq5 new file mode 100644 index 00000000..46e26734 --- /dev/null +++ b/Providers/x-saherelm.xuschf5.provider.lib.mq5 @@ -0,0 +1,1373 @@ +//////////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XUSCHF5 Signal Provider Library +// -------------------------------------------------------- +// Name: XUSCHF5SignalProvider +// Description: XUSCHF5 based signal provider ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +#define XUSCHF5ProviderName "XUSCHF5" + +// +// START Inputs ... +// + +#include "x-saherelm.xuschf5.provider.inputs.lib.mq5"; + +// +// END Inputs ... +// + +// +// Include Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Include Logger Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" + +// +// Include Alert Library ... +#include "../Libraries/x-saherelm.alert.lib.mq5" + +// +// Include Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// Include Class Libraries ... +#include "../Classes/x-saherelm.class.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +XCGuard *xUSCHF5Guard; +XCTrade *xUSCHF5Trader; +XCReporter *xUSCHF5Reporter; +XCCollector *xUSCHF5Collector; +XCAccountInfo *xUSCHF5AccountInfo; +XCVolumeManager *xUSCHF5VolumeManager; + +// +#include "x-saherelm.xuschf5.provider.indicators.lib.mq5" + +// +// Controlling Variables ... +bool xUSCHF5MEnableProvider = false; +bool xUSCHF5MAllowLongTrades = false; +bool xUSCHF5MAllowShortTrades = false; + +// +double xUSCHF5Deposit = 0; +double xUSCHF5Balance = 0; +double xUSCHF5MinReward = 0; +double xUSCHF5FreeMargin = 0; +double xUSCHF5BalanceForOpenTrades = 0; +double xUSCHF5FreeMarginForOpenTrades = 0; + +// +// Guard ... +double xUSCHF5CriticalDrawDown = 0; +double xUSCHF5MaxAllowedDrawDown = 0; + +// +double xUSCHF5MaxDrawUp = 0; +double xUSCHF5MaxDrawDown = 0; + +// +int NOT_ENOUGH_MONEY_ERROR = 4756; +const string XUSCHF5_SUPPORT_ID = "SP"; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// + +// +// Initial Library if required ... +bool XUSCHF5InitSignalProviderLibrary() +{ + // + bool result = false; + + // + if (!xUSCHF5EnableProvider) + { + return result; + } + + // + // Controlling Variables ... + xUSCHF5MEnableProvider = xUSCHF5EnableProvider; + xUSCHF5MAllowLongTrades = xUSCHF5AllowLongTrades; + xUSCHF5MAllowShortTrades = xUSCHF5AllowShortTrades; + + // + // Validate Inputs ... + result = XUSCHF5ValidateInputs(); + if (!result) + { + return result; + } + + // + // Init Indicators ... + result = XUSCHF5InitIndicators(); + if (!result) + { + return result; + } + + // + xUSCHF5Reporter = new XCReporter(); + xUSCHF5Collector = new XCCollector(); + xUSCHF5AccountInfo = new XCAccountInfo(); + + // + // Calculate Account Deposit ... + xUSCHF5Deposit = xUSCHF5AccountInfo.GetInitialBalance(); + + // + // Prepare Min Reward ... + if (xUSCHF5MinRewardInPips > 0) + { + xUSCHF5MinReward = PipsToPrice(xUSCHF5MinRewardInPips); + } + + // + // Calculate Min Balance for Trades ... + if (xUSCHF5BalanceFactorForOpenTrades > 0) + { + xUSCHF5BalanceForOpenTrades = xUSCHF5BalanceFactorForOpenTrades * xUSCHF5Deposit; + } + + // + // Claculate Min Free Marging for Trades ... + if (xUSCHF5FreeMarginFactorForOpenTrades > 0) + { + xUSCHF5FreeMarginForOpenTrades = xUSCHF5FreeMarginFactorForOpenTrades * xUSCHF5Deposit; + } + + // + // Calculate Init Time Critical DrawDown Value ... + if (xUSCHF5CriticalDrawDownFactor > 0) + { + xUSCHF5CriticalDrawDown = xUSCHF5CriticalDrawDownFactor * xUSCHF5Deposit; + } + + // + // Calculate Init Time Max Allowed DrawDown Value ... + if (xUSCHF5MaxAllowedDrawDownFactor > 0) + { + xUSCHF5MaxAllowedDrawDown = xUSCHF5MaxAllowedDrawDownFactor * xUSCHF5Deposit; + } + + // + // Instant Volume Manager ... + xUSCHF5VolumeManager = new XCVolumeManager( + xUSCHF5StaticVolumeFactor, + xUSCHF5StaticVolumeMethod, + xUSCHF5VolumeMultiplier, + xUSCHF5ApplyVolumeMultiplierFactor, + xUSCHF5MaxSupportedVolumePerTradeFactor, + xUSCHF5IncreasedMaxSupportedVolumeRate); + + // + // Make XCTrader instance ... + xUSCHF5Trader = new XCTrade( + XUSCHF5ProviderName, + _Symbol, + xUSCHF5Slippage, + xUSCHF5MagicNumber, + xUSCHF5UseVirtualTPSl, + xUSCHF5MaxAllowedTrades, + xUSCHF5FreeMarginForOpenTrades, + xUSCHF5BalanceForOpenTrades); + + // + // Instantiate Account Guard ... + xUSCHF5Guard = new XCGuard( + // + // Old Trades ... + xUSCHF5MaxAllowedTradeAge, + xUSCHF5OldTradesAction, + // + // Critical DrawDown ... + xUSCHF5CriticalDrawDownFactor, + xUSCHF5CriticalGuardAction, + // + // Max Allowed DrawDown ... + xUSCHF5MaxAllowedDrawDownFactor, + xUSCHF5MaxAllowedGuardAction, + xUSCHF5GuardStopoutFiredAfterTouches, + // + // xUSCHF5GuardSupportMethod + X_SUPPORT_DO_NOTHING + // + ); + + // + // Reset Calculations Buffers and Variables ... + XUSCHF5ResetCollectors(); + + // + XUSCHF5UpdateReports(); + + // + result = true; + + // + // Logging State ... + XUSCHF5IssueInitializationSucceedAlert(); + + // + return result; +} + +// +// DeInitial Library if required ... +void XUSCHF5DeinitSignalProviderLibrary(const int reason) +{ + // + // Release Handlers ... + XUSCHF5ReleaseIndicators(); + + // + // Logging State ... + XUSCHF5IssueDeinitializationSucceedAlert(); +} + +// +// this is a Globally Function which do all of +// checkings and positions handling ... +void XUSCHF5SignalProviderHandleTick() +{ + // + // Check Provider is Enable or Not ... + if (!xUSCHF5MEnableProvider) + { + return; + } + + // + XUSCHF5SignalProviderDoControlState(); + + // + // Reading Indicator Buffers ... + XUSCHF5HandleReadingBuffers(); + if (xUSCHF5CalculatedBars < xUSCHF5MaxLengthOfInputs) + { + return; + } + + // + // Handle Open Trades ... + XUSCHF5HandleOpenTrades(); + + // + // Handle Close Trades ... + XUSCHF5HandleCloseTrades(); + + // + // DrawDown and DrawUp ... + XUSCHF5HandleCalculateDrawDownUp(); +} + +// +// Do Control Checks here ... +void XUSCHF5SignalProviderDoControlState() +{ + // + // Update account Balance ... + xUSCHF5Balance = xUSCHF5AccountInfo.GetBalance(); + xUSCHF5FreeMargin = xUSCHF5AccountInfo.GetFreeMargin(); + + // + // Check Provider is Enable or Not ... + if (!xUSCHF5MEnableProvider) + { + return; + } + + // + // Protect Account by Guarding Maximum Drawdown ... + // TODO: add Guard Result here ... + string guardMessage = ""; + XGuardHandlerResult guardHandlerResult; + bool isGuarded = xUSCHF5Guard.Guard( + guardHandlerResult, + guardMessage, + xUSCHF5Trader, + _Period); + if (isGuarded) + { + // + // Criticals ... + int criticalsCount = ArraySize(guardHandlerResult.criticals); + if (criticalsCount > 0) + { + // + for (int i = 0; i < criticalsCount; i++) + { + // + XSignal iSignal = guardHandlerResult.criticals[i]; + + // + XUSCHF5OnGuard( + iSignal, + X_GUARDED_CRITICAL, + guardMessage); + } + } + + // + // Maxes ... + int maxesCount = ArraySize(guardHandlerResult.maxes); + if (maxesCount > 0) + { + // + for (int i = 0; i < maxesCount; i++) + { + // + XSignal iSignal = guardHandlerResult.maxes[i]; + + // + XUSCHF5OnGuard( + iSignal, + X_GUARDED_MAX, + guardMessage, + guardHandlerResult.isStopOut); + } + } + + // + // Olds ... + int oldsCount = ArraySize(guardHandlerResult.olds); + if (oldsCount > 0) + { + // + for (int i = 0; i < oldsCount; i++) + { + // + XSignal iSignal = guardHandlerResult.olds[i]; + + // + XUSCHF5OnGuard( + iSignal, + X_GUARDED_OLD, + guardMessage); + } + } + } + + // + // Signal Protection ... + XSignal protectSupports[]; + bool isSupported = xUSCHF5Guard.ProtectSignals( + protectSupports, + xUSCHF5Trader); + if (isSupported) + { + // + LogMessage("Guard do Support Trdae ..."); + } + + // + // Handling Signals ... + XTraderHandlerResult signalHandlerResult; + xUSCHF5Trader.HandleSignals( + signalHandlerResult, + false // Ignore Risk Free Trdaes + ); + + // + // Handle Sl Reports ... + int handledSLsCount = ArraySize(signalHandlerResult.sl); + if (handledSLsCount > 0) + { + // + for (int i = 0; i < handledSLsCount; i++) + { + // + XSignal iSignal = signalHandlerResult.sl[i]; + XUSCHF5OnSL(iSignal); + } + } + + // + // Handle TP Reports ... + int handledTPsCount = ArraySize(signalHandlerResult.tp); + if (handledTPsCount > 0) + { + // + for (int i = 0; i < handledTPsCount; i++) + { + // + XSignal iSignal = signalHandlerResult.tp[i]; + XUSCHF5OnTP(iSignal); + } + } + + // + // Handle RFs as TP Reports ... + int handledRFsCount = ArraySize(signalHandlerResult.rf); + if (handledRFsCount > 0) + { + // + for (int i = 0; i < handledRFsCount; i++) + { + // + XSignal iSignal = signalHandlerResult.rf[i]; + XUSCHF5OnRF(iSignal); + } + } +} + +// +// Handle Trades when OnTrade Event Hnadler Calls ... +void XUSCHF5SignalProviderHandleTrade() +{ + // + // Check Provider Enabled ... + if (!xUSCHF5MEnableProvider) + { + return; + } + + // + // Handle OnTrade Event ... + XOnTradeHandlerResult result = {}; + xUSCHF5Trader.HandleOnTradeEvent( + result); + + // + // Detected TP or SL ... + if (result.hasNewDeal) + { + // + XDeal last = xUSCHF5Trader.GetLastDeal(); + + // + if (last.reason == DEAL_REASON_SL) + { + xUSCHF5Reporter.AddTradeSLInReports(); + } + else if (last.reason == DEAL_REASON_TP) + { + xUSCHF5Reporter.AddTradeTPInReports(); + } + } +} + +// +// Handle Open Trades ... +void XUSCHF5HandleOpenTrades() +{ + // + // Check Can Trade ... + bool canTrade = xUSCHF5MAllowLongTrades || xUSCHF5MAllowShortTrades; + if (!canTrade) + { + return; + } + + // + // Check Max Open Trades ... + int openSignals = xUSCHF5Trader.Count(); + bool canOpenPositions = openSignals < xUSCHF5MaxAllowedTrades; + if (!canOpenPositions) + { + return; + } + + // + // Check Signals Exists ... + XProvidedSignal longSignalInfo; + XProvidedSignal shortSignalInfo; + bool hasLongSignal = XUSCHF5CanOpenLongTrade(longSignalInfo); + bool hasShortSignal = XUSCHF5CanOpenShortTrade(shortSignalInfo); + if (!hasLongSignal && !hasShortSignal) + { + return; + } + + // + // Update Reports ... + XUSCHF5UpdateReports(); + + // + xUSCHF5WaitUntilNextCandle = true; + + // + // Open Long Trades ... + if ( + // + hasLongSignal && + xUSCHF5MAllowLongTrades) + { + // + bool isOpened = XUSCHF5OpenLongPosition(longSignalInfo); + } + + // + // Open Short Trades ... + if ( + // + hasShortSignal && + xUSCHF5MAllowShortTrades) + { + // + bool isOpened = XUSCHF5OpenShortPosition(shortSignalInfo); + } +} + +// +// Handle Close Trades ... +void XUSCHF5HandleCloseTrades() +{ + // + // Force Close Long Trades ... + bool isClosedLongTrades = false; + bool canCloseLongTrades = XUSCHF5CanCloseLongTrade(); + if (xUSCHF5MAllowLongTrades && canCloseLongTrades) + { + // + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_LONG; + + // + XSignal closed[]; + xUSCHF5Trader.CloseSignals( + closed, + type); + + // + int closedTradesCount = ArraySize(closed); + isClosedLongTrades = closedTradesCount > 0; + if (isClosedLongTrades) + { + // + for (int i = 0; i < closedTradesCount; i++) + { + // + XSignal iSignal = closed[i]; + XUSCHF5OnFC(iSignal); + } + } + } + + // + // Force Close Short Trades ... + bool isClosedShortTrades = false; + bool canCloseShortTrades = XUSCHF5CanCloseShortTrade(); + if (xUSCHF5MAllowShortTrades && canCloseShortTrades) + { + // + ENUM_X_SIGNAL_TYPE type = X_SIGNAL_SHORT; + + // + XSignal closed[]; + xUSCHF5Trader.CloseSignals( + closed, + type); + + // + int closedTradesCount = ArraySize(closed); + isClosedShortTrades = closedTradesCount > 0; + if (isClosedShortTrades) + { + // + for (int i = 0; i < closedTradesCount; i++) + { + // + XSignal iSignal = closed[i]; + XUSCHF5OnFC(iSignal); + } + } + } +} + +// +// Open Long Position ... +bool XUSCHF5OpenLongPosition( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + // Calculate Required Data for Position ... + double entry = GetEntry(_Symbol, X_SIGNAL_LONG); + double sl = info.sl > 0 ? info.sl : 0; + // entry - (200 * _Point); + // info.sl > 0 ? info.sl : 0; + double tp = info.tp > 0 ? info.tp : entry + xUSCHF5MinReward; + double riskFreeRate = xUSCHF5RiskFreeRate; + double riskFreeStep = xUSCHF5RiskFreeStepInPips; + double volume = XUSCHF5CalculateVolume(ArraySize(info.signallers)); + + // + XSignal signal = {}; + signal = xUSCHF5Trader.GenerateSignal( + X_SIGNAL_LONG, + tp, + sl, + volume, + riskFreeStep, + riskFreeRate); + bool isValidSignal = IsValid( + signal, + xUSCHF5MagicNumber); + if (!isValidSignal) + { + return result; + } + + // + int signalsCount = xUSCHF5Trader.Count(); + bool isCross = signalsCount >= 1; + if (isCross) + { + // + // Handle Cross Signals ... + XUSCHF5HnadleCrossSignal(signal); + } + + // + // Retrieve Can Execute Signal or not ... + bool canExecuteSignal = + !isCross + // + || + // + ( + // + isCross && + xUSCHF5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING + // + ); + if (!canExecuteSignal) + { + return result; + } + + // + // Execute Signal ... + ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSCHF5Trader.ExecuteSignal( + signal, + false, // Ignore Number of Trades ... + true // Check Account Conditions ... + ); + result = executionResult == X_TRADER_SUCCEED_EXECUTION; + if (result) + { + // + // Update Reports ... + string providers[]; + ArrayCopy( + providers, + info.signallers + ); + + // + XSignal tSignal = xUSCHF5Trader.GetSignal(signal.ticket); + + // + XUSCHF5OnSignal( + tSignal, + providers); + } + else + { + XUSCHF5IssueSignalExecutionError(executionResult); + } + + // + return result; +} + +// +// Open Short Position ... +bool XUSCHF5OpenShortPosition( + XProvidedSignal &info // Retrieve Signal Additional Info on this Object +) +{ + // + bool result = false; + + // + // Calculate Required Data for Position ... + double entry = GetEntry(_Symbol, X_SIGNAL_SHORT); + double sl = info.sl > 0 ? info.sl : 0; + // entry + (200 * _Point); + // info.sl > 0 ? info.sl : 0; + double tp = info.tp > 0 ? info.tp : entry - xUSCHF5MinReward; + double riskFreeRate = xUSCHF5RiskFreeRate; + double riskFreeStep = xUSCHF5RiskFreeStepInPips; + double volume = XUSCHF5CalculateVolume(ArraySize(info.signallers)); + + // + XSignal signal = {}; + signal = xUSCHF5Trader.GenerateSignal( + X_SIGNAL_SHORT, + tp, + sl, + volume, + riskFreeStep, + riskFreeRate); + bool isValidSignal = IsValid( + signal, + xUSCHF5MagicNumber); + if (!isValidSignal) + { + return result; + } + + // + int signalsCount = xUSCHF5Trader.Count(); + bool isCross = signalsCount >= 1; + if (isCross) + { + // + // Handle Cross Signals ... + XUSCHF5HnadleCrossSignal(signal); + } + + // + // Retrieve Can Execute Signal or not ... + bool canExecuteSignal = + !isCross + // + || + // + ( + // + isCross && + xUSCHF5CrossSignalsMethod != X_CROSS_SIGNAL_DO_NOTHING + // + ); + if (!canExecuteSignal) + { + return result; + } + + // + // Execute Signal ... + ENUM_EXECUTION_SIGNAL_RESULT executionResult = xUSCHF5Trader.ExecuteSignal( + signal, + false, // Ignore Number of Trades ... + true // Check Account Conditions ... + ); + result = executionResult == X_TRADER_SUCCEED_EXECUTION; + if (result) + { + string providers[]; + ArrayCopy( + providers, + info.signallers + ); + + // + XSignal tSignal = xUSCHF5Trader.GetSignal(signal.ticket); + + // + XUSCHF5OnSignal( + tSignal, + providers); + } + else + { + XUSCHF5IssueSignalExecutionError(executionResult); + } + + // + return result; +} + +// +// Apply Cross Signal Actions ... +void XUSCHF5HnadleCrossSignal( + XSignal &signal // Specified Signal ... +) +{ + // + // Check Cross Signal Handling Enabled ... + if (xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DO_NOTHING) + { + return; + } + + // + // First We have to Change Cross Signals Comment ... + string comment = xUSCHF5Trader.GenerateSignalComment( + signal, + true); + + // + signal.comment = comment; + + // + // If Every thing is Regular, prevent any changes here ... + if (xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_REGULAR) + { + return; + } + + // + // Retrieve Max in Drawdown Signal ... + XSignal maxInDDSignal = xUSCHF5Trader.GetMaxInDrawdownSignal(); + + // + // Validate Signal ... + bool isValidSignal = + maxInDDSignal.ticket > 0 && + maxInDDSignal.symbol == signal.symbol && + IsValid(maxInDDSignal, xUSCHF5MagicNumber); + if (!isValidSignal) + { + return; + } + + // + double volume = signal.volume; + bool isDirectional = maxInDDSignal.type == signal.type; + + // + // Prevent any changes on Regular Conditions ... + bool isRegular = + isDirectional + ? ( + // + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR || + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_REGULAR_INDIRECTION_IMPORTANT + // + ) + : ( + // + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_INDIRECTION_REGULAR || + xUSCHF5CrossSignalsMethod == X_CROSS_SIGNAL_DIRECTION_IMPORTANT_INDIRECTION_REGULAR + // + ); + if (isRegular) + { + return; + } + + // + // Important Act needs to Multiply volume by 2 ... + volume *= 2; + + // + // Set Volume of signal ... + signal.volume = volume; +} + +// +// Calculate Usefull data ... +void XUSCHF5HandleCalculateDrawDownUp() +{ + // + XSignal signals[]; + xUSCHF5Trader.GetSignals(signals); + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + double profit = 0; + double volume = 0; + XCollector collector = {}; + double maxAllowedVolume = xUSCHF5VolumeManager.GetMaxAllowedVolume(); + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + profit += iSignal.profit; + + // + volume = + volume == 0 || + volume < iSignal.volume + ? iSignal.volume + : volume; + } + + // + if (profit < 0) + { + // + xUSCHF5MaxDrawDown = + xUSCHF5MaxDrawDown == 0 || + xUSCHF5MaxDrawDown > MathAbs(profit) + ? MathAbs(profit) + : xUSCHF5MaxDrawDown; + + // + // Update Buffers ... + datetime time = iTime(_Symbol, _Period, 0); + + // + // Calculate Max Allowed Drawdown ... + // + collector.time = time; + collector.volume = volume; + collector.maxDrawDown = xUSCHF5MaxDrawDown; + collector.maxAllowedVolume = maxAllowedVolume; + collector.minBalanceForOpenTrade = xUSCHF5Trader.GetMinBalanceForOpenTrades(); + } + else + { + // + xUSCHF5MaxDrawUp = + xUSCHF5MaxDrawUp == 0 || + xUSCHF5MaxDrawUp < profit + ? profit + : xUSCHF5MaxDrawUp; + } + + // + // Update Collector ... + xUSCHF5Collector.Add(collector); + + // + // Update Reports ... + xUSCHF5Reporter.UpdateMaxDrawUpInReports(xUSCHF5MaxDrawUp); + xUSCHF5Reporter.UpdateMaxDrawDownInReports(xUSCHF5MaxDrawDown); + xUSCHF5Reporter.UpdateMaxSameTimeTradesInReports(signalsCount); +} + +// +// START Event Handlers ... +// + +// +// Runs When a Signal Successfully Executed ... +void XUSCHF5OnSignal( + XSignal &signal, // Specified Signal + string &providers[] // Signal Providers +) +{ + // + // Issue Propper Alert ... + XUSCHF5IssueSignalExecutionAlert( + signal, + providers); + + // + // Add Signal To Supports on Guard ... + xUSCHF5Guard.AddSupport(signal); + + // + // Update Reports ... + xUSCHF5Reporter.AddSignalToReports( + signal, + providers); +} + +// +// Runs when a Position Got Take Profit ... +void XUSCHF5OnTP( + XSignal &signal // Specified Signal +) +{ + // + // Issue Propper Alert ... + XUSCHF5IssueTPAlert(signal); + + // + // Remove Signal From Guard Protector ... + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); + + // + // Update Reports ... + xUSCHF5Reporter.AddTradeTPInReports(); + XUSCHF5UpdateReports(); +} + +// +// Runs when a Position Got Stop Loss ... +void XUSCHF5OnSL( + XSignal &signal // Specified Signal +) +{ + // + // Issue Propper Alert ... + XUSCHF5IssueSLAlert(signal); + + // + // Remove Signal From Guard Protector ... + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); + + // + // Update Reports ... + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); +} + +// +// Runs when a Position Risk Free ... +void XUSCHF5OnRF( + XSignal &signal // Specified Signal +) +{ + // + // Issue Propper Alert ... + XUSCHF5IssueRFAlert(signal); + + // + // Remove Signal From Guard Protector ... + // since RiskFree Signals has SL ... + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); + + // + // Update Reports ... + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); +} + +// +// Runs when a Position Force Closed ... +void XUSCHF5OnFC( + XSignal &signal // Specified Signal +) +{ + // + // Issue Propper Alert ... + XUSCHF5IssueFCAlert(signal); + + // + // Remove Signal From Guard Protector ... + xUSCHF5Guard.Remove(signal.ticket); + xUSCHF5Guard.RemoveSupport(signal.ticket); + + // + // Update Reports ... + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); +} + +// +// Runs when a Position Guarded ... +void XUSCHF5OnGuard( + XSignal &signal, // Specified Signal + ENUM_X_GUARD_REASONS reason, // Reason of Guard Applied + string message, // Guard Returned Message + bool isStopOut = false // Specified StopOut Fired or not +) +{ + // + // Chekc StopOut ... + if (isStopOut) + { + // + LogMessage(message); + + // + xUSCHF5MEnableProvider = false; + } + + // + // Issue Propper Alert ... + XUSCHF5IssueGuardAlert(signal, reason, isStopOut); + + // + // Update Reports ... + xUSCHF5Reporter.AddTradeSLInReports(); + XUSCHF5UpdateReports(); +} + +// +// END Event Handlers ... +// + +// +// END Provided Functions ... +// + +// +// START Private Functions ... +// + +// +// START Volume Baseed Functions ... +// + +// +// Calculating Volume for Tradings ... +double XUSCHF5CalculateVolume( + double forceMultiplier = 0 // some times we get more than one signal at the same time, here we increase volume using this ... +) +{ + // + // Check Open Trades ... + int openSignals = xUSCHF5Trader.Count(); + + // + double result = xUSCHF5VolumeManager.CalculateVolume( + openSignals, + _Symbol); + + // + result *= forceMultiplier; + + // + // Normalize Volume ... + result = NormalizeVolume(result, _Symbol, 2); + + // + return result; +} + +// +// END Volume Baseed Functions ... +// + +// +// START Report/Collect and Guard Functions ... +// + +// +// Update Report Info ... +void XUSCHF5UpdateReports() +{ + // + double staticVolume = xUSCHF5VolumeManager.GetStaticVolume(); + string staticVolumeCalculationMethod = EnumToString(xUSCHF5StaticVolumeMethod); + double maxAllowedVolume = xUSCHF5VolumeManager.GetMaxAllowedVolume(); + double volumeIncreaseMultiplier = xUSCHF5VolumeManager.GetVolumeMultiplier(); + double balanceGowingToApplyMultiplier = xUSCHF5VolumeManager.GetIncreaseMultiplierBalance(); + + double balanceGrowingToIncreaseMaxAllowedVolume = xUSCHF5VolumeManager.GetIncreaseMaxAllowedVolumeBalance(); + + // + // Update Reports Volume Info ... + xUSCHF5Reporter.UpdateReportsVolumeInfo( + staticVolume, + staticVolumeCalculationMethod, + maxAllowedVolume, + volumeIncreaseMultiplier, + balanceGowingToApplyMultiplier, + balanceGrowingToIncreaseMaxAllowedVolume); + + // + // Calculate Max Allowed Drawdown ... + double minBalanceForTradeBasedOnBalance = xUSCHF5Trader.GetMinBalanceForOpenTrades(); + xUSCHF5Reporter.UpdateMinBalanceForOpenTradesInReports(minBalanceForTradeBasedOnBalance); +} + +// +// Reset XUSCHF5 Info Buffers ... +void XUSCHF5ResetCollectors() +{ + // + // Reset Calculations Buffers and Variables ... + xUSCHF5MaxDrawUp = 0; + xUSCHF5MaxDrawDown = 0; + + // + xUSCHF5Trader.Reset(); + xUSCHF5Reporter.Reset(); + xUSCHF5Collector.Reset(); + xUSCHF5VolumeManager.ResetForceVolumeMultiplier(); +} + +// +// END Report/Collect and Guard Functions ... +// + +// +// START Alert Functions ... +// + +// +// Send Alert ... +void XUSCHF5IssueAlert(string message) +{ + // + // Validate Args ... + if (StringLen(message) <= 0) + { + return; + } + + // + if (xUSCHF5EnableAlerts) + { + SendAlert(message); + } + else + { + LogMessage(message); + } +} + +// +// Send Take Profit Alert on Specific Signal ... +void XUSCHF5IssueTPAlert( + XSignal &signal // Specified Signal +) +{ + // + string message = ""; + + // + message = xUSCHF5Trader.GenerateSignalTPComment(signal); + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Stop Loss Alert on Specific Signal ... +void XUSCHF5IssueSLAlert( + XSignal &signal // Specified Signal +) +{ + // + string message = ""; + + // + message = xUSCHF5Trader.GenerateSignalSLComment(signal); + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Force Close Alert on Specific Signal ... +void XUSCHF5IssueFCAlert( + XSignal &signal // Specified Signal +) +{ + // + string message = ""; + + // + message = xUSCHF5Trader.GenerateSignalForceCloseComment(signal); + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Risk Free Alert on Specific Signal ... +void XUSCHF5IssueRFAlert( + XSignal &signal // Specified Signal +) +{ + // + string message = ""; + + // + message = xUSCHF5Trader.GenerateSignalRFComment(signal, 0); + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Guard Alert on Specific Signal ... +void XUSCHF5IssueGuardAlert( + XSignal &signal, // Specified Signal + ENUM_X_GUARD_REASONS reason, // Specified Guard Reason + bool isStopOut = false // Specified StopOut Fired or not +) +{ + // + string message = ""; + + // + message = xUSCHF5Guard.GenerateGuardedSignalComment( + signal, + reason); + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Initialization Succeed Alert ... +void XUSCHF5IssueInitializationSucceedAlert() +{ + // + string message = "Initializion of (" + XUSCHF5ProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ..."; + XUSCHF5IssueAlert(message); +} + +// +// Send De Initialization Succeed Alert ... +void XUSCHF5IssueDeinitializationSucceedAlert() +{ + // + string message = "De Initializion of (" + XUSCHF5ProviderName + " Provider" + ") Succeeded ..."; + XUSCHF5IssueAlert(message); +} + +// +// Send Signal Successfully Execution Alert ... +void XUSCHF5IssueSignalExecutionAlert( + XSignal &signal, // Specified Signal + string &providers[] // Signal Providers +) +{ + // + string message = xUSCHF5Trader.ToString(signal); + + // + string providersMsg = ToString(providers); + if (StringLen(providersMsg) > 0) + { + message += ", Providers: " + providersMsg; + } + + // + XUSCHF5IssueAlert(message); +} + +// +// Send Signal Execution Alert ... +void XUSCHF5IssueSignalExecutionError(int error) +{ + // + string message = GetSignalExecutionError(error); + if (StringLen(message) == 0) + { + return; + } + + // + XUSCHF5IssueAlert(message); +} + +// +// END Alert Functions ... +// + +// +// END Private Functions ... +// diff --git a/package.json b/package.json index 2db2c51b..d4bea8e4 100644 --- a/package.json +++ b/package.json @@ -98,6 +98,30 @@ "acd": "|----------|", "ace": "| /XAU5 |", "acf": "|----------|", + "bda": "|-----------|", + "bdb": "| XUSCHF5 |", + "bdc": "|-----------|", + "xUSCHF5CpExperts": "shx --silent mkdir -p ./Experts && shx --silent cp -r ./Projects/XUSCHF5/Experts/*.mq5 ./Experts || npm run true", + "xUSCHF5CpHelpers": "shx --silent mkdir -p ./Helpers && shx --silent cp -r ./Projects/XUSCHF5/Helpers/*.mq5 ./Helpers || npm run true", + "xUSCHF5CpClasses": "shx --silent mkdir -p ./Classes && shx --silent cp -r ./Projects/XUSCHF5/Classes/*.mq5 ./Classes || npm run true", + "xUSCHF5CpProviders": "shx --silent mkdir -p ./Providers && shx --silent cp -r ./Projects/XUSCHF5/Providers/*.mq5 ./Providers || npm run true", + "xUSCHF5CpLibraries": "shx --silent mkdir -p ./Libraries && shx --silent cp -r ./Projects/XUSCHF5/Libraries/*.mq5 ./Libraries || npm run true", + "xUSCHF5CpIndicators": "shx --silent mkdir -p ./Indicators && shx --silent cp -r ./Projects/XUSCHF5/Indicators/*.mq5 ./Indicators || npm run true", + "xUSCHF5UpSourceExperts": "shx --silent cp -r ./Experts/*.mq5 ./Projects/XUSCHF5/Experts || npm run true", + "xUSCHF5UpSourceHelpers": "shx --silent cp -r ./Helpers/*.mq5 ./Projects/XUSCHF5/Helpers || npm run true", + "xUSCHF5UpSourceClasses": "shx --silent cp -r ./Classes/*.mq5 ./Projects/XUSCHF5/Classes || npm run true", + "xUSCHF5UpSourceProviders": "shx --silent cp -r ./Providers/*.mq5 ./Projects/XUSCHF5/Providers || npm run true", + "xUSCHF5UpSourceLibraries": "shx --silent cp -r ./Libraries/*.mq5 ./Projects/XUSCHF5/Libraries || npm run true", + "xUSCHF5UpSourceIndicators": "shx --silent cp -r ./Indicators/*.mq5 ./Projects/XUSCHF5/Indicators || npm run true", + "xUSCHF5CpWorkspace": "npm run xUSCHF5CpExperts && npm run xUSCHF5CpProviders && npm run xUSCHF5CpIndicators && npm run xUSCHF5CpLibraries && npm run xUSCHF5CpHelpers && npm run xUSCHF5CpClasses", + "xUSCHF5UpSourceFromWorkspace": "npm run xUSCHF5UpSourceExperts && npm run xUSCHF5UpSourceProviders && npm run xUSCHF5UpSourceIndicators && npm run xUSCHF5UpSourceLibraries && npm run xUSCHF5UpSourceHelpers && npm run xUSCHF5UpSourceClasses", + "xUSCHF5PrepareWorkspace": "npm run backupWorkspace && npm run cleanupWorkspace && npm run xUSCHF5CpWorkspace", + "xUSCHF5ApplyFromWorkspace": "npm run backupWorkspace && npm run xUSCHF5UpSourceFromWorkspace", + "xUSCHF5Compile": "npm run compile XUSCHF5", + "xUSCHF5CompileAndPack": "npm run compile XUSCHF5 true", + "bdd": "|-----------|", + "bde": "| /XUSCHF5 |", + "bdf": "|-----------|", "ada": "|-----------|", "adb": "| XUSPY5 |", "adc": "|-----------|",