From 649cef249f9101dd6d91bdc3c8f3aa0c941d7f69 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 8 Jan 2026 11:41:25 +0330 Subject: [PATCH] remove backups ... --- Documents/BKP/TestRegresser.mq5 | 344 - Documents/BKP/XFIMA Signals/1.mq5 | 1195 --- Documents/BKP/XFIMA Signals/2.mq5 | 843 -- Documents/BKP/XFIMA Signals/3.mq5 | 496 - Documents/BKP/XFIMA Signals/Test.mq5 | 949 -- Documents/BKP/XFIMA Signals/signallers.mq5 | 1029 -- ...-saherelm.xfima.signaller.class copy 2.mq5 | 3727 -------- ...-saherelm.xfima.signaller.class copy 3.mq5 | 3780 -------- .../x-saherelm.xfima.signaller.class copy.mq5 | 3485 ------- .../x-saherelm.xfima.signaller.class.mq5 | 2621 ----- Documents/BKP/XKI_MTF_EA.mq5 | 547 -- Documents/BKP/XPullbackTradeer.mq5 | 708 -- Documents/BKP/XZoneEa.mq5 | 525 - .../ZigZagLinearRegression/TestRegresser.mq5 | 1108 --- .../BKP/ZigZagLinearRegression/ZigZag.mq5 | Bin 18826 -> 0 bytes .../ZigZagLinearRegression/ZigZagColor.mq5 | 288 - .../ZigZagLinearRegression/x-saherelm.xzg.mq5 | 1111 --- .../x-zigzag.analyser.ea.mq5 | 383 - Documents/BKP/backtester.temp.mq5 | 1484 --- Documents/BKP/signaller.xfima.drawing.tmp.mq5 | 208 - Documents/BKP/support and resistances.bkp.mq5 | 76 - Documents/BKP/test-xpv.ind.mq5 | 765 -- Documents/BKP/test.fima.conditions.mq5 | 295 - Documents/BKP/test.fima.ind.mq5 | 2523 ----- Documents/BKP/tmp-trade_symbol.info.mq5 | 977 -- Documents/BKP/tmp.backtester.codes.mq5 | 1389 --- Documents/BKP/tmp.codes.mq5 | 7167 -------------- Documents/BKP/tmp.poi.drawer.codes.mq5 | 379 - Documents/BKP/tmp.poi.mq5 | 7182 -------------- .../BKP/x-fima.pattern.detection.bkp.mq5 | 699 -- .../BKP/x-saherelm.x-cobject.class copy.mq5 | 3787 -------- Documents/BKP/x-saherelm.x-cobject.class.mq5 | 3478 ------- .../BKP/x-saherelm.x-market.pattern.class.mq5 | 4780 ---------- .../x-saherelm.x-poi.drawer.class copy.mq5 | 1195 --- .../BKP/x-saherelm.x-poi.drawer.class.mq5 | 4384 --------- .../BKP/x-saherelm.x-poi.extensions.lib.mq5 | 3807 -------- Documents/BKP/x-saherelm.x-poi.state.lib.mq5 | 4680 --------- Documents/BKP/x-saherelm.x121.xcatb.v1.mq5 | 5499 ----------- .../x-saherelm.x121.xki.signaller.class.mq5 | 1184 --- .../x-saherelm.xfima.backtester.ea copy.mq5 | 1899 ---- .../BKP/x-saherelm.xfima.backtester.ea.mq5 | 1053 --- .../BKP/x-saherelm.xfima.helper copy 2.mq5 | 8413 ----------------- .../BKP/x-saherelm.xfima.helper copy.mq5 | 3820 -------- Documents/BKP/x-saherelm.xfima.helper.mq5 | 4974 ---------- Documents/BKP/x-saherelm.xfima.lib copy 2.mq5 | 567 -- Documents/BKP/x-saherelm.xfima.lib copy.mq5 | 694 -- Documents/BKP/x-saherelm.xfima.lib.mq5 | 792 -- ...-saherelm.xfima.signaller.class copy 2.mq5 | 2249 ----- ...-saherelm.xfima.signaller.class copy 3.mq5 | 1657 ---- .../x-saherelm.xfima.signaller.class copy.mq5 | 1697 ---- .../BKP/x-saherelm.xfima.signaller.class.mq5 | 3804 -------- .../x-saherelm.xfima.x-poi.detector.class.mq5 | 495 - ...saherelm.xfima.x-poi.drawer.class copy.mq5 | 1775 ---- .../x-saherelm.xfima.x-poi.drawer.class.mq5 | 1949 ---- Documents/BKP/x-tmp-market-analyser.codes.mq5 | 826 -- Documents/BKP/xfima-zone-detector.bkp.mq5 | 1219 --- Documents/BKP/xfima.ind.tmp.mq5 | 2648 ------ Documents/BKP/xfima.poi.analysis.tmp.code.mq5 | 641 -- Documents/BKP/xfima.signaller.tmp.codes.mq5 | 511 - Documents/BKP/xfima.tmp.codes.poi.mq5 | 916 -- 60 files changed, 121676 deletions(-) delete mode 100644 Documents/BKP/TestRegresser.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/1.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/2.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/3.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/Test.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/signallers.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 2.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 3.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy.mq5 delete mode 100644 Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class.mq5 delete mode 100644 Documents/BKP/XKI_MTF_EA.mq5 delete mode 100644 Documents/BKP/XPullbackTradeer.mq5 delete mode 100644 Documents/BKP/XZoneEa.mq5 delete mode 100644 Documents/BKP/ZigZagLinearRegression/TestRegresser.mq5 delete mode 100644 Documents/BKP/ZigZagLinearRegression/ZigZag.mq5 delete mode 100644 Documents/BKP/ZigZagLinearRegression/ZigZagColor.mq5 delete mode 100644 Documents/BKP/ZigZagLinearRegression/x-saherelm.xzg.mq5 delete mode 100644 Documents/BKP/ZigZagLinearRegression/x-zigzag.analyser.ea.mq5 delete mode 100644 Documents/BKP/backtester.temp.mq5 delete mode 100644 Documents/BKP/signaller.xfima.drawing.tmp.mq5 delete mode 100644 Documents/BKP/support and resistances.bkp.mq5 delete mode 100644 Documents/BKP/test-xpv.ind.mq5 delete mode 100644 Documents/BKP/test.fima.conditions.mq5 delete mode 100644 Documents/BKP/test.fima.ind.mq5 delete mode 100644 Documents/BKP/tmp-trade_symbol.info.mq5 delete mode 100644 Documents/BKP/tmp.backtester.codes.mq5 delete mode 100644 Documents/BKP/tmp.codes.mq5 delete mode 100644 Documents/BKP/tmp.poi.drawer.codes.mq5 delete mode 100644 Documents/BKP/tmp.poi.mq5 delete mode 100644 Documents/BKP/x-fima.pattern.detection.bkp.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-cobject.class copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-cobject.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-market.pattern.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-poi.drawer.class copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-poi.drawer.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-poi.extensions.lib.mq5 delete mode 100644 Documents/BKP/x-saherelm.x-poi.state.lib.mq5 delete mode 100644 Documents/BKP/x-saherelm.x121.xcatb.v1.mq5 delete mode 100644 Documents/BKP/x-saherelm.x121.xki.signaller.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.backtester.ea copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.helper copy 2.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.helper copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.helper.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.lib copy 2.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.lib copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.lib.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.signaller.class copy 2.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.signaller.class copy 3.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.signaller.class copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.signaller.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.x-poi.detector.class.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.x-poi.drawer.class copy.mq5 delete mode 100644 Documents/BKP/x-saherelm.xfima.x-poi.drawer.class.mq5 delete mode 100644 Documents/BKP/x-tmp-market-analyser.codes.mq5 delete mode 100644 Documents/BKP/xfima-zone-detector.bkp.mq5 delete mode 100644 Documents/BKP/xfima.ind.tmp.mq5 delete mode 100644 Documents/BKP/xfima.poi.analysis.tmp.code.mq5 delete mode 100644 Documents/BKP/xfima.signaller.tmp.codes.mq5 delete mode 100644 Documents/BKP/xfima.tmp.codes.poi.mq5 diff --git a/Documents/BKP/TestRegresser.mq5 b/Documents/BKP/TestRegresser.mq5 deleted file mode 100644 index 5b14ef61..00000000 --- a/Documents/BKP/TestRegresser.mq5 +++ /dev/null @@ -1,344 +0,0 @@ -//+------------------------------------------------------------------+ -//| TestRegresser.mq5 | -//| SaherElm IT Center | -//| https://www.saherelm.ir | -//+------------------------------------------------------------------+ -#property copyright "SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" -#include - -// -// Inputs ... -input int mLoopbackLength = 200; -input ENUM_X_PRICE mPriceType = X_PRICE_HIGH; - -// -// Calculation ... -input group "Calculation"; -input int zigzagDepth = 12; // Depth -input int zigzagDeviation = 5; // Deviation -input int zigzagBackStep = 3; // Back Step - -// -// Variables ... - -// -int mZigZagHandler = INVALID_HANDLE; - -// -// double mSumX = 0; -// double mSumY = 0; -// double mSumXY = 0; -// double mSumX2 = 0; - -//+------------------------------------------------------------------+ -//| Expert initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - // - double xData[]; - double yData[]; - int xDataCount = CollectData( - xData, - yData // - ); - - // - // Initialize ZigZag Handler ... - mZigZagHandler = iCustom( - _Symbol, - _Period, - "ZigZagColor", - zigzagDepth, - zigzagDeviation, - zigzagBackStep // - ); - if (mZigZagHandler == INVALID_HANDLE) - { - Print("Error creating ZigZag handle"); - return (INIT_FAILED); - } - - // // - // for (int i = 0; i < mLoopbackLength; i++) - // { - // // - // double iY = yData[i]; - // double iX = xData[i]; - - // // - // mSumX += iX; - // mSumY += iY; - // mSumXY += (iX * iY); - // mSumX2 += (iX * iX); - // } - - // // - // for (int i = 0; i < mLoopbackLength; i++) - // { - // // - // double iY = GetAppliedPrice( - // _Symbol, - // _Period, - // i, - // mPriceType // - // ); - // double iX = i + 1; - - // // - // mSumX += iX; - // mSumY += iY; - // mSumXY += (iX * iY); - // mSumX2 += (iX * iX); - // } - - // - // int n = mLoopbackLength; - // double slope = (n * mSumXY - mSumX * mSumY) / (n * mSumX2 - mSumX * mSumX); - // double intercept = (mSumY - slope * mSumX) / n; - - // // - // double xData[]; - // double yData[]; - // int xDataCount = CollectData( - // xData, - // yData // - // ); - double _cSlope; - double _cIntercept; - int calculatedCount = CalculateSlopeandIntercept( - _cSlope, - _cIntercept, - xData, - yData // - ); - - // - datetime time1 = iTime(_Symbol, _Period, mLoopbackLength); - datetime time2 = iTime(_Symbol, _Period, 0); - - // // - // double price1 = (intercept + slope * mLoopbackLength); - // double price2 = (intercept + slope); - - // - double cPrice1 = PredictValue( - _cSlope, - _cIntercept, - time1 // - ); - double cPrice2 = PredictValue( - _cSlope, - _cIntercept, - time2 // - ); - - // - string name = "TrendLine"; - string cName = "cTrendLine"; - - // - // CChartObjectTrend *iTrend = new CChartObjectTrend(); - // bool isCreated = iTrend.Create( - // ChartID(), - // name, - // 0, - // time1, - // price1, - // time2, - // price2 // - // ); - // if (isCreated) - // { - // // - // // Styling Trend Line ... - // } - - // - CChartObjectTrend *iCTrend = new CChartObjectTrend(); - bool isCreated = iCTrend.Create( - ChartID(), - cName, - 0, - time1, - cPrice1, - time2, - cPrice2 // - ); - if (isCreated) - { - // - // Styling Trend Line ... - } - - // - return (INIT_SUCCEEDED); -} -//+------------------------------------------------------------------+ -//| Expert deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - //--- -} -//+------------------------------------------------------------------+ -//| Expert tick function | -//+------------------------------------------------------------------+ -void OnTick() -{ - //--- -} -//+------------------------------------------------------------------+ - -// -int CollectData( - double &xData[], - double &yData[], - int barIndex = 0 // -) -{ - // - int result = false; - - // - SpecifiedClean(xData); - SpecifiedClean(yData); - - // - barIndex = NormalizeInt(barIndex, 0); - - // - int start = barIndex; - int end = start + mLoopbackLength; - for (int i = start; i < end; i++) - { - // - double iY = GetAppliedPrice( - _Symbol, - _Period, - i // - ); - - // - datetime iTime = iTime( - _Symbol, - _Period, - i // - ); - double iX = i + 1; // (double)TimeToSeconds(iTime); - - // - Add( - iX, - xData // - ); - - // - Add( - iY, - yData // - ); - } - - // - result = ArraySize(xData); - - // - return result; -} - -// -int CalculateSlopeandIntercept( - double &_slope, - double &_intercept, - double &xData[], - double &yData[] // -) -{ - // - int result = 0; - - // - bool has = false; - - // - _slope = 0; - _intercept = 0; - - // - if (!HasChild(xData) || - !HasChild(yData)) - { - return result; - } - - // - double sumX = 0; - double sumY = 0; - double sumXY = 0; - double sumX2 = 0; - - // - double x = 0; - double y = 0; - int end = MathMin(ArraySize(xData), ArraySize(yData)); - for (int i = 0; i < end; i++) - { - // - double x = xData[i]; - double y = yData[i]; - - // - sumX += x; - sumY += y; - sumXY += x * y; - sumX2 += x * x; - } - - // - int n = end; - _slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); - _intercept = (sumY - _slope * sumX) / n; - - // - result = n; - - // - return result; -} - -// -double PredictValue( - double &_slope, - double &_intercept, - datetime forTime // -) -{ - // - double result = 0; - - // - if (!IsSpecifiedValid(forTime)) - { - return result; - } - - // - double forX = iBarShift( - _Symbol, - _Period, - forTime // - ); // (double)TimeToSeconds(forTime); - result = (_intercept + _slope * forX); - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/XFIMA Signals/1.mq5 b/Documents/BKP/XFIMA Signals/1.mq5 deleted file mode 100644 index 4dd62939..00000000 --- a/Documents/BKP/XFIMA Signals/1.mq5 +++ /dev/null @@ -1,1195 +0,0 @@ - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validator Flags ... - bool validateByATRZone = false; - bool validateByBarPatterns = false; - bool validateRejectedXFIMA = true; - bool validateByAffectedZone = false; - bool validateStartedPullback = true; - bool validateStartedPinnedBar = true; - bool validateByPinBarZoneTrend = false; - bool validateByDirectionalZones = false; - bool validateByDoubleBarPatterns = false; - bool validateByCycleMAsDirection = true; - bool validateByInDirectionalZones = false; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - XBoxZone atrBox; - XBoxZone mcPVZone; - XBoxZone lcPVZone; - XBoxZone hcPVZone; - double rejecteds[]; - XBoxZone supports[]; - XBoxZone pinBarZone; - XBoxZone pullbackZone; - XBoxZone affectedZone; - XBoxZone liquidityZone; - XBoxZone resistances[]; - XTrend pinBarZoneTrend; - bool isBullish = false; - bool isBearish = false; - XPatternAnalysis iPatterns; - XPatternAnalysis iPPatterns; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysis p3BarPatterns; - ENUM_X_BAR_PATTERN doublePatterns[]; - XPatternAnalysisConfig iPatternsConfig; - - // - // Reading Bars ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Reading Bar Patterns ... - iPatternsConfig.Default(); - iPatternsConfig.FullPattern(); - result = - result && - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p3Bar, - p3BarPatterns, - iPatternsConfig // - ); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } - - // - // Detect Support / Resistance / FVG Touches ... - - - // - // Prepare Zone ... - if (result) - { - // - string type = NULL; - datetime to = NULL; - datetime from = NULL; - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - ENUM_X_DIRECTION zDir = X_DIRECTION_NONE; - - // - zone.at = bar.time; - zone.symbol = bar.symbol; - zone.period = bar.period; - - // - if (pinBarZone.IsValid()) - { - // - upper = - !NotEmptyZero(upper) - ? pinBarZone.upper - : MathMax(upper, pinBarZone.upper); - - // - lower = - !NotEmptyZero(lower) - ? pinBarZone.lower - : MathMin(lower, pinBarZone.lower); - - // - to = bar.time; - from = !IsXValid(from) - ? pinBarZone.from - : MathMin(from, pinBarZone.from); - - // - zDir = pinBarZone.dir; - type = pinBarZone.type; - } - - // - if (pullbackZone.IsValid()) - { - // - upper = - !NotEmptyZero(upper) - ? pullbackZone.upper - : MathMax(upper, pullbackZone.upper); - - // - lower = - !NotEmptyZero(lower) - ? pullbackZone.lower - : MathMin(lower, pullbackZone.lower); - - // - from = !IsXValid(from) - ? pullbackZone.from - : MathMin(from, pullbackZone.from); - - // - if (!HasDirection(zDir)) - { - zDir = pullbackZone.dir; - } - - // - type = - !IsXValid(type) - ? pullbackZone.type - : type + "_" + pullbackZone.type; - } - - // - zone.to = to; - zone.dir = zDir; - zone.from = from; - zone.type = type; - zone.upper = upper; - zone.lower = lower; - - // - result = zone.IsValid(); - if (result) - { - // - int zoneLength = zone.FromIndex() - zone.ToIndex(); - double zoneLL = pBar.FindLowest(zoneLength, MODE_LOW); - double zoneHH = pBar.FindHighest(zoneLength, MODE_HIGH); - - // - if (zone.IsBullish()) - { - zone.lower = MathMin(zone.lower, zoneLL); - } - if (zone.IsBearish()) - { - zone.upper = MathMax(zone.upper, zoneHH); - } - } - - // - // Validating Zone by Shadows ... - if (result) - { - // - XOHCL iBar; - int idx = -1; - bool canContinue = true; - while (canContinue) - { - // - idx = zone.FromIndex() + 1; - canContinue = IsValidIndex(idx); - if (!canContinue) - { - break; - } - - // - iBar.Clean(); - canContinue = pBar.BarAt(idx, iBar); - if (!canContinue) - { - break; - } - - // - canContinue = isBullish - ? iBar.low > zone.lower - : iBar.high < zone.upper; - if (!canContinue) - { - break; - } - - // - zone.from = iBar.time; - } - } - - // - if (!result) - { - // - result = false; - isBullish = false; - isBearish = false; - dir = X_DIRECTION_NONE; - } - } - - // - // Validate Bu Liquidity ... - if (result) - { - // - // Detecting Liquidity ... - XOHCL liqBar; - int idx = zone.FromIndex() + 1; - result = IsValidIndex(idx); - result = result && - bar.BarAt(idx, liqBar); - if (result) - { - // - liquidityZone = zone; - - // - if (isBullish) - { - // - liquidityZone.upper = liquidityZone.lower; - liquidityZone.lower = liqBar.low; - } - else if (isBearish) - { - // - liquidityZone.lower = liquidityZone.upper; - liquidityZone.upper = liqBar.high; - } - } - - // - liqBar.Clean(); - result = liquidityZone.IsValid(); - if (!result) - { - // - zone.Clean(); - result = false; - isBullish = false; - isBearish = false; - dir = X_DIRECTION_NONE; - } - } - - // - // Validate By Affected Zone ... - if (result && validateByAffectedZone) - { - // - // Check pBar is Reject Zone ... - - // // - // // Prepare Zone ... - - // // - // XOHCL tmpBar; - // XBoxZone tmpZone; - - // // - // isBullish = - // isBullish && - // poiDetector.IsSupportTouched( - // p2Bar, - // tmpBar, - // tmpZone, - // 5, - // 21 // - // ); - // if (isBullish) - // { - // affectedZone = tmpZone; - // } - - // // - // isBearish = - // isBearish && - // poiDetector.IsResistanceTouched( - // p2Bar, - // tmpBar, - // tmpZone, - // 5, - // 21 // - // ); - // if (isBearish) - // { - // affectedZone = tmpZone; - // } - - // // - // tmpBar.Clean(); - // tmpZone.Clean(); - - // // - // result = isBullish || isBearish; - } - - // - if (result) - { - // - poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - poiDrawer.DrawZone(liquidityZone, structureDrawConfig.drawConfig); - DebugBreak(); - } - - // - zone.Clean(); - result = false; - isBullish = false; - isBearish = false; - dir = X_DIRECTION_NONE; - - // - // Looking For a Pin Bar in P2Bar ... - bool isP2BarIsPinBar = poiDetector.IsPinnedBar( - p2Bar, - dir, - 4, // Shadow Multiplier ... - 4, // Minimum Range Multiplier ... - true // Force Pin Bar Direction ... - ); - if (isP2BarIsPinBar) - { - // - isP2BarIsPinBar = ToBox( - p2Bar, - pinBarZone, - dir, - X_BAR_PATTERN_PINNED // - ); - if (isP2BarIsPinBar) - { - // - pinBarZone.to = bar.time; - - // - // Validate By PinBar Zone Trend ... - if (validateByPinBarZoneTrend) - { - // - isP2BarIsPinBar = poiDetector.HasBoundaryTrend( - pinBarZone, - pinBarZoneTrend, - false // - ); - - // - isP2BarIsPinBar = - isP2BarIsPinBar && - dir == pinBarZoneTrend.dir; - } - - // - // Validate PinBar Zone By XFIMA ... - if (validateRejectedXFIMA) - { - // - int rejectedsCount = poiDetector.IsRejectXFIMA(p2Bar, rejecteds, pinBarZone.dir); - isP2BarIsPinBar = IsValidSize(rejectedsCount); - } - } - } - bool isP2BarPinnedBullish = isP2BarIsPinBar && IsXBullish(dir); - bool isP2BarPinnedBearish = isP2BarIsPinBar && IsXBearish(dir); - - // - // Check P2Bar is Pullback Bar ... - bool isPBarIsPullBack = poiDetector.IsPullbackPattern( - pBar, - pullbackZone, - dir, - 2, // Pull back Length ... - false // Force Break Pullback ... - ); - bool isPBarPullbackBullish = isPBarIsPullBack && pullbackZone.IsBullish(); - bool isPBarPullbackBaerish = isPBarIsPullBack && pullbackZone.IsBearish(); - if (isPBarIsPullBack && validateRejectedXFIMA) - { - // - double iRejecteds[]; - int rejectedCounts = poiDetector.IsRejectXFIMA( - p2Bar, - iRejecteds, - dir, - X_PRICE_CLOSE, - X_PRICE_OPEN, - X_PRICE_OPEN, - X_PRICE_CLOSE, - false // - ); - isPBarIsPullBack = IsValidSize(rejectedCounts); - if (isPBarIsPullBack) - { - // - Copy( - iRejecteds, - rejecteds, - false // - ); - } - } - - // - isBullish = - isP2BarPinnedBullish || - isPBarPullbackBullish; - - // - isBearish = - isP2BarPinnedBearish || - isPBarPullbackBullish; - - // - result = isBullish || isBearish; - - // - // Validate Starter Pinned ... - if (result && validateStartedPinnedBar && !validateStartedPullback) - { - // - isBullish = - isBullish && - isP2BarPinnedBullish; - - // - isBearish = - isBearish && - isP2BarPinnedBearish; - - // - result = isBullish || isBearish; - } - - // - // Validate Starter Pullback ... - if (result && !validateStartedPinnedBar && validateStartedPullback) - { - // - isBullish = - isBullish && - isPBarPullbackBullish; - - // - isBearish = - isBearish && - isPBarPullbackBaerish; - - // - result = isBullish || isBearish; - } - - // - // Validate By ATR Zone ... - if (result && validateByATRZone) - { - // - // Checking ATR Box ... - bool hasATRBox = fimaParser.GetATRBox( - atrBox, - bar.Index() // - ); - bool hasATRBoxBullish = hasATRBox && atrBox.IsBullish(); - bool hasATRBoxBearish = hasATRBox && atrBox.IsBearish(); - - // - isBullish = - isBullish && - hasATRBoxBullish; - - // - isBearish = - isBearish && - hasATRBoxBearish; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Detect Directional Candlestic Patterns ... - if (result && validateByBarPatterns) - { - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isP2BarHasBullishPatterns = - (bar.close > p2Bar.low || - bar.open > p2Bar.low) && - ( - // - p2BarPatterns.IsPinned(X_DIRECTION_BULLISH) || - p2BarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - p2BarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - p2BarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - p2BarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isP3BarHasBullishPatterns = - (bar.close > p3Bar.low || - bar.open > p3Bar.low) && - ( - // - p3BarPatterns.IsPinned(X_DIRECTION_BULLISH) || - p3BarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - p3BarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - p3BarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - p3BarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - bool isP2BarHasBearishPatterns = - (bar.close < p2Bar.high || - bar.open < p2Bar.high) && - ( - // - p2BarPatterns.IsPinned(X_DIRECTION_BEARISH) || - p2BarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - p2BarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - p2BarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - p2BarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - bool isP3BarHasBearishPatterns = - (bar.close < p3Bar.high || - bar.open < p3Bar.high) && - ( - // - p3BarPatterns.IsPinned(X_DIRECTION_BEARISH) || - p3BarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - p3BarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - p3BarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - p3BarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - bool hasBullishPatterns = - isPBarHasBullishPatterns && - (isP2BarHasBullishPatterns || - isP3BarHasBullishPatterns); - - // - bool hasBearishPatterns = - isPBarHasBearishPatterns && - (isP2BarHasBearishPatterns || - isP3BarHasBearishPatterns); - - // - isBullish = - isBullish && - hasBullishPatterns; - - // - isBearish = - isBearish && - hasBearishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validating Market Direction ... - if (result && validateByCycleMAsDirection) - { - // - // Bullish ... - bool isLCBullish = fimaParser.IsLCMABullish(pBar.Index()); - bool isHCBullish = fimaParser.IsHCMABullish(pBar.Index()); - bool isLCHigherLow = - (fimaParser.IsLCHigherLow(pBar.Index()) || - fimaParser.IsLCHigherLow(p2Bar.Index()) || - fimaParser.IsLCHigherLow(p3Bar.Index())); - bool isCyclesBullish = - isLCBullish && - isHCBullish && - isLCHigherLow; - - // - // Bearish ... - bool isLCBearish = fimaParser.IsLCMABearish(pBar.Index()); - bool isHCBearish = fimaParser.IsHCMABearish(pBar.Index()); - bool isLCLowerHigh = - (fimaParser.IsLCLowerHigh(pBar.Index()) || - fimaParser.IsLCLowerHigh(p2Bar.Index()) || - fimaParser.IsLCLowerHigh(p3Bar.Index())); - bool isCyclesBearish = - isLCBearish && - isHCBearish && - isLCLowerHigh; - - // - isBullish = - isBullish && - isCyclesBullish; - - // - isBearish = - isBearish && - isCyclesBearish; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate By Double Bar Patterns ... - if (result && validateByDoubleBarPatterns) - { - // - GetCandlestickPatterns(doublePatterns); - bool hasDoublePatterns = poiDetector.HasDoublePatterns( - pBar, - dir, - iPatterns, - iPPatterns, - doublePatterns, - iPatternsConfig, - 5 // - ); - bool hasBullishDoublePatterns = hasDoublePatterns && IsXBullish(dir); - bool hasBearishDoublePatterns = hasDoublePatterns && IsXBearish(dir); - - // - isBullish = - isBullish && - hasBullishDoublePatterns; - - // - isBearish = - isBearish && - hasBearishDoublePatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate by Directional Zones ... - if (result && validateByDirectionalZones) - { - // - // Collecting Zones ... - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone tmpZone; - - // - // Support ... - bool hasSupport = pBarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = pBarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p2BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p3BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p3BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = HasChild(supports); - - // - // Resistance ... - bool hasResistance = pBarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = pBarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p2BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p3BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p3BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = HasChild(resistances); - - // - // Cleanup ... - tmpBar.Clean(); - tmpZone.Clean(); - tmpPivot.Clean(); - - // - // Validating ... - - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate by InDirectional Zones ... - if (result && validateByInDirectionalZones) - { - // - // Collecting Zones ... - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone tmpZone; - - // - // Supports ... - bool hasSupport = false; - if (!HasChild(supports)) - { - // - hasSupport = pBarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = pBarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p2BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p3BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p3BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = HasChild(supports); - } - hasSupport = HasChild(supports); - - // - // Resistances ... - bool hasResistance = false; - if (!HasChild(resistances)) - { - // - hasResistance = pBarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = pBarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p2BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p3BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p3BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = HasChild(resistances); - } - hasResistance = HasChild(resistances); - - // - // Cleanup ... - tmpBar.Clean(); - tmpZone.Clean(); - tmpPivot.Clean(); - - // - // Validate by Not InDirectional Exixsts ... - result = - (isBullish && !hasResistance) || - (isBearish && !hasSupport); - - // - // Validate InDirectional Distance by TP ... - if (!result) - { - // - // Calculate Requirements ... - double points = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, (isBullish ? X_DIRECTION_BULLISH : X_DIRECTION_BEARISH)); - double slAddition = slAdditionDistance <= 0 ? 0 : slAdditionDistance * points; - double sl = isBullish - ? pinBarZone.lower - slAddition - : pinBarZone.upper + slAddition; - double risk = MathAbs(entry - sl); - double tpReward = defaultSignalR2R * risk; - double tp = isBullish - ? entry + tpReward - : entry - tpReward; - - // - int idx = -1; - if (isBullish) - { - idx = GetYoungest(resistances); - } - else if (isBearish) - { - idx = GetYoungest(supports); - } - result = IsValidIndex(idx); - result = - result && - (isBullish - ? tp < resistances[idx].lower - : tp > supports[idx].upper); - } - - // - // Reset Flags ... - if (!result) - { - // - result = false; - isBullish = false; - isBearish = false; - dir = X_DIRECTION_NONE; - } - } - - // - // Detecting Direction ... - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - // Since Zone Prepared in Above Steps ... - // here we only Validate it ... - result = zone.IsValid(); - } - - // - // Draws ... - if (result) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - XPatternAnalysisDrawConfig iPatternsConfig = structureDrawConfig.barAnalysisDrawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - // PinBar Zone ... - if (pinBarZone.IsValid()) - { - poiDrawer.DrawZone(pinBarZone, iConfig); - } - - // - // Pullback Zone ... - if (pullbackZone.IsValid()) - { - poiDrawer.DrawZone(pullbackZone, iConfig); - } - - // - // PinBar Zone Trend ... - if (pinBarZoneTrend.IsValid()) - { - poiDrawer.DrawTrendLine(pinBarZoneTrend, iConfig); - } - - // - // Rejected Values ... - if (HasChild(rejecteds)) - { - // - XTrend iTrend; - bool has = false; - int count = ArraySize(rejecteds); - datetime toTime = zone.to + PeriodSeconds(zone.period); - datetime fromTime = zone.to - PeriodSeconds(zone.period); - for (int i = 0; i < count; i++) - { - // - // Initialize Trend ... - iTrend.Clean(); - has = iTrend.Init( - bar.symbol, - bar.period, - bar.time, - rejecteds[i], - fromTime, - rejecteds[i], - toTime // - ); - if (has) - { - poiDrawer.DrawTrendLine(iTrend, iConfig); - } - } - } - - // - // Draw Zone ... - if (zone.IsValid()) - { - // - iConfig.zonesStyle = STYLE_DASHDOT; - iConfig.bullishColor = clrYellow; - iConfig.bearishColor = clrDarkOrange; - - // - poiDrawer.DrawZone(zone, iConfig); - } - - // - // poiDrawer.DrawZone(mcPVZone, iConfig); - // poiDrawer.DrawZone(lcPVZone, iConfig); - // poiDrawer.DrawZone(hcPVZone, iConfig); - - // - // poiDrawer.DrawZone(pinBarZone, iConfig); - // poiDrawer.DrawZone(pullbackZone, iConfig); - // poiDrawer.DrawTrendLine(pinBarZoneTrend, iConfig); - - // - poiDrawer.DrawPatternAnalysis(pBarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p2BarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p3BarPatterns, iPatternsConfig); - - // - // if (hasATRBox) - // { - // poiDrawer.DrawZone(atrBox, iConfig); - // } - - // - // if (hasDoublePatterns) - // { - // // - // poiDrawer.DrawPatternAnalysis(iPatterns, iPatternsConfig); - // poiDrawer.DrawPatternAnalysis(iPPatterns, iPatternsConfig); - // } - - // - iConfig.Clean(); - iPatternsConfig.Clean(); - - // - DebugBreak(); - - // // - // result = false; - // isBullish = false; - // isBearish = false; - // zone.Clean(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(supports); - mcPVZone.Clean(); - lcPVZone.Clean(); - hcPVZone.Clean(); - XClean(rejecteds); - iPatterns.Clean(); - pinBarZone.Clean(); - iPPatterns.Clean(); - XClean(resistances); - affectedZone.Clean(); - pullbackZone.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - XClean(doublePatterns); - pinBarZoneTrend.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } diff --git a/Documents/BKP/XFIMA Signals/2.mq5 b/Documents/BKP/XFIMA Signals/2.mq5 deleted file mode 100644 index 7770102b..00000000 --- a/Documents/BKP/XFIMA Signals/2.mq5 +++ /dev/null @@ -1,843 +0,0 @@ - -// -// Order Flow ... - -// -bool drawOrderFlow; -XBoxZone orderFlow[]; -bool manageOrderFlow; -ENUM_X_DIRECTION orderFlowDir; - -// -bool HasOrderFlow() -{ - // - return HasChild(orderFlow) && - HasDirection(orderFlowDir); -} - -// -bool HasBullishOrderFlow() -{ - return HasOrderFlow() && - IsXBullish(orderFlowDir); -} - -// -bool HasBearishOrderFlow() -{ - return HasOrderFlow() && - IsXBearish(orderFlowDir); -} - -// -bool GetOrderFlowBoundary( - double &upper, - double &lower // -) -{ - // - bool result = false; - - // - // Prepare ... - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - - // - // Validate ... - result = HasOrderFlow(); - if (!result) - { - return result; - } - - // - int idx = -1; - - // - // Upper ... - idx = GetHighest(orderFlow); - if (IsValidIndex(idx)) - { - upper = orderFlow[idx].upper; - } - - // - // Lower ... - idx = GetLowest(orderFlow); - if (IsValidIndex(idx)) - { - lower = orderFlow[idx].lower; - } - - // - result = NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - // Cleanup ... - if (!result) - { - // - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - } - - // - return result; -} - -// -bool ValidateOrderFlow(XOHCL &bar) -{ - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasOrderFlow(); - if (!result) - { - return result; - } - - // - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - result = GetOrderFlowBoundary(upper, lower); - result = result && - HasBullishOrderFlow() - ? bar.low > lower - : bar.high < upper; - - // - return result; -} - -// -void DrawOrderFlow() -{ - // - if (!drawOrderFlow || !HasOrderFlow()) - { - return; - } - - // - poiDrawer.DrawZones(orderFlow, structureDrawConfig.drawConfig); -} - -// -void ManageOrderFlow(XOHCL &bar) -{ - // - // Validate Exists ... - if (HasOrderFlow()) - { - // - if (!ValidateOrderFlow(bar)) - { - // - // Invalidate OrderFlow ... - XClean(orderFlow); - orderFlowDir = X_DIRECTION_NONE; - } - } - - // - // Detect New ... - if (!HasOrderFlow()) - { - // - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - // patternConfig.Default(); - // patternConfig.supportAndResistanceLoopbackLength = 21; - // patternConfig.supportAndResistanceValidationLength = 7; - - // - poiDetector.HasOrderFlow( - bar, - orderFlowDir, - orderFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - } - - // - // Update Exists ... - if (HasOrderFlow()) - { - // - // Update to Times ... - UpdateToTime(orderFlow, TimeCurrent()); - - // - DrawOrderFlow(); - } -} - -// -// Zone ... - -// -XBoxZone support; -XBoxZone resistance; -bool drawZones; -bool drawSupport; -bool manageZones; -bool drawResistance; - -// -bool HasZones() -{ - return HasSupport() || - HasResistance(); -} - -// -bool HasSupport() -{ - return support.IsValid(); -} - -// -bool HasResistance() -{ - return resistance.IsValid(); -} - -// -bool ValidateZones(XOHCL &bar) -{ - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasZones(); - if (!result) - { - return result; - } - - // - // Support ... - bool hasSupport = HasSupport(); - if (hasSupport) - { - // - result = bar.close > support.lower && - !IsBreaked(support, X_PRICE_CLOSE); - if (!result) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.breakAt = bar.time; - support.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasResistance(); - if (hasResistance) - { - // - result = bar.close < resistance.upper && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!result) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.breakAt = bar.time; - resistance.Clean(); - } - } - - // - result = - (hasSupport && !HasSupport()) || - (hasResistance && !HasResistance()); - - // - return result; -} - -// -void DrawZones() -{ - // - if (!drawZones || !HasZones()) - { - return; - } - - // - if (drawSupport && HasSupport()) - { - poiDrawer.DrawZone(support, structureDrawConfig.drawConfig); - } - - // - if (drawResistance && HasResistance()) - { - poiDrawer.DrawZone(resistance, structureDrawConfig.drawConfig); - } -} - -// -void ManageZones(XOHCL &bar) -{ - // - // Validate Exists ... - if (HasZones()) - { - // - if (!ValidateZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(support.breakAt)) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.Clean(); - } - - // - // Resistance ... - if (IsXValid(resistance.breakAt)) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.Clean(); - } - } - } - - // - // Detect New ... - XOHCL tmpBar; - bool has = false; - - // - // Detect Support ... - if (!HasSupport()) - { - // - has = poiDetector.HasSupport( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToSupportBox(tmpBar, support, bar.time); - has = - has && - !IsBreaked(support, X_PRICE_CLOSE); - if (!has) - { - // - if (support.IsValid()) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - support.Clean(); - } - } - } - - // - // Detect Resistance ... - if (!HasResistance()) - { - // - has = poiDetector.HasResistance( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToResistanceBox(tmpBar, resistance, bar.time); - has = - has && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!has) - { - // - if (resistance.IsValid()) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - resistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasZones()) - { - // - if (HasSupport()) - { - // - support.to = bar.time; - support.type = "XFIMASup"; - } - - // - if (HasResistance()) - { - // - resistance.to = bar.time; - resistance.type = "XFIMARes"; - } - - // - DrawZones(); - } - - // - // Cleanup ... - tmpBar.Clean(); -} - -// -XBoxZone iSupport; -XBoxZone iResistance; -bool drawIZones; -bool drawISupport; -bool manageIZones; -bool drawIResistance; - -// -bool HasIZones() -{ - // - return HasISupport() || - HasIResistance(); -} - -// -bool HasISupport() -{ - return iSupport.IsValid(); -} - -// -bool HasIResistance() -{ - return iResistance.IsValid(); -} - -// -void DrawIZones() -{ - // - if (!drawIZones || !HasIZones()) - { - return; - } - - // - if (drawISupport && HasISupport()) - { - poiDrawer.DrawZone(iSupport, structureDrawConfig.drawConfig); - } - - // - if (drawIResistance && HasIResistance()) - { - poiDrawer.DrawZone(iResistance, structureDrawConfig.drawConfig); - } -} - -// -bool ValidateIZones(XOHCL &bar) -{ - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasIZones(); - if (!result) - { - return result; - } - - // - - // - // Support ... - bool hasSupport = HasISupport(); - if (hasSupport) - { - // - result = bar.close > iSupport.lower && - !IsBreaked(iSupport, X_PRICE_CLOSE); - if (!result) - { - // - iSupport.breakAt = bar.time; - iSupport.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasIResistance(); - if (hasResistance) - { - // - result = bar.close < iResistance.upper && - !IsBreaked(iResistance, X_PRICE_CLOSE); - if (!result) - { - // - iResistance.breakAt = bar.time; - iResistance.Clean(); - } - } - - // - result = - (hasSupport && !HasISupport()) || - (hasResistance && !HasIResistance()); - - // - return result; -} - -// -void ManageIZones(XOHCL &bar) -{ - // - // Validate Exists ... - if (HasIZones()) - { - // - if (!ValidateIZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(iSupport.breakAt)) - { - iSupport.Clean(); - } - - // - // Resistance ... - if (IsXValid(iResistance.breakAt)) - { - iResistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasIZones()) - { - // - if (HasISupport()) - { - // - iSupport.to = bar.time; - iSupport.type = "XFIMAISup"; - } - - // - if (HasIResistance()) - { - // - iResistance.to = bar.time; - iResistance.type = "XFIMAIRes"; - } - - // - DrawIZones(); - } -} - -// -// Trends ... - -// -XTrend scTrend; -XTrend mcTrend; -XTrend lcTrend; -XTrend hcTrend; - -// -bool drawTrends; -bool drawSCTrend; -bool drawMCTrend; -bool drawLCTrend; -bool drawHCTrend; -bool manageTrends; - -// -bool HasTrend() -{ - // - bool result = - HasSCTrend() || - HasMCTrend() || - HasLCTrend() || - HasHCTrend(); - - // - return result; -} - -// -bool HasSCTrend() -{ - return scTrend.IsValid() && - scTrend.HasTrend(); -} - -// -bool HasMCTrend() -{ - return mcTrend.IsValid() && - mcTrend.HasTrend(); -} - -// -bool HasLCTrend() -{ - return lcTrend.IsValid() && - lcTrend.HasTrend(); -} - -// -bool HasHCTrend() -{ - return hcTrend.IsValid() && - hcTrend.HasTrend(); -} - -// -void DrawTrends() -{ - // - if (!drawTrends || !HasTrend()) - { - return; - } - - // - // SC ... - if (drawSCTrend && HasSCTrend()) - { - poiDrawer.DrawTrendLine(scTrend, structureDrawConfig.drawConfig); - } - - // - // MC ... - if (drawMCTrend && HasMCTrend()) - { - poiDrawer.DrawTrendLine(mcTrend, structureDrawConfig.drawConfig); - } - - // - // LC ... - if (drawLCTrend && HasLCTrend()) - { - poiDrawer.DrawTrendLine(lcTrend, structureDrawConfig.drawConfig); - } - - // - // HC ... - if (drawHCTrend && HasHCTrend()) - { - poiDrawer.DrawTrendLine(hcTrend, structureDrawConfig.drawConfig); - } -} - -// -void ManageTrends(XOHCL &bar) -{ - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XTrend tmpTrend; - - // - // SC ... - tmpTrend.Clean(); - has = fimaParser.HasSCTrend(tmpTrend, bar.Index()); - if (has) - { - scTrend = tmpTrend; - } - - // - // MC ... - tmpTrend.Clean(); - has = fimaParser.HasMCTrend(tmpTrend, bar.Index()); - if (has) - { - mcTrend = tmpTrend; - } - - // - // LC ... - tmpTrend.Clean(); - has = fimaParser.HasLCTrend(tmpTrend, bar.Index()); - if (has) - { - lcTrend = tmpTrend; - } - - // - // HC ... - tmpTrend.Clean(); - has = fimaParser.HasHCTrend(tmpTrend, bar.Index()); - if (has) - { - hcTrend = tmpTrend; - } - - // - DrawTrends(); - - // - // Cleanup ... - tmpTrend.Clean(); -} - -// -void Manage(XOHCL &bar) -{ - // - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - has = bar.GetPreviousBar(pBar); - has = has && - pBar.GetPreviousBar(p2Bar); - has = has && - p2Bar.GetPreviousBar(p3Bar); - if (!has) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - ManageTrends(bar); - ManageZones(p2Bar); - ManageIZones(p2Bar); - ManageOrderFlow(p3Bar); - - // - // Cleanup ... - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); -} - -// -// Configure ... -drawZones = false; -drawIZones = false; -drawTrends = false; -drawSCTrend = false; -drawMCTrend = false; -drawLCTrend = false; -drawHCTrend = false; -drawSupport = false; -drawISupport = false; -drawOrderFlow = false; -drawResistance = false; -drawIResistance = false; - -// -manageZones = true; -manageIZones = true; -manageTrends = false; -manageOrderFlow = true; - -// -// Manage ... -Manage(iBar); diff --git a/Documents/BKP/XFIMA Signals/3.mq5 b/Documents/BKP/XFIMA Signals/3.mq5 deleted file mode 100644 index 25ddcd13..00000000 --- a/Documents/BKP/XFIMA Signals/3.mq5 +++ /dev/null @@ -1,496 +0,0 @@ - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validator Flags ... - bool validateByZones = true; - bool validateByPinBar = true; - bool validateByBarPatterns = true; - bool validateByCyclesTrend = true; - bool validateByMaFastSlowGrows = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysis p3BarPatterns; - XPatternAnalysisConfig iPatternsConfig; - - // - // Reading Bars ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Reading Bar Patterns ... - iPatternsConfig.Default(); - iPatternsConfig.FullPattern(); - result = - result && - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p3Bar, - p3BarPatterns, - iPatternsConfig // - ); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } - - // - // Detect a Cross of MAs ... - bool isFastCrossedOverSlow = fimaParser.IsMAFastCrossedOverSlow(p2Bar.Index()); - bool isFastCrossedUnderSlow = fimaParser.IsMAFastCrossedUnderSlow(p2Bar.Index()); - - // - isBullish = isFastCrossedOverSlow; - isBearish = isFastCrossedUnderSlow; - - // - result = isBullish || isBearish; - - // - // Validate Cross By Over/Under Last ... - if (result && validateByMaFastSlowGrows) - { - // - // Bullish ... - bool isFastOverLast = fimaParser.IsMAFastOverLast(pBar.Index()); - bool isSlowOverLast = fimaParser.IsMASlowOverLast(pBar.Index()); - bool isOverLast = isFastOverLast && isSlowOverLast; - - // - // Bearish ... - bool isFastUnderLast = fimaParser.IsMAFastUnderLast(pBar.Index()); - bool isSlowUnderLast = fimaParser.IsMASlowUnderLast(pBar.Index()); - bool isUnderLast = isFastUnderLast && isSlowUnderLast; - - // - isBullish = - isBullish && - isOverLast; - - // - isBearish = - isBearish && - isUnderLast; - - // - result = isBullish || isBearish; - } - - // - // Validate By Cycles Trend ... - if (result && validateByCyclesTrend) - { - // - // Reading Cycles Trend ... - - // - // Bullish ... - - // - bool isLCMABullish = fimaParser.IsLCMABullish(pBar.Index()); - bool isHCMABullish = fimaParser.IsHCMABullish(pBar.Index()); - - // - bool isLCMAOverLast = fimaParser.IsLCMAOverLast(pBar.Index()); - bool isHCMAOverLast = fimaParser.IsHCMAOverLast(pBar.Index()); - - // - bool isCyclesMABullish = isLCMABullish && isHCMABullish && isLCMAOverLast && isHCMAOverLast; - - // - // Bearish ... - - // - bool isLCMABearish = fimaParser.IsLCMABearish(pBar.Index()); - bool isHCMABearish = fimaParser.IsHCMABearish(pBar.Index()); - - // - bool isLCMAUnderLast = fimaParser.IsLCMAUnderLast(pBar.Index()); - bool isHCMAUnderLast = fimaParser.IsHCMAUnderLast(pBar.Index()); - - // - bool isCyclesMABearish = isLCMABearish && isHCMABearish && isLCMAUnderLast && isHCMAUnderLast; - - // - isBullish = - isBullish && - isCyclesMABullish; - - // - isBearish = - isBearish && - isCyclesMABearish; - - // - result = isBullish || isBearish; - } - - // - // Validate Has a PinBar ... - if (result && validateByPinBar) - { - // - bool isPBarIsPinBar = poiDetector.IsPinnedBar(pBar, dir); - bool isPBarIsPinBarBullish = isPBarIsPinBar && IsXBullish(dir); - bool isPBarIsPinBarBearish = isPBarIsPinBar && IsXBearish(dir); - - // - bool isP2BarIsPinBar = poiDetector.IsPinnedBar(p2Bar, dir); - bool isP2BarIsPinBarBullish = isP2BarIsPinBar && IsXBullish(dir); - bool isP2BarIsPinBarBearish = isP2BarIsPinBar && IsXBearish(dir); - - // - bool isBullishPin = isPBarIsPinBarBullish || isP2BarIsPinBarBullish; - bool isBearishPin = isPBarIsPinBarBearish || isP2BarIsPinBarBearish; - - // - isBullish = - isBullish && - isBullishPin; - - // - isBearish = - isBearish && - isBearishPin; - - // - result = isBullish || isBearish; - } - - // - // Validate By Bar Patterns ... - if (result && validateByBarPatterns) - { - // - int count = 0; - int bullishCount = 0; - int bearishCount = 0; - - // - count = pBarPatterns.Count(X_DIRECTION_BULLISH); - bullishCount += count; - - // - count = p2BarPatterns.Count(X_DIRECTION_BULLISH); - bullishCount += count; - - // - count = pBarPatterns.Count(X_DIRECTION_BEARISH); - bearishCount += count; - - // - count = p2BarPatterns.Count(X_DIRECTION_BEARISH); - bearishCount += count; - - // - bool hasBullishScore = IsValidSize(bullishCount) && - bullishCount > bearishCount; - - // - bool hasBearishScore = IsValidSize(bearishCount) && - bearishCount > bullishCount; - - // - // Reading Bar Patterns ... - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (pBarPatterns.HasPattern(X_BAR_PATTERN_FLAG, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_STAR, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_PINNED, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_RISING, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_ENGULFED, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_MOMENTUM, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_PIERCING, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_SIGNALKEY, X_DIRECTION_BULLISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_TRUE_GAPED, X_DIRECTION_BULLISH)); - bool isP2BarHasBullishPatterns = - (p2BarPatterns.HasPattern(X_BAR_PATTERN_FLAG, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_STAR, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_PINNED, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_RISING, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_ENGULFED, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_MOMENTUM, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_PIERCING, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_SIGNALKEY, X_DIRECTION_BULLISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_TRUE_GAPED, X_DIRECTION_BULLISH)); - bool hasBullishPatterns = isPBarHasBullishPatterns || isP2BarHasBullishPatterns; - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (pBarPatterns.HasPattern(X_BAR_PATTERN_FLAG, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_STAR, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_PINNED, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_RISING, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_ENGULFED, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_MOMENTUM, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_PIERCING, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_SIGNALKEY, X_DIRECTION_BEARISH) || - pBarPatterns.HasPattern(X_BAR_PATTERN_TRUE_GAPED, X_DIRECTION_BEARISH)); - bool isP2BarHasBearishPatterns = - (p2BarPatterns.HasPattern(X_BAR_PATTERN_FLAG, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_STAR, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_PINNED, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_RISING, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_ENGULFED, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_MOMENTUM, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_PIERCING, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_SIGNALKEY, X_DIRECTION_BEARISH) || - p2BarPatterns.HasPattern(X_BAR_PATTERN_TRUE_GAPED, X_DIRECTION_BEARISH)); - bool hasBearishPatterns = isPBarHasBearishPatterns || isP2BarHasBearishPatterns; - - // - isBullish = - isBullish && - hasBullishScore && - hasBullishPatterns; - - // - isBearish = - isBearish && - hasBearishScore && - hasBearishPatterns; - - // - result = isBullish || isBearish; - } - - // - // Validate By Zones ... - if (result && validateByZones) - { - // - XBoxZone zones[]; - int count = poiDetector.DetectZones( - pBar, - zones, - true, // Validate Zones ... - false, // OB ... - true, // FVG ... - true, // Supports ... - true, // Resistances ... - X_DIRECTION_NONE, // All Directions ... - X_SORT_BY_DATE, // Sort By ... - X_DIRECTION_BEARISH, // Sort Direction ... - 5, // Zones Loopback ... - 5, // Zones Validation ... - 100 // Loopback ... - ); - - // - bool has = IsValidSize(count); - if (has) - { - poiDrawer.DrawZones(zones, structureDrawConfig.drawConfig); - } - } - - // - if (result) - { - // - DebugBreak(); - - // - result = false; - isBullish = false; - isBearish = false; - } - - // - // Detecting Direction ... - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - // Since Zone Prepared in Above Steps ... - // here we only Validate it ... - result = zone.IsValid(); - } - - // - // Draws ... - if (result) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - XPatternAnalysisDrawConfig iPatternsConfig = structureDrawConfig.barAnalysisDrawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - // Draw Zone ... - if (zone.IsValid()) - { - // - iConfig.zonesStyle = STYLE_DASHDOT; - iConfig.bullishColor = clrYellow; - iConfig.bearishColor = clrDarkOrange; - - // - poiDrawer.DrawZone(zone, iConfig); - } - - // - // poiDrawer.DrawZone(mcPVZone, iConfig); - // poiDrawer.DrawZone(lcPVZone, iConfig); - // poiDrawer.DrawZone(hcPVZone, iConfig); - - // - // poiDrawer.DrawZone(pinBarZone, iConfig); - // poiDrawer.DrawZone(pullbackZone, iConfig); - // poiDrawer.DrawTrendLine(pinBarZoneTrend, iConfig); - - // - poiDrawer.DrawPatternAnalysis(pBarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p2BarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p3BarPatterns, iPatternsConfig); - - // - // if (hasATRBox) - // { - // poiDrawer.DrawZone(atrBox, iConfig); - // } - - // - // if (hasDoublePatterns) - // { - // // - // poiDrawer.DrawPatternAnalysis(iPatterns, iPatternsConfig); - // poiDrawer.DrawPatternAnalysis(iPPatterns, iPatternsConfig); - // } - - // - iConfig.Clean(); - iPatternsConfig.Clean(); - - // - DebugBreak(); - - // // - // result = false; - // isBullish = false; - // isBearish = false; - // zone.Clean(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } diff --git a/Documents/BKP/XFIMA Signals/Test.mq5 b/Documents/BKP/XFIMA Signals/Test.mq5 deleted file mode 100644 index e3433d9f..00000000 --- a/Documents/BKP/XFIMA Signals/Test.mq5 +++ /dev/null @@ -1,949 +0,0 @@ - -/** - * Check Bar Has Signal Based on Strategy 4 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateByBarPatterns = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - - // - bool isConsolidation = poiDetector.DetectXPVZone(zone, p2Bar.Index()); - - // - isBullish = - isConsolidation && - zone.IsBullish(); - - // - isBearish = - isConsolidation && - zone.IsBearish(); - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Force PBar Has Pattern ... - if (result && validateByBarPatterns) - { - // - // Analyse Bar Patterns ... - result = pBarPatterns.IsValid(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - result && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - result && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - if (result) - { - // - poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - DebugBreak(); - - // - result = false; - isBullish = false; - isBearish = false; - } - - // // - // // Validate based on Bars Patterns ... - // bool validateByBarPatterns = true; - // if (validateByBarPatterns) - // { - // // - // // Reading pBar Patterns ... - // XPatternAnalysis pBarAnalysis; - // poiDetector.AnalyseBarPatterns( - // pBar, - // pBarAnalysis, - // structureConfig.barsAnalysisConfig // - // ); - - // // - // // Bullish ... - // bool isPBarHasBullishPatterns = - // (bar.close > pBar.low || - // bar.open > pBar.low) && - // ( - // // - // pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - // pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - // pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - // pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - // pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // // - // ); - - // // - // // Bearish ... - // bool isPBarHasBearishPatterns = - // (bar.close < pBar.high || - // bar.open < pBar.high) && - // ( - // // - // pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - // pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - // pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - // pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - // pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // // - // ); - - // // - // isBullish = - // isBullish && - // isPBarHasBullishPatterns && - // !isPBarHasBearishPatterns; - - // // - // isBearish = - // isBearish && - // isPBarHasBearishPatterns && - // !isPBarHasBullishPatterns; - - // // - // // Summarize Result ... - // result = isBullish || - // isBearish; - // } - - // // - // // Checking PullBack ... - // bool validateByPullback = false; - // if (validateByPullback) - // { - // // - // XBoxZone pullback; - // ENUM_X_DIRECTION pullbackDir; - // bool isPullBack = result && - // poiDetector.IsPullbackPattern( - // pBar, - // pullback, - // pullbackDir, - // 2, - // false // Force Break ... - // ); - // bool isPullbackBullish = isPullBack && - // IsXBullish(pullbackDir); - // bool isPullbackBearish = isPullBack && - // IsXBearish(pullbackDir); - - // // - // isBullish = - // isBullish && - // isPullbackBullish; - - // // - // isBearish = - // isBearish && - // isPullbackBearish; - - // // - // // Summarize Result ... - // result = isBullish || - // isBearish; - // } - - // - // Validate ... - result = isBullish || - isBearish; - - // - // Prepare Zone ... - if (result) - { - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - - // - return result; -} - -// // -// bool isConsolidation = poiDetector.DetectXPVZone(zone, p2Bar.Index()); - -// // -// isBullish = -// isConsolidation && -// zone.IsBullish(); - -// // -// isBearish = -// isConsolidation && -// zone.IsBearish(); - -// // -// // Summarize Result ... -// result = isBullish || isBearish; - -// // -// // Force PBar Has Pattern ... -// if (result && validateByBarPatterns) -// { -// // -// // Analyse Bar Patterns ... -// result = pBarPatterns.IsValid(); - -// // -// // Bullish ... -// bool isPBarHasBullishPatterns = -// result && -// ( -// // -// pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || -// pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || -// pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || -// pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || -// pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) -// // -// ); - -// // -// // Bearish ... -// bool isPBarHasBearishPatterns = -// result && -// ( -// // -// pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || -// pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || -// pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || -// pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || -// pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) -// // -// ); - -// // -// isBullish = -// isBullish && -// isPBarHasBullishPatterns && -// !isPBarHasBearishPatterns; - -// // -// isBearish = -// isBearish && -// isPBarHasBearishPatterns && -// !isPBarHasBullishPatterns; - -// // -// // Summarize Result ... -// result = isBullish || isBearish; - -// // -// // Reset Flags ... -// if (!result) -// { -// // -// isBullish = false; -// isBearish = false; -// } -// } - -// // -// if (result) -// { -// // -// poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); -// poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); -// DebugBreak(); - -// // -// result = false; -// isBullish = false; -// isBearish = false; -// } - -// // -// // Validate based on Bars Patterns ... -// bool validateByBarPatterns = true; -// if (validateByBarPatterns) -// { -// // -// // Reading pBar Patterns ... -// XPatternAnalysis pBarAnalysis; -// poiDetector.AnalyseBarPatterns( -// pBar, -// pBarAnalysis, -// structureConfig.barsAnalysisConfig // -// ); - -// // -// // Bullish ... -// bool isPBarHasBullishPatterns = -// (bar.close > pBar.low || -// bar.open > pBar.low) && -// ( -// // -// pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || -// pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || -// pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || -// pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || -// pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) -// // -// ); - -// // -// // Bearish ... -// bool isPBarHasBearishPatterns = -// (bar.close < pBar.high || -// bar.open < pBar.high) && -// ( -// // -// pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || -// pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || -// pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || -// pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || -// pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) -// // -// ); - -// // -// isBullish = -// isBullish && -// isPBarHasBullishPatterns && -// !isPBarHasBearishPatterns; - -// // -// isBearish = -// isBearish && -// isPBarHasBearishPatterns && -// !isPBarHasBullishPatterns; - -// // -// // Summarize Result ... -// result = isBullish || -// isBearish; -// } - -// // -// // Checking PullBack ... -// bool validateByPullback = false; -// if (validateByPullback) -// { -// // -// XBoxZone pullback; -// ENUM_X_DIRECTION pullbackDir; -// bool isPullBack = result && -// poiDetector.IsPullbackPattern( -// pBar, -// pullback, -// pullbackDir, -// 2, -// false // Force Break ... -// ); -// bool isPullbackBullish = isPullBack && -// IsXBullish(pullbackDir); -// bool isPullbackBearish = isPullBack && -// IsXBearish(pullbackDir); - -// // -// isBullish = -// isBullish && -// isPullbackBullish; - -// // -// isBearish = -// isBearish && -// isPullbackBearish; - -// // -// // Summarize Result ... -// result = isBullish || -// isBearish; -// } - -/** - * Check Bar Has Signal Based on Strategy 4 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateByBarPatterns = false; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - patternConfig // - ); - - // - bool hasSupport = p2BarPatterns.IsValid() && - p2BarPatterns.IsSupport(); - bool hasResistance = p2BarPatterns.IsValid() && - p2BarPatterns.IsResistance(); - - // - isBullish = - hasSupport && - p2BarPatterns.Count(X_DIRECTION_BULLISH) >= 4; - - // - isBearish = - hasResistance && - p2BarPatterns.Count(X_DIRECTION_BEARISH) >= 4; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Extract Affected Zone ... - if (result) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone tmpZone; - - // - if (hasSupport) - { - // - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - isBullish = - isBullish && - hasSupport && - (IsActed(pBar, tmpZone) || - IsTested(pBar, tmpZone)); - } - - // - if (hasResistance) - { - // - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - isBearish = - isBearish && - hasResistance && - (IsActed(pBar, tmpZone) || - IsTested(pBar, tmpZone)); - } - - // - // Cleanup ... - tmpBar.Clean(); - tmpZone.Clean(); - tmpPivot.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate based on Bars Patterns ... - if (result && validateByBarPatterns) - { - // - // Bullish... - bool isPBarHasBullishPatterns = - pBarPatterns.IsValid() && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - pBarPatterns.IsValid() && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - if (result) - { - // - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - poiDrawer.DrawPatternAnalysis(p2BarPatterns, structureDrawConfig.barAnalysisDrawConfig); - DebugBreak(); - - // - result = false; - isBullish = false; - isBearish = false; - } - - // // - // bool isConsolidation = poiDetector.DetectXPVZone(zone, p2Bar.Index()); - - // // - // isBullish = - // isConsolidation && - // zone.IsBullish(); - - // // - // isBearish = - // isConsolidation && - // zone.IsBearish(); - - // // - // // Summarize Result ... - // result = isBullish || isBearish; - - // // - // // Force PBar Has Pattern ... - // if (result && validateByBarPatterns) - // { - // // - // // Analyse Bar Patterns ... - // result = pBarPatterns.IsValid(); - - // // - // // Bullish ... - // bool isPBarHasBullishPatterns = - // result && - // ( - // // - // pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - // pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - // pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - // pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - // pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // // - // ); - - // // - // // Bearish ... - // bool isPBarHasBearishPatterns = - // result && - // ( - // // - // pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - // pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - // pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - // pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - // pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // // - // ); - - // // - // isBullish = - // isBullish && - // isPBarHasBullishPatterns && - // !isPBarHasBearishPatterns; - - // // - // isBearish = - // isBearish && - // isPBarHasBearishPatterns && - // !isPBarHasBullishPatterns; - - // // - // // Summarize Result ... - // result = isBullish || isBearish; - - // // - // // Reset Flags ... - // if (!result) - // { - // // - // isBullish = false; - // isBearish = false; - // } - // } - - // // - // if (result) - // { - // // - // poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - // poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - // DebugBreak(); - - // // - // result = false; - // isBullish = false; - // isBearish = false; - // } - - // // - // // Checking PullBack ... - // bool validateByPullback = false; - // if (validateByPullback) - // { - // // - // XBoxZone pullback; - // ENUM_X_DIRECTION pullbackDir; - // bool isPullBack = result && - // poiDetector.IsPullbackPattern( - // pBar, - // pullback, - // pullbackDir, - // 2, - // false // Force Break ... - // ); - // bool isPullbackBullish = isPullBack && - // IsXBullish(pullbackDir); - // bool isPullbackBearish = isPullBack && - // IsXBearish(pullbackDir); - - // // - // isBullish = - // isBullish && - // isPullbackBullish; - - // // - // isBearish = - // isBearish && - // isPullbackBearish; - - // // - // // Summarize Result ... - // result = isBullish || - // isBearish; - // } - - // - // Validate ... - result = isBullish || - isBearish; - - // - // Prepare Zone ... - if (result) - { - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - patternConfig.Clean(); - p2BarPatterns.Clean(); - - // - return result; -} - -bool validateByPVChange = false; -bool validateByPVInside = false; - -// -// Validate By PV Inside ... -if (result && validateByPVInside) -{ - // - double pVale = fimaHelper.GetVale(pBar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - - // - bool isValePassed = pVale <= support.upper && - pVale >= support.upper && - fimaParser.IsValeSame(pBar.Index()); - - // - bool isPeakPassed = pPeak <= resistance.upper && - pPeak >= resistance.upper && - fimaParser.IsPeakSame(pBar.Index()); - - // - isBullish = - isBullish && - isValePassed; - - // - isBearish = - isBearish && - isPeakPassed; - - // - // Summarize Result ... - result = isBullish || isBearish; -} - -// -// Validate by PV Change ... -if (result && validateByPVChange) -{ - // - // bullish => p3, p2 vale under last ... - // bearish => p3, p2 peak over last ... - - // - bool isValePassed = - fimaParser.IsValeUnderLast(p2Bar.Index()) || - fimaParser.IsValeUnderLast(p3Bar.Index()); - - // - bool isPeakPassed = - fimaParser.IsPeakOverLast(p2Bar.Index()) || - fimaParser.IsPeakOverLast(p3Bar.Index()); - - // - isBullish = - isBullish && - isValePassed; - - // - isBearish = - isBearish && - isPeakPassed; - - // - // Summarize Result ... - result = isBullish || isBearish; -} diff --git a/Documents/BKP/XFIMA Signals/signallers.mq5 b/Documents/BKP/XFIMA Signals/signallers.mq5 deleted file mode 100644 index c2e811c8..00000000 --- a/Documents/BKP/XFIMA Signals/signallers.mq5 +++ /dev/null @@ -1,1029 +0,0 @@ - -// ======================================= -// Temp Signaller: -// ======================================= - -/** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool StrategyXHasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Do ... - - // - isBullish = - // - false - // - ; - - // - isBearish = - // - false - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Manage Stops ... - if (result) - { - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; -} - -// ======================================= -// Signallers: -// ======================================= - -/** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Reading Conditions ... - int pullBackStartBar = -1; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - zone, - dir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(dir); - bool isPullbackBearish = isPullBack && - IsXBearish(dir); - if (isPullBack) - { - pullBackStartBar = zone.FromIndex(); - } - - // - // Reading HK Bond ... - - // - double pHKBondUpper = fimaHelper.GetHKBondUpper(pBar.Index()); - double pHKBondLower = fimaHelper.GetHKBondLower(pBar.Index()); - int overHKBondUpperCount = fimaHelper.CountOverHKBondUpper(pullBackStartBar, X_PRICE_LOW); - int underHKBondLowerCount = fimaHelper.CountUnderHKBondLower(pullBackStartBar, X_PRICE_HIGH); - - // - // Reading PV Requirements ... - - // - int lastPeakOverLastIDX = -1; - int lastValeUnderLastIDX = -1; - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - int samePeaks = fimaHelper.CountSamePeaks(pBar.Index()); - int sameVales = fimaHelper.CountSameVales(pBar.Index()); - fimaHelper.FindLastPeakOverLast(lastPeakOverLastIDX, pBar.Index()); - fimaHelper.FindLastValeUnderLast(lastValeUnderLastIDX, pBar.Index()); - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - - // - // Try To Find Affected Zone ... - - // - // Collecting Zones ... - XBoxZone zones[]; - XBoxZone affectedZones[]; - XBoxZone affectedZonesBullish[]; - XBoxZone affectedZonesBearish[]; - int zonesCount = poiDetector.CollectZones( - pBar, - zones, // - 5, // Zones Loopback ... - 3 // Zones Validation Length ... - // Required Zones ... - // Loopback ... - ); - int affectedZonesCount = ExtractAffectedZones( - pBar, - zones, - affectedZones // - ); - int affectedZonesBullishCount = ExtractByDirection( - affectedZonesBullish, - affectedZones, - X_DIRECTION_BULLISH // - ); - int affectedZonesBearishCount = ExtractByDirection( - affectedZonesBearish, - affectedZones, - X_DIRECTION_BEARISH // - ); - - // - int insideBullishIDX = -1; - int insideBearishIDX = -1; - bool hasBullishInside = - pBar.IsBullish() && - HasInside( - insideBullishIDX, - pBar, - affectedZonesBullish // - ); - bool hasBearishInside = - pBar.IsBearish() && - HasInside( - insideBearishIDX, - pBar, - affectedZonesBearish // - ); - - // - // Do ... - - // - isBullish = - // - hasBullishInside && - isPullbackBullish && - isPBarHasBullishPatterns && - fimaHelper.IsSarBullish(pBar.Index()) && - (pVale >= affectedZonesBullish[insideBullishIDX].lower && - pVale <= affectedZonesBullish[insideBullishIDX].upper) - // - ; - - // - isBearish = - // - hasBearishInside && - isPullbackBearish && - isPBarHasBearishPatterns && - fimaHelper.IsSarBearish(pBar.Index()) && - (pPeak >= affectedZonesBearish[insideBearishIDX].lower && - pPeak <= affectedZonesBearish[insideBearishIDX].upper) - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - if (isBullish) - { - // - poiDrawer.DrawZone( - affectedZonesBullish[insideBullishIDX], - structureDrawConfig.drawConfig // - ); - } - else - { - // - poiDrawer.DrawZone( - affectedZonesBearish[insideBearishIDX], - structureDrawConfig.drawConfig // - ); - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - if (isBullish) - { - zone = affectedZonesBullish[insideBullishIDX]; - } - else - { - zone = affectedZonesBearish[insideBearishIDX]; - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - XClean(zones); - pBarAnalysis.Clean(); - XClean(affectedZones); - XClean(affectedZonesBullish); - XClean(affectedZonesBearish); - - // - return result; -} - -/** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - double peak = fimaHelper.GetPeak(bar.Index()); - double vale = fimaHelper.GetVale(bar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - double p2Peak = fimaHelper.GetPeak(p2Bar.Index()); - double p2Vale = fimaHelper.GetVale(p2Bar.Index()); - bool isPPeakOverLast = fimaHelper.IsPeakOverLast(pBar.Index()); - bool isPValeUnderLast = fimaHelper.IsValeUnderLast(pBar.Index()); - bool isP2PeakOverLast = fimaHelper.IsPeakOverLast(p2Bar.Index()); - bool isP2ValeUnderLast = fimaHelper.IsValeUnderLast(p2Bar.Index()); - bool isPeakOverLast = isPPeakOverLast || - isP2PeakOverLast; - bool isValeUnderLast = isPValeUnderLast || - isP2ValeUnderLast; - bool isP2ValeOverLast = pVale > p2Vale; - bool isP2PeakUnderLast = pPeak < p2Peak; - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - bool isFastOverLast = fimaHelper.GetMAFast(pBar.Index()) > fimaHelper.GetMAFast(p2Bar.Index()); - bool isFastUnderLast = fimaHelper.GetMAFast(pBar.Index()) < fimaHelper.GetMAFast(p2Bar.Index()); - - // - // Force P2Bar is Pin Bar ... - ENUM_X_DIRECTION p2Dir; - bool isP2BarPinned = poiDetector.IsPinnedBar( - p2Bar, - p2Dir // - ); - bool isP2BarBullishPinned = - isP2BarPinned && - IsXBullish(p2Dir); - bool isP2BarBearishPinned = - isP2BarPinned && - IsXBearish(p2Dir); - - // - // Do ... - - // - isBullish = - // - isFastOverLast && - isValeUnderLast && - !isP2PeakUnderLast && - isPBarCloseOverFast && - isP2BarBullishPinned && - isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - isPeakOverLast && - isFastUnderLast && - !isP2ValeOverLast && - isPBarCloseUnderFast && - isP2BarBearishPinned && - isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Manage Stops ... - if (result) - { - // - double entry = GetEntry(zone.symbol, zone.dir); - double riskSide = zone.IsBullish() ? zone.lower : zone.upper; - double risk = MathAbs(entry - riskSide); - - // - // Collecting Affected Zones ... - XBoxZone tmps[]; - XBoxZone zones[]; - XBoxZone actedZones[]; - XBoxZone insideZones[]; - XBoxZone breakedZones[]; - XBoxZone affectedZones[]; - - // - // Support and Resistances ... - poiDetector.CollectZones(bar, tmps); - Copy(tmps, zones, false); - - // - // OBS ... - poiDetector.CollectOBs(bar, tmps); - Copy(tmps, zones, false); - - // - // FVGs ... - poiDetector.CollectFVGs(bar, tmps); - Copy(tmps, zones, false); - - // - ExtractAffectedZones(bar, zones, affectedZones); - - // - // Acteds Zones ... - ExtractActeds(bar, actedZones, affectedZones); - - // - // Inside Zones ... - ExtractInsides(bar, insideZones, affectedZones); - - // - // Breaked Zones ... - ExtractBreakeds(bar, breakedZones, affectedZones); - - // - // Draw Affected Zones ... - if (HasChild(affectedZones)) - { - // - UpdateToTime(affectedZones, bar.time); - poiDrawer.DrawZones(affectedZones, structureDrawConfig.drawConfig); - } - - // - // Draw Acted Zones ... - // if (HasChild(actedZones)) - // { - // poiDrawer.DrawZones(actedZones, structureDrawConfig.drawConfig); - // } - - // - // Draw Inside Zones ... - // if (HasChild(insideZones)) - // { - // poiDrawer.DrawZones(insideZones, structureDrawConfig.drawConfig); - // } - - // // - // // Draw Breaked Zones ... - // if (HasChild(breakedZones)) - // { - // poiDrawer.DrawZones(breakedZones, structureDrawConfig.drawConfig); - // } - - // - // Cleanup ... - XClean(tmps); - XClean(zones); - XClean(actedZones); - XClean(insideZones); - XClean(breakedZones); - XClean(affectedZones); - } - - // - if (result) - { - // - zone.to = bar.time; - - // - poiDrawer.DrawZone( - zone, - structureDrawConfig.drawConfig // - ); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; -} - -/** - * Check Bar Has Signal Based on Strategy 4 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Do ... - // XFIMA Consolidation ... - - // - bool isConsolidation = fimaHelper.HasPVConsolidationZone( - zone, - pBar.Index(), - true, // Force PV Break ... - true // Force Has Sar Switch ... - ); - - // - isBullish = - isConsolidation && - zone.IsBullish(); - - // - isBearish = - isConsolidation && - zone.IsBearish(); - - // - // Validate based on Bars Patterns ... - bool validateByBarPatterns = true; - if (validateByBarPatterns) - { - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || - isBearish; - } - - // - // Checking PullBack ... - bool validateByPullback = false; - if (validateByPullback) - { - // - XBoxZone pullback; - ENUM_X_DIRECTION pullbackDir; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - pullback, - pullbackDir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(pullbackDir); - bool isPullbackBearish = isPullBack && - IsXBearish(pullbackDir); - - // - isBullish = - isBullish && - isPullbackBullish; - - // - isBearish = - isBearish && - isPullbackBearish; - - // - // Summarize Result ... - result = isBullish || - isBearish; - } - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = zone.dir; - zone.to = bar.time; - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - iConfig.zonesWidth = 3; - iConfig.bullishColor = clrYellow; - iConfig.bearishColor = clrDarkOrange; - poiDrawer.DrawZone(zone, iConfig); - Print("Consolidation"); - } - - // - // Prepare Zone ... - if (result) - { - // - // zone.Clean(); - // result = ToBox( - // p2Bar, - // zone, - // dir, - // X_BAR_PATTERN_PINNED // - // ); - - // - // Manage Stops ... - if (result) - { - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; -} diff --git a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 2.mq5 b/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 2.mq5 deleted file mode 100644 index 40fdf46d..00000000 --- a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 2.mq5 +++ /dev/null @@ -1,3727 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.parser.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - CArrayObj drawnObjects; // Drawing Objects Holder ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAHelperParser *fimaParser; // XFIMA Helper Parser ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - XFIMAMarketStructureConfig structureConfig; // XFIMA Market Structure Detector Config ... - XFIMAMarketStructureDrawerConfig structureDrawConfig; // XFIMA Market Structure Draw Config ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - // Instantiate XFIMA Helper Parser ... - fimaParser = new XCXFIMAHelperParser(fimaHelper); - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper, fimaParser); - - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - structureConfig.Clean(); - structureDrawConfig.Clean(); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure ... - drawLeg = false; - drawZones = false; - drawIZones = false; - drawTrends = false; - drawSCTrend = false; - drawMCTrend = false; - drawLCTrend = false; - drawHCTrend = false; - drawSupport = false; - drawISupport = false; - drawOrderFlow = false; - drawResistance = false; - drawIResistance = false; - - // - manageLegs = true; - manageZones = true; - manageIZones = true; - manageTrends = false; - manageOrderFlow = true; - - // - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Manage ... - Manage(iBar); - - // - // Strategy X ... - has = HasSignal( - iBar, - iZone, - iTargets, - iDir // - ); - - // - // Handle Resting Signals ... - has = HasDirection(iDir) && - iZone.IsValid(); - - // - // Prepare Signal ... - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, iDir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Signal ... - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - sl, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - } - - // - // Notify On Signal Event ... - if (has) - { - NotifySignalEventListeners(iSignal); - } - - // - // Cleanup ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - XClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - XClean(guards); - return result; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Requirements ... - XGuard iGuard; - bool has = false; - int samePeaks = 0; - int sameVales = 0; - double iValue = 0; - double points10 = 0; - double points50 = 0; - double points100 = 0; - int samePVValidation = 5; - bool isPeakOverLast = false; - bool isValeUnderLast = false; - - // - for (int i = 0; i < positionsCount; i++) - { - // - points10 = 10 * positions[i].GetPointsValue(); - points50 = 50 * positions[i].GetPointsValue(); - points100 = 100 * positions[i].GetPointsValue(); - - // - // Near to TP Guard ... - has = positions[i].profit > 0; - if (has) - { - // - // Has Same Peaks or Vales ... - samePeaks = fimaParser.CountSamePeaks(barIndex); - sameVales = fimaParser.CountSameVales(barIndex); - isPeakOverLast = (fimaParser.IsPeakOverLast(barIndex) || - fimaParser.IsPeakOverLast(barIndex + 1)); - isValeUnderLast = (fimaParser.IsValeUnderLast(barIndex) || - fimaParser.IsValeUnderLast(barIndex + 1)); - has = (positions[i].IsBullish() - ? ( - isPeakOverLast && - sameVales >= samePVValidation && - fimaHelper.GetVale(barIndex) > positions[i].sl) - : positions[i].IsBearish() - ? ( - isValeUnderLast && - samePeaks >= samePVValidation && - fimaHelper.GetPeak(barIndex) < positions[i].sl) - : false); - if (has) - { - // - iGuard.Clean(); - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.sl = positions[i].IsBullish() - ? fimaHelper.GetVale(barIndex) - points10 - : fimaHelper.GetPeak(barIndex) + points10; - iGuard.action = X_GUARD_ACTION_TRAIL_STOP; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - - // - // Remove TP if in Profit SL ... - iValue = (positions[i].IsBullish() ? positions[i].entry + points10 : positions[i].entry - points10); - has = - (positions[i].IsBullish() && HasResistance()) - ? (iGuard.sl >= iValue && - positions[i].tp < resistance.lower) - : (positions[i].IsBearish() && HasSupport()) - ? (iGuard.sl <= iValue && - positions[i].tp > support.upper) - : false; - if (has) - { - // - iGuard.Clean(); - iGuard.force = false; - iGuard.tp = positions[i].IsBullish() - ? resistance.lower - : support.upper; - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.action = X_GUARD_ACTION_TRAIL_TARGET; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - } - } - } - } - } - } - - // - result = ArraySize(guards); - - // - // Cleanup ... - iGuard.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - void Manage(XOHCL &bar) - { - // - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - has = bar.GetPreviousBar(pBar); - has = has && - pBar.GetPreviousBar(p2Bar); - has = has && - p2Bar.GetPreviousBar(p3Bar); - if (!has) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - ManageLeg(bar); - ManageTrends(bar); - ManageZones(p2Bar); - ManageIZones(p2Bar); - ManageOrderFlow(p3Bar); - - // - // Cleanup ... - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - // Private ... - private: - // - // Props ... - - // - // Leg ... - - XLeg leg; // Exists Leg ... - bool drawLeg; // Draw Leg ... - bool manageLegs; - - // - bool HasLeg() - { - return leg.IsValid(); - } - - // - bool ValidateLeg(XOHCL &bar) - { - // - bool result = false; - - // - result = HasLeg() && - bar.IsValid(); - if (!result) - { - return result; - } - - // - result = - leg.IsBullish() - ? bar.low > leg.lower - : leg.IsBearish() - ? bar.high < leg.upper - : false; - - // - return result; - } - - // - void DrawLeg() - { - // - if (!drawLeg) - { - return; - } - - // - if (!HasLeg()) - { - return; - } - - // - // Update to Times ... - leg.UpdateTimes(); - - // - // Draw Leg Box ... - XBoxZone legZone; - leg.ToBox(legZone); - if (legZone.IsValid()) - { - // - legZone.to = TimeCurrent(); - poiDrawer.DrawZone(legZone, structureDrawConfig.drawConfig); - } - - // - // Draw Legs Other Stufs ... - return; - - // - // FVGs ... - poiDrawer.DrawZones(leg.bullishFVGs, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.bearishFVGs, structureDrawConfig.drawConfig); - - // - // Support and Resistances ... - poiDrawer.DrawZones(leg.supports, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.resistances, structureDrawConfig.drawConfig); - - // - // Patterns ... - poiDrawer.DrawPatternAnalysises(leg.patterns, structureDrawConfig.barAnalysisDrawConfig); - } - - // - void ManageLeg(XOHCL &bar) - { - // - // Validate Exists ... - if (HasLeg()) - { - // - if (!ValidateLeg(bar)) - { - // - // Invalidate XLeg ... - leg.Clean(); - } - } - - // - // Detect New ... - if (!HasLeg()) - { - poiDetector.IsLegPattern(bar, leg); - } - - // - // Update Exists ... - if (HasLeg()) - { - // - // Update to Times ... - leg.UpdateTimes(); - - // - DrawLeg(); - } - } - - // - // Order Flow ... - - // - bool drawOrderFlow; - XBoxZone orderFlow[]; - bool manageOrderFlow; - ENUM_X_DIRECTION orderFlowDir; - - // - bool HasOrderFlow() - { - // - return HasChild(orderFlow) && - HasDirection(orderFlowDir); - } - - // - bool HasBullishOrderFlow() - { - return HasOrderFlow() && - IsXBullish(orderFlowDir); - } - - // - bool HasBearishOrderFlow() - { - return HasOrderFlow() && - IsXBearish(orderFlowDir); - } - - // - bool GetOrderFlowBoundary( - double &upper, - double &lower // - ) - { - // - bool result = false; - - // - // Prepare ... - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - - // - // Validate ... - result = HasOrderFlow(); - if (!result) - { - return result; - } - - // - int idx = -1; - - // - // Upper ... - idx = GetHighest(orderFlow); - if (IsValidIndex(idx)) - { - upper = orderFlow[idx].upper; - } - - // - // Lower ... - idx = GetLowest(orderFlow); - if (IsValidIndex(idx)) - { - lower = orderFlow[idx].lower; - } - - // - result = NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - // Cleanup ... - if (!result) - { - // - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - } - - // - return result; - } - - // - bool ValidateOrderFlow(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasOrderFlow(); - if (!result) - { - return result; - } - - // - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - result = GetOrderFlowBoundary(upper, lower); - result = result && - HasBullishOrderFlow() - ? bar.low > lower - : bar.high < upper; - - // - return result; - } - - // - void DrawOrderFlow() - { - // - if (!drawOrderFlow || !HasOrderFlow()) - { - return; - } - - // - poiDrawer.DrawZones(orderFlow, structureDrawConfig.drawConfig); - } - - // - void ManageOrderFlow(XOHCL &bar) - { - // - // Validate Exists ... - if (HasOrderFlow()) - { - // - if (!ValidateOrderFlow(bar)) - { - // - // Invalidate OrderFlow ... - XClean(orderFlow); - orderFlowDir = X_DIRECTION_NONE; - } - } - - // - // Detect New ... - if (!HasOrderFlow()) - { - // - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - // patternConfig.Default(); - // patternConfig.supportAndResistanceLoopbackLength = 21; - // patternConfig.supportAndResistanceValidationLength = 7; - - // - poiDetector.HasOrderFlow( - bar, - orderFlowDir, - orderFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - } - - // - // Update Exists ... - if (HasOrderFlow()) - { - // - // Update to Times ... - UpdateToTime(orderFlow, TimeCurrent()); - - // - DrawOrderFlow(); - } - } - - // - // Zone ... - - // - XBoxZone support; - XBoxZone resistance; - bool drawZones; - bool drawSupport; - bool manageZones; - bool drawResistance; - - // - bool HasZones() - { - return HasSupport() || - HasResistance(); - } - - // - bool HasSupport() - { - return support.IsValid(); - } - - // - bool HasResistance() - { - return resistance.IsValid(); - } - - // - bool ValidateZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasZones(); - if (!result) - { - return result; - } - - // - // Support ... - bool hasSupport = HasSupport(); - if (hasSupport) - { - // - result = bar.close > support.lower && - !IsBreaked(support, X_PRICE_CLOSE); - if (!result) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.breakAt = bar.time; - support.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasResistance(); - if (hasResistance) - { - // - result = bar.close < resistance.upper && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!result) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.breakAt = bar.time; - resistance.Clean(); - } - } - - // - result = - (hasSupport && !HasSupport()) || - (hasResistance && !HasResistance()); - - // - return result; - } - - // - void DrawZones() - { - // - if (!drawZones || !HasZones()) - { - return; - } - - // - if (drawSupport && HasSupport()) - { - poiDrawer.DrawZone(support, structureDrawConfig.drawConfig); - } - - // - if (drawResistance && HasResistance()) - { - poiDrawer.DrawZone(resistance, structureDrawConfig.drawConfig); - } - } - - // - void ManageZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasZones()) - { - // - if (!ValidateZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(support.breakAt)) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.Clean(); - } - - // - // Resistance ... - if (IsXValid(resistance.breakAt)) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.Clean(); - } - } - } - - // - // Detect New ... - XOHCL tmpBar; - bool has = false; - - // - // Detect Support ... - if (!HasSupport()) - { - // - has = poiDetector.HasSupport( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToSupportBox(tmpBar, support, bar.time); - has = - has && - !IsBreaked(support, X_PRICE_CLOSE); - if (!has) - { - // - if (support.IsValid()) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - support.Clean(); - } - } - } - - // - // Detect Resistance ... - if (!HasResistance()) - { - // - has = poiDetector.HasResistance( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToResistanceBox(tmpBar, resistance, bar.time); - has = - has && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!has) - { - // - if (resistance.IsValid()) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - resistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasZones()) - { - // - if (HasSupport()) - { - // - support.to = bar.time; - support.type = "XFIMASup"; - } - - // - if (HasResistance()) - { - // - resistance.to = bar.time; - resistance.type = "XFIMARes"; - } - - // - DrawZones(); - } - - // - // Cleanup ... - tmpBar.Clean(); - } - - // - XBoxZone iSupport; - XBoxZone iResistance; - bool drawIZones; - bool drawISupport; - bool manageIZones; - bool drawIResistance; - - // - bool HasIZones() - { - // - return HasISupport() || - HasIResistance(); - } - - // - bool HasISupport() - { - return iSupport.IsValid(); - } - - // - bool HasIResistance() - { - return iResistance.IsValid(); - } - - // - void DrawIZones() - { - // - if (!drawIZones || !HasIZones()) - { - return; - } - - // - if (drawISupport && HasISupport()) - { - poiDrawer.DrawZone(iSupport, structureDrawConfig.drawConfig); - } - - // - if (drawIResistance && HasIResistance()) - { - poiDrawer.DrawZone(iResistance, structureDrawConfig.drawConfig); - } - } - - // - bool ValidateIZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasIZones(); - if (!result) - { - return result; - } - - // - - // - // Support ... - bool hasSupport = HasISupport(); - if (hasSupport) - { - // - result = bar.close > iSupport.lower && - !IsBreaked(iSupport, X_PRICE_CLOSE); - if (!result) - { - // - iSupport.breakAt = bar.time; - iSupport.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasIResistance(); - if (hasResistance) - { - // - result = bar.close < iResistance.upper && - !IsBreaked(iResistance, X_PRICE_CLOSE); - if (!result) - { - // - iResistance.breakAt = bar.time; - iResistance.Clean(); - } - } - - // - result = - (hasSupport && !HasISupport()) || - (hasResistance && !HasIResistance()); - - // - return result; - } - - // - void ManageIZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasIZones()) - { - // - if (!ValidateIZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(iSupport.breakAt)) - { - iSupport.Clean(); - } - - // - // Resistance ... - if (IsXValid(iResistance.breakAt)) - { - iResistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasIZones()) - { - // - if (HasISupport()) - { - // - iSupport.to = bar.time; - iSupport.type = "XFIMAISup"; - } - - // - if (HasIResistance()) - { - // - iResistance.to = bar.time; - iResistance.type = "XFIMAIRes"; - } - - // - DrawIZones(); - } - } - - // - // Trends ... - - // - XTrend scTrend; - XTrend mcTrend; - XTrend lcTrend; - XTrend hcTrend; - - // - bool drawTrends; - bool drawSCTrend; - bool drawMCTrend; - bool drawLCTrend; - bool drawHCTrend; - bool manageTrends; - - // - bool HasTrend() - { - // - bool result = - HasSCTrend() || - HasMCTrend() || - HasLCTrend() || - HasHCTrend(); - - // - return result; - } - - // - bool HasSCTrend() - { - return scTrend.IsValid() && - scTrend.HasTrend(); - } - - // - bool HasMCTrend() - { - return mcTrend.IsValid() && - mcTrend.HasTrend(); - } - - // - bool HasLCTrend() - { - return lcTrend.IsValid() && - lcTrend.HasTrend(); - } - - // - bool HasHCTrend() - { - return hcTrend.IsValid() && - hcTrend.HasTrend(); - } - - // - void DrawTrends() - { - // - if (!drawTrends || !HasTrend()) - { - return; - } - - // - // SC ... - if (drawSCTrend && HasSCTrend()) - { - poiDrawer.DrawTrendLine(scTrend, structureDrawConfig.drawConfig); - } - - // - // MC ... - if (drawMCTrend && HasMCTrend()) - { - poiDrawer.DrawTrendLine(mcTrend, structureDrawConfig.drawConfig); - } - - // - // LC ... - if (drawLCTrend && HasLCTrend()) - { - poiDrawer.DrawTrendLine(lcTrend, structureDrawConfig.drawConfig); - } - - // - // HC ... - if (drawHCTrend && HasHCTrend()) - { - poiDrawer.DrawTrendLine(hcTrend, structureDrawConfig.drawConfig); - } - } - - // - void ManageTrends(XOHCL &bar) - { - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XTrend tmpTrend; - - // - // SC ... - tmpTrend.Clean(); - has = fimaParser.HasSCTrend(tmpTrend, bar.Index()); - if (has) - { - scTrend = tmpTrend; - } - - // - // MC ... - tmpTrend.Clean(); - has = fimaParser.HasMCTrend(tmpTrend, bar.Index()); - if (has) - { - mcTrend = tmpTrend; - } - - // - // LC ... - tmpTrend.Clean(); - has = fimaParser.HasLCTrend(tmpTrend, bar.Index()); - if (has) - { - lcTrend = tmpTrend; - } - - // - // HC ... - tmpTrend.Clean(); - has = fimaParser.HasHCTrend(tmpTrend, bar.Index()); - if (has) - { - hcTrend = tmpTrend; - } - - // - DrawTrends(); - - // - // Cleanup ... - tmpTrend.Clean(); - } - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Configuration Flags ... - - // - // Signaller Flags ... - bool useSignaller1 = true; - bool useSignaller2 = false; - bool useSignaller3 = false; - bool useSignaller4 = false; - - // - XBoxZone tmpZone; - string provider = NULL; - ENUM_X_DIRECTION tmpDir; - - // - bool signaller1HasSignal = false; - bool signaller2HasSignal = false; - bool signaller3HasSignal = false; - bool signaller4HasSignal = false; - - // - // Validator Flags ... - bool validateByOrderFlow = false; - - // - // Target Flags ... - bool hasPartialCloseOnTp1 = false; - - // - bool doRFOnEntryOnTP1 = false; - - // - // Draw Flags ... - bool draw = true; - bool drawZone = true; - bool drawMarketStructurePivots = false; - bool drawMarketStructureAnalysis = false; - bool drawMarketStructureOrderFlow = false; - XPOIDrawConfig iDrawConfig; - - // - drawLeg = false; - drawZones = false; - drawIZones = false; - drawTrends = false; - drawSCTrend = false; - drawMCTrend = false; - drawLCTrend = false; - drawHCTrend = false; - drawSupport = false; - drawISupport = false; - drawOrderFlow = false; - drawResistance = false; - drawIResistance = false; - - // - // Signal Checking ... - - // - // Analyse Market Strucutre ... - XFIMAMarketStructure marketStructure; - - // - // Signal Detection Flags ... - - // - // Signaller 1 ... - if (useSignaller1) - { - // - signaller1HasSignal = Strategy1HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller1HasSignal) - { - // - provider += "1"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 2 ... - if (useSignaller2) - { - // - signaller2HasSignal = Strategy2HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller2HasSignal) - { - // - provider += "2"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 3 ... - if (useSignaller3) - { - // - signaller3HasSignal = Strategy3HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller3HasSignal) - { - // - provider += "3"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 4 ... - if (useSignaller4) - { - // - signaller4HasSignal = Strategy4HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller4HasSignal) - { - // - provider += "4"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Summarize Signallers Result ... - result = signaller1HasSignal || - signaller2HasSignal || - signaller3HasSignal || - signaller4HasSignal; - - // - // Signal Validating ... - - // - // Validate Signals by Order Flow ... - if (result && validateByOrderFlow) - { - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - - // - bool isBullish = IsXBullish(dir) && - marketStructure.HasBullishOrderFlow(); - - // - bool isBearish = IsXBearish(dir) && - marketStructure.HasBearishOrderFlow(); - - // - // Summarizing result ... - result = isBullish || - isBearish; - } - - // - // Targets, Restrictions and Risk Management ... - if (result) - { - // - // Requirements ... - XTarget iTarget; - - // - // Checking Direction of Signal ... - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, dir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? zone.lower - slAddition - : zone.upper + slAddition; - - // - // Calculate Risk ... - double risk = MathAbs(entry - sl); - - // - // Calculate Reward ... - double reward = defaultSignalR2R * risk; - - // - // Calculate TP1 ... - double tp1 = isBullish - ? entry + risk - : entry - risk; - double tp2 = isBullish - ? entry + (2 * risk) - : entry - (2 * risk); - - // - // Calculate TP ... - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Check Max Allowed Risk ... - bool hasTooMuchRisk = maxAllowedRiskDistance <= 0 - ? false - : risk >= (maxAllowedRiskDistance * points); - if (hasTooMuchRisk) - { - // - // Clean Signal if Too much Risk ... - zone.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Common Targets ... - - // - // Partial Close on TP 1 ... - if (hasPartialCloseOnTp1) - { - // - iTarget.Clean(); - iTarget.target = tp1; - iTarget.actingDistance = 5; - iTarget.volumeMultiplier = 0.8; - iTarget.doRFOnEntry = doRFOnEntryOnTP1; - - // - AddRef(iTarget, targets); - } - - // - // Custom Signaller Targets ... - - // - // Restrictions Handling ... - if (risk > 0 && HasRestrictions()) - { - // - // Reset Restricitons if necessary ... - ResetRestrictions(); - - // - // Handle Custom Restrictions Senario ... - } - - // - // Ignore Targets ... - if (ignoreTargets) - { - XClean(targets); - } - - // - // Summarize Result ... - result = zone.IsValid() && - HasDirection(dir); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Draws ... - if (result && draw) - { - // - // Prepare Draw Config ... - iDrawConfig = structureDrawConfig.drawConfig; - iDrawConfig.zonesWidth = 3; - iDrawConfig.zonesStyle = STYLE_DASH; - iDrawConfig.bullishColor = clrYellow; - iDrawConfig.bearishColor = clrDarkOrange; - - // - // Draw Zone ... - if (drawZone) - { - poiDrawer.DrawZone(zone, iDrawConfig); - } - - // - // Draw Market Structure ... - - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - if (marketStructure.IsValid()) - { - // - // Order Flow ... - if (drawMarketStructureOrderFlow && marketStructure.HasOrderFlow()) - { - poiDrawer.DrawZones(marketStructure.orderFlow, iDrawConfig); - } - - // - // Pivots ... - if (drawMarketStructurePivots) - { - // - XPivot pivots[]; - int pivotsCount = marketStructure.CollectPivots( - pivots, - true // Contains Patterns ... - ); - if (IsValidSize(pivotsCount)) - { - poiDrawer.DrawPivots(pivots, iDrawConfig); - } - - // - XClean(pivots); - } - - // - // Analysis ... - if (drawMarketStructureAnalysis) - { - // - } - } - - // - // Other Drawing Materials ... - Print("Signaller Providers: ", provider); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - - // - // Cleanup ... - tmpZone.Clean(); - iDrawConfig.Clean(); - marketStructure.Clean(); - - // - return result; - } - - // - // Custom Signal Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - return result; - } - - // - // Reading Conditions ... - int pullBackStartBar = -1; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - zone, - dir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(dir); - bool isPullbackBearish = isPullBack && - IsXBearish(dir); - if (isPullBack) - { - pullBackStartBar = zone.FromIndex(); - } - - // - // Reading HK Band ... - - // - double pHKBandUpper = fimaHelper.GetHKBandUpper(pBar.Index()); - double pHKBandLower = fimaHelper.GetHKBandLower(pBar.Index()); - int overHKBandUpperCount = fimaParser.CountOverHKBandUpper(pullBackStartBar, X_PRICE_LOW); - int underHKBandLowerCount = fimaParser.CountUnderHKBandLower(pullBackStartBar, X_PRICE_HIGH); - - // - // Reading PV Requirements ... - - // - int lastPeakOverLastIDX = -1; - int lastValeUnderLastIDX = -1; - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - int samePeaks = fimaParser.CountSamePeaks(pBar.Index()); - int sameVales = fimaParser.CountSameVales(pBar.Index()); - fimaParser.FindLastPeakOverLast(lastPeakOverLastIDX, pBar.Index()); - fimaParser.FindLastValeUnderLast(lastValeUnderLastIDX, pBar.Index()); - - // - // Reading pBar Patterns ... - XOHCL _tmpBar; - XPivot _tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - XPatternAnalysis pBarPatterns; - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - structureConfig.barsAnalysisConfig // - ); - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - if (hasSupport) - { - hasSupport = pBarPatterns.GetSupport(_tmpBar, _tmpPivot, _support); - } - if (hasResistance) - { - hasResistance = pBarPatterns.GetResistance(_tmpBar, _tmpPivot, _resistance); - } - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - - // - // Try To Find Affected Zone ... - - // - // Collecting Zones ... - XBoxZone zones[]; - XBoxZone affectedZones[]; - XBoxZone affectedZonesBullish[]; - XBoxZone affectedZonesBearish[]; - int zonesCount = poiDetector.CollectZones( - pBar, - zones, // - 5, // Zones Loopback ... - 3 // Zones Validation Length ... - // Required Zones ... - // Loopback ... - ); - int affectedZonesCount = ExtractAffectedZones( - pBar, - zones, - affectedZones // - ); - int affectedZonesBullishCount = ExtractByDirection( - affectedZonesBullish, - affectedZones, - X_DIRECTION_BULLISH // - ); - int affectedZonesBearishCount = ExtractByDirection( - affectedZonesBearish, - affectedZones, - X_DIRECTION_BEARISH // - ); - - // - int insideBullishIDX = -1; - int insideBearishIDX = -1; - bool hasBullishInside = - pBar.IsBullish() && - HasInside( - insideBullishIDX, - pBar, - affectedZonesBullish // - ); - bool hasBearishInside = - pBar.IsBearish() && - HasInside( - insideBearishIDX, - pBar, - affectedZonesBearish // - ); - - // - // Detecting Boundary Trend ... - XTrend boundaryTrend; - double boundaryMin = fimaParser.GetBoundaryMin(pBar.Index()); - double boundaryMax = fimaParser.GetBoundaryMax(pBar.Index()); - bool hasBoundaryTrend = fimaParser.HasBoundaryTrend(boundaryTrend, pBar.Index()); - bool hasBoundaryBullishTrend = hasBoundaryTrend && boundaryTrend.IsBullish(); - bool hasBoundaryBearishTrend = hasBoundaryTrend && boundaryTrend.IsBearish(); - - // - // Do ... - - // - isBullish = - // - hasBullishInside && - isPullbackBullish && - isPBarHasBullishPatterns && - fimaParser.IsSARBullish(pBar.Index()) && - (pVale >= affectedZonesBullish[insideBullishIDX].lower && - pVale <= affectedZonesBullish[insideBullishIDX].upper) - // - ; - - // - isBearish = - // - hasBearishInside && - isPullbackBearish && - isPBarHasBearishPatterns && - fimaParser.IsSARBearish(pBar.Index()) && - (pPeak >= affectedZonesBearish[insideBearishIDX].lower && - pPeak <= affectedZonesBearish[insideBearishIDX].upper) - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - if (isBullish) - { - zone = affectedZonesBullish[insideBullishIDX]; - } - else - { - zone = affectedZonesBearish[insideBearishIDX]; - } - - // - result = zone.IsValid(); - - // - // Zone Validations ... - if (result) - { - // - if (boundaryTrend.IsValid()) - { - poiDrawer.DrawTrendLine(boundaryTrend, structureDrawConfig.drawConfig); - } - - // - poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - - // - if (hasSupport) - { - poiDrawer.DrawZone(_support, structureDrawConfig.drawConfig); - } - - // - if (hasResistance) - { - poiDrawer.DrawZone(_resistance, structureDrawConfig.drawConfig); - } - - // - if (HasChild(affectedZones)) - { - poiDrawer.DrawZones(affectedZones, structureDrawConfig.drawConfig); - } - - // - if (NotEmptyZero(boundaryMin)) - { - // - XTrend trend; - trend.Init( - pBar.symbol, - pBar.period, - bar.time, - boundaryMin, - pBar.BeforeOn(), - boundaryMin, - pBar.NextAt() // - ); - if (trend.IsValid()) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - poiDrawer.DrawTrendLine(trend, iConfig); - - // - iConfig.Clean(); - } - - // - trend.Clean(); - } - - // - if (NotEmptyZero(boundaryMax)) - { - // - XTrend trend; - trend.Init( - pBar.symbol, - pBar.period, - bar.time, - boundaryMax, - pBar.BeforeOn(), - boundaryMax, - pBar.NextAt() // - ); - if (trend.IsValid()) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - poiDrawer.DrawTrendLine(trend, iConfig); - - // - iConfig.Clean(); - } - - // - trend.Clean(); - } - - // - DebugBreak(); - } - - // - result = zone.IsValid(); - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - isBullish = false; - isBearish = false; - } - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - XClean(zones); - _tmpBar.Clean(); - _support.Clean(); - _tmpPivot.Clean(); - _resistance.Clean(); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - XClean(affectedZones); - XClean(affectedZonesBullish); - XClean(affectedZonesBearish); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 2 ... - * - * Strategy 2: - * =========== - * - Works Based On PBar Patterns Focused on PinBar ... - * - Looking for a Bar Directional Pattern Happens ... - * - Validate Fast Ma Over/Under Slow ... - * - Validate P2Peak/Vale doesnt Under or Over Last (InDirectional) ... - * - Validate P2Bar Has Directional Market Strucuture Zone (OB, FVG, Support/Resistance) ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarPatterns; - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - structureConfig.barsAnalysisConfig // - ); - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Check Boundary Trend ... - XTrend boundaryTrend; - bool hasBoundaryTrend = fimaParser.HasBoundaryTrend(boundaryTrend, pBar.Index()); - bool hasBoundaryBullishTrend = hasBoundaryTrend && boundaryTrend.IsBullish(); - bool hasBoundaryBearishTrend = hasBoundaryTrend && boundaryTrend.IsBearish(); - - // - // Check Bar Patterns ... - - // - // Bars Sequences ... - bool hasBullishSequence = p3Bar.IsBearish() && - pBar.IsBullish(); - bool hasBearishSequence = p3Bar.IsBullish() && - pBar.IsBearish(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - double peak = fimaHelper.GetPeak(bar.Index()); - double vale = fimaHelper.GetVale(bar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - double p2Peak = fimaHelper.GetPeak(p2Bar.Index()); - double p2Vale = fimaHelper.GetVale(p2Bar.Index()); - bool isPPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isPValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - bool isP2PeakOverLast = fimaParser.IsPeakOverLast(p2Bar.Index()); - bool isP2ValeUnderLast = fimaParser.IsValeUnderLast(p2Bar.Index()); - bool isPeakOverLast = isPPeakOverLast || - isP2PeakOverLast; - bool isValeUnderLast = isPValeUnderLast || - isP2ValeUnderLast; - bool isP2ValeOverLast = pVale > p2Vale; - bool isP2PeakUnderLast = pPeak < p2Peak; - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - bool isFastOverLast = fimaHelper.GetMAFast(pBar.Index()) > fimaHelper.GetMAFast(p2Bar.Index()); - bool isFastUnderLast = fimaHelper.GetMAFast(pBar.Index()) < fimaHelper.GetMAFast(p2Bar.Index()); - - // - // Force P2Bar is Pin Bar ... - ENUM_X_DIRECTION p2Dir; - bool isP2BarPinned = poiDetector.IsPinnedBar( - p2Bar, - p2Dir // - ); - bool isP2BarBullishPinned = - isP2BarPinned && - IsXBullish(p2Dir); - bool isP2BarBearishPinned = - isP2BarPinned && - IsXBearish(p2Dir); - - // - // Check Based On LC and HC MA State ... - - // - bool isLCMABullish = fimaParser.IsLCMABullish(pBar.Index()); - bool isHCMABullish = fimaParser.IsHCMABullish(pBar.Index()); - bool isCycleMABullish = isLCMABullish && isHCMABullish; - - // - bool isLCMABearish = fimaParser.IsLCMABearish(pBar.Index()); - bool isHCMABearish = fimaParser.IsHCMABearish(pBar.Index()); - bool isCycleMABearish = isLCMABearish && isHCMABearish; - - // - // Do ... - - // - isBullish = - // - hasSupport && - isFastOverLast && - isValeUnderLast && - isCycleMABullish && - hasBullishSequence && - !isP2PeakUnderLast && - isPBarCloseOverFast && - isP2BarBullishPinned && - hasBoundaryBullishTrend && - isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - hasResistance && - isPeakOverLast && - isFastUnderLast && - isCycleMABearish && - !isP2ValeOverLast && - hasBearishSequence && - isPBarCloseUnderFast && - isP2BarBearishPinned && - hasBoundaryBearishTrend && - isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Draws ... - if (result) - { - // - // XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - // iConfig.trendRayLeft = false; - // iConfig.trendRayRight = false; - // poiDrawer.DrawTrendLine(boundaryTrend, iConfig); - // poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - // iConfig.Clean(); - - // - // DebugBreak(); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * Strategy 3: - * =========== - * - Works Based On Breaked Support or Resistances ... - * - Looking for a Support or Resistance to Breaked ... - * - Validate Breaker Bar to Change Peak or Vale ... - * - Validate Bar Opposit Side of Breaker Bar's Shadow ... - * - Validate by Checking Market Strucutre to Has Directional Zone - * (Support for Resistance Break / Resistance for Support Break) ... - * - Validate Breaker Bar to Has Directional FVG ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - - // - bool validateByPVChanges = true; - bool validateByGapExists = true; - bool validateByBarShadows = true; - bool validateHasDirectionalZone = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XBoxZone _fvg; - XBoxZone _support; - XBoxZone _resistance; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - patternConfig // - ); - - // - // Price Must Break Support or Resistance ... - - // - // Extract Support and Resistance ... - bool hasSupport = p2BarPatterns.IsSupport(); - bool hasResistance = p2BarPatterns.IsResistance(); - if (hasSupport) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, _support); - tmpBar.Clean(); - tmpPivot.Clean(); - } - if (hasResistance) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - tmpBar.Clean(); - tmpPivot.Clean(); - } - - // - bool hasBreakedSupport = hasSupport && - pBar.close < _support.lower && - p2Bar.close > _support.lower; - bool hasBreakedResistance = hasResistance && - pBar.close > _resistance.upper && - p2Bar.close < _resistance.upper; - - // - isBullish = hasBreakedResistance; - isBearish = hasBreakedSupport; - - // - result = isBullish || isBearish; - - // - // Validate By PV Changed ... - // Breaker Bar must Change Peak or Value ... - if (result && validateByPVChanges) - { - // - bool isPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - - // - isBullish = - isBullish && - isPeakOverLast; - - // - isBearish = - isBearish && - isValeUnderLast; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate by Bar Shadows ... - // Breakre Bar Side Shadow must not Reached ... - if (result && validateByBarShadows) - { - // - isBullish = - isBullish && - pBar.low > p2Bar.low; - - // - isBearish = - isBearish && - pBar.high < p2Bar.high; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Has Directional Zone ... - if (result && validateHasDirectionalZone) - { - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate By Gap Exists ... - if (result && validateByGapExists) - { - // - ENUM_X_DIRECTION tmpDir; - bool hasFVG = poiDetector.HasFVG( - pBar, - tmpDir, - _fvg // - ); - - // - isBullish = - isBullish && - hasFVG && - IsXBullish(tmpDir); - - // - isBearish = - isBearish && - hasFVG && - IsXBearish(tmpDir); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Prepare Direction and Zone ... - if (result) - { - // - if (isBullish) - { - // - zone = _resistance; - zone.dir = Opposit(_resistance.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - if (isBearish) - { - // - zone = _support; - zone.dir = Opposit(_support.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - // Zone Validation Base ... - result = zone.IsValid(); - if (result) - { - // - // Validate By Trend of Zone ... - XTrend zoneTrend; - XTrend zoneToTrend; - - // - // Detecting Trends ... - result = poiDetector.HasBoundaryTrend(zone, zoneTrend, false); - result = result && - poiDetector.HasBoundaryTrend(zone, zoneToTrend, true); - - // - // Validate Trend ... - result = - result && - zone.dir == zoneTrend.dir && - zone.dir == zoneToTrend.dir; - - // - // Draw ... - if (result) - { - // // - // XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - // iConfig.trendRayLeft = false; - // iConfig.trendRayRight = false; - - // // - // poiDrawer.DrawTrendLine(zoneTrend, iConfig); - // poiDrawer.DrawTrendLine(zoneToTrend, iConfig); - - // // - // iConfig.Clean(); - } - - // - // Cleanup ... - zoneTrend.Clean(); - zoneToTrend.Clean(); - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - isBullish = false; - isBearish = false; - } - } - - // - result = zone.IsValid(); - } - - // - if (result) - { - // - if (_support.IsValid()) - { - poiDrawer.DrawZone(_support, structureDrawConfig.drawConfig); - } - - // - if (_resistance.IsValid()) - { - poiDrawer.DrawZone(_resistance, structureDrawConfig.drawConfig); - } - - // - if (pBarPatterns.IsValid()) - { - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - } - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - patternConfig.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * Strategy 4: - * =========== - * - Works Based on Order Flow ... - * - Looking for new and Fresh Order Flow ... - * - Validate Bar is Inside Order Flow ... - * - Validate Bar has Proper Pattern ... - * - Validate Bar Based on ATR Band in two Step: - * - Step 1: Bars is Inside ATR Band (Middle) ... - * - Step 2: Trigger Bars Close Price based on ATR Band ... - * - Validate Order Flow based on Market Structure Zone ... - * - Validate Trigger Bar based on InDirectional Market Structure Zones ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateBarInsideZone = true; - bool validateByBarPatterns = true; - bool validateByXFIMABoundary = true; - bool validateByBarInsideATRBand = true; - bool validateByBarBasedOnATRBand = true; - bool validateByXFIMABoundaryTrend = true; - bool validateMarketStructureHasDirectionalZone = true; - bool validateMarketStructureDirectionalZoneInsideOrderFlow = true; - bool validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - - // - // Detecting OrderFlow ... - XBoxZone oFlow[]; - bool hasOrderFlow = poiDetector.HasOrderFlow( - p3Bar, - dir, - oFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - - // - XTrend boundaryTrend; - XTrend boundaryZoneTrend; - - // - double atrBandUpper = EMPTY_VALUE; - double atrBandLower = EMPTY_VALUE; - double atrBandMiddle = EMPTY_VALUE; - - // - isBullish = hasOrderFlow && - IsXBullish(dir); - - // - isBearish = hasOrderFlow && - IsXBearish(dir); - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Force Price of p2Bar is Inside Order Flow ... - if (result && validateBarInsideZone) - { - // - double orderFlowUpper = 0; - double orderFlowLower = 0; - - // - int idx = -1; - idx = GetHighest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowUpper = oFlow[idx].upper; - } - idx = GetLowest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowLower = oFlow[idx].lower; - } - - // - result = NotEmptyZero(orderFlowUpper) && - NotEmptyZero(orderFlowLower) && - orderFlowUpper > orderFlowLower && - (isBullish - ? p2Bar.low < orderFlowUpper - : p2Bar.high > orderFlowLower); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Has Pattern ... - if (result && validateByBarPatterns) - { - // - // Analyse Bar Patterns ... - result = pBarPatterns.IsValid(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - result && - // (bar.close > pBar.low || - // bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - result && - // (bar.close < pBar.high || - // bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force P2Bar Place Checking based on ATR Band ... - if (result && validateByBarInsideATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(p2Bar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(p2Bar.Index()); - - // - atrBandMiddle = atrBandLower + ((atrBandUpper - atrBandLower) / 2); - - // - isBullish = - isBullish && - NotEmptyZero(atrBandMiddle) && - p2Bar.low < atrBandMiddle; - - // - isBearish = - isBearish && - NotEmptyZero(atrBandMiddle) && - p2Bar.high > atrBandMiddle; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Place Checking based on ATR Band ... - if (result && validateByBarBasedOnATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(pBar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(pBar.Index()); - - // - result = - NotEmptyZero(atrBandUpper) && - NotEmptyZero(atrBandLower) && - (isBullish - ? pBar.close > atrBandLower - : pBar.close < atrBandUpper); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // for Bullish has Support ... - // for Bearish has Resistance ... - if (result && validateMarketStructureHasDirectionalZone) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Validate Support and Resistance by Order Flow ... - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - // Check Market Strucutre Support and Resistance Validation ... - if (validateMarketStructureDirectionalZoneInsideOrderFlow) - { - // - hasSupport = - hasOFBox && - hasSupport && - ofZone.lower < _support.lower && - ofZone.upper > _support.upper; - - // - hasResistance = - hasOFBox && - hasResistance && - ofZone.lower < _resistance.lower && - ofZone.upper > _resistance.upper; - } - - // - // Validate Directional Support or Resistance Exists ... - - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Makret Structure Has Not Indirectional Zone ... - if (result && validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - bool hasIndirectionalZone = - (isBullish && hasResistance) || - (isBearish && hasSupport); - if (hasIndirectionalZone) - { - // - // Here we Have to Validate Zone Place ... - - // - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? oFlow[0].lower : oFlow[0].upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Bullish ... - if (isBullish && hasResistance) - { - hasResistance = _resistance.lower <= tp; - } - - // - // Bearish ... - if (isBearish && hasSupport) - { - hasSupport = _support.upper >= tp; - } - } - - // - isBullish = - isBullish && - !hasResistance; - - // - isBearish = - isBearish && - !hasSupport; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate ... - result = isBullish || isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone and do Zone Based Validations ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Refine Zone ... - zone.to = bar.time; - zone.upper = MathMax(zone.upper, atrBandMiddle); - zone.lower = MathMin(zone.lower, atrBandMiddle); - - // - // Validate by XFIMA Boundary ... - if (result && validateByXFIMABoundary) - { - // - // Try to Retrieve Boundary To Trend ... - result = poiDetector.HasBoundaryTrend( - zone, - boundaryTrend, - true // - ); - - // - // Try to Retrieve Boundary Zone Trend ... - result = - result && - poiDetector.HasBoundaryTrend( - zone, - boundaryZoneTrend, - false // - ); - - // - // Check and Validate Trend Direction ... - result = - result && - zone.dir == boundaryTrend.dir && - zone.dir == boundaryZoneTrend.dir; - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - result = false; - isBullish = false; - isBearish = false; - } - } - - // - // Manage Stops ... - if (result) - { - // - // Since Stop Management Changes Zones Edge(s) ... - // we do it here for Refining Zone ... - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - XTarget iTarget; - - // - // Calculate Requirements ... - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? zone.lower : zone.upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // High Risk Target is Used to Protect In Profit Positiions - // from Reversal Patterns ... - double highRiskR2r = (defaultSignalR2R / 5) * 4; - double highRiskReward = highRiskR2r * risk; - double highRiskTP = isBullish - ? entry + highRiskReward - : entry - highRiskReward; - iTarget.Clean(); - iTarget.actingDistance = 5; - iTarget.doRFOnEntry = true; - iTarget.target = highRiskTP; - iTarget.volumeMultiplier = 0.8; - // AddRef(iTarget, targets); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(oFlow); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - patternConfig.Clean(); - boundaryZoneTrend.Clean(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 3.mq5 b/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 3.mq5 deleted file mode 100644 index 6283fb86..00000000 --- a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy 3.mq5 +++ /dev/null @@ -1,3780 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.parser.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - CArrayObj drawnObjects; // Drawing Objects Holder ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAHelperParser *fimaParser; // XFIMA Helper Parser ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - XFIMAMarketStructureConfig structureConfig; // XFIMA Market Structure Detector Config ... - XFIMAMarketStructureDrawerConfig structureDrawConfig; // XFIMA Market Structure Draw Config ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - // Instantiate XFIMA Helper Parser ... - fimaParser = new XCXFIMAHelperParser(fimaHelper); - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper, fimaParser); - - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - structureConfig.Clean(); - structureDrawConfig.Clean(); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure ... - drawZones = false; - drawIZones = false; - drawTrends = false; - drawSCTrend = false; - drawMCTrend = false; - drawLCTrend = false; - drawHCTrend = false; - drawSupport = false; - drawISupport = false; - drawOrderFlow = false; - drawResistance = false; - drawIResistance = false; - - // - manageZones = true; - manageIZones = true; - manageTrends = false; - manageOrderFlow = true; - - // - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Manage ... - Manage(iBar); - - // - // Strategy X ... - has = HasSignal( - iBar, - iZone, - iTargets, - iDir // - ); - - // - // Handle Resting Signals ... - has = HasDirection(iDir) && - iZone.IsValid(); - - // - // Prepare Signal ... - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, iDir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Signal ... - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - sl, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - } - - // - // Notify On Signal Event ... - if (has) - { - NotifySignalEventListeners(iSignal); - } - - // - // Cleanup ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - XClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - XClean(guards); - return result; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Requirements ... - XGuard iGuard; - bool has = false; - int samePeaks = 0; - int sameVales = 0; - double iValue = 0; - double points10 = 0; - double points50 = 0; - double points100 = 0; - int samePVValidation = 5; - bool isPeakOverLast = false; - bool isValeUnderLast = false; - - // - for (int i = 0; i < positionsCount; i++) - { - // - points10 = 10 * positions[i].GetPointsValue(); - points50 = 50 * positions[i].GetPointsValue(); - points100 = 100 * positions[i].GetPointsValue(); - - // - // Near to TP Guard ... - has = positions[i].profit > 0; - if (has) - { - // - // Has Same Peaks or Vales ... - samePeaks = fimaParser.CountSamePeaks(barIndex); - sameVales = fimaParser.CountSameVales(barIndex); - isPeakOverLast = (fimaParser.IsPeakOverLast(barIndex) || - fimaParser.IsPeakOverLast(barIndex + 1)); - isValeUnderLast = (fimaParser.IsValeUnderLast(barIndex) || - fimaParser.IsValeUnderLast(barIndex + 1)); - has = (positions[i].IsBullish() - ? ( - isPeakOverLast && - sameVales >= samePVValidation && - fimaHelper.GetVale(barIndex) > positions[i].sl) - : positions[i].IsBearish() - ? ( - isValeUnderLast && - samePeaks >= samePVValidation && - fimaHelper.GetPeak(barIndex) < positions[i].sl) - : false); - if (has) - { - // - iGuard.Clean(); - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.sl = positions[i].IsBullish() - ? fimaHelper.GetVale(barIndex) - points10 - : fimaHelper.GetPeak(barIndex) + points10; - iGuard.action = X_GUARD_ACTION_TRAIL_STOP; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - - // - // Remove TP if in Profit SL ... - iValue = (positions[i].IsBullish() ? positions[i].entry + points10 : positions[i].entry - points10); - has = - (positions[i].IsBullish() && HasResistance()) - ? (iGuard.sl >= iValue && - positions[i].tp < resistance.lower) - : (positions[i].IsBearish() && HasSupport()) - ? (iGuard.sl <= iValue && - positions[i].tp > support.upper) - : false; - if (has) - { - // - iGuard.Clean(); - iGuard.force = false; - iGuard.tp = positions[i].IsBullish() - ? resistance.lower - : support.upper; - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.action = X_GUARD_ACTION_TRAIL_TARGET; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - } - } - } - } - } - } - - // - result = ArraySize(guards); - - // - // Cleanup ... - iGuard.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - void Manage(XOHCL &bar) - { - // - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - has = bar.GetPreviousBar(pBar); - has = has && - pBar.GetPreviousBar(p2Bar); - has = has && - p2Bar.GetPreviousBar(p3Bar); - if (!has) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - ManageTrends(bar); - ManageZones(p2Bar); - ManageIZones(p2Bar); - ManageOrderFlow(p3Bar); - - // - // Cleanup ... - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - // Private ... - private: - // - // Props ... - - // - // Order Flow ... - - // - bool drawOrderFlow; - XBoxZone orderFlow[]; - bool manageOrderFlow; - ENUM_X_DIRECTION orderFlowDir; - - // - bool HasOrderFlow() - { - // - return HasChild(orderFlow) && - HasDirection(orderFlowDir); - } - - // - bool HasBullishOrderFlow() - { - return HasOrderFlow() && - IsXBullish(orderFlowDir); - } - - // - bool HasBearishOrderFlow() - { - return HasOrderFlow() && - IsXBearish(orderFlowDir); - } - - // - bool GetOrderFlowBoundary( - double &upper, - double &lower // - ) - { - // - bool result = false; - - // - // Prepare ... - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - - // - // Validate ... - result = HasOrderFlow(); - if (!result) - { - return result; - } - - // - int idx = -1; - - // - // Upper ... - idx = GetHighest(orderFlow); - if (IsValidIndex(idx)) - { - upper = orderFlow[idx].upper; - } - - // - // Lower ... - idx = GetLowest(orderFlow); - if (IsValidIndex(idx)) - { - lower = orderFlow[idx].lower; - } - - // - result = NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - // Cleanup ... - if (!result) - { - // - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - } - - // - return result; - } - - // - bool ValidateOrderFlow(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasOrderFlow(); - if (!result) - { - return result; - } - - // - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - result = GetOrderFlowBoundary(upper, lower); - result = result && - HasBullishOrderFlow() - ? bar.low > lower - : bar.high < upper; - - // - return result; - } - - // - void DrawOrderFlow() - { - // - if (!drawOrderFlow || !HasOrderFlow()) - { - return; - } - - // - poiDrawer.DrawZones(orderFlow, structureDrawConfig.drawConfig); - } - - // - void ManageOrderFlow(XOHCL &bar) - { - // - // Validate Exists ... - if (HasOrderFlow()) - { - // - if (!ValidateOrderFlow(bar)) - { - // - // Invalidate OrderFlow ... - XClean(orderFlow); - orderFlowDir = X_DIRECTION_NONE; - } - } - - // - // Detect New ... - if (!HasOrderFlow()) - { - // - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - // patternConfig.Default(); - // patternConfig.supportAndResistanceLoopbackLength = 21; - // patternConfig.supportAndResistanceValidationLength = 7; - - // - poiDetector.HasOrderFlow( - bar, - orderFlowDir, - orderFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - } - - // - // Update Exists ... - if (HasOrderFlow()) - { - // - // Update to Times ... - UpdateToTime(orderFlow, TimeCurrent()); - - // - DrawOrderFlow(); - } - } - - // - // Zone ... - - // - XBoxZone support; - XBoxZone resistance; - bool drawZones; - bool drawSupport; - bool manageZones; - bool drawResistance; - - // - bool HasZones() - { - return HasSupport() || - HasResistance(); - } - - // - bool HasSupport() - { - return support.IsValid(); - } - - // - bool HasResistance() - { - return resistance.IsValid(); - } - - // - bool ValidateZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasZones(); - if (!result) - { - return result; - } - - // - // Support ... - bool hasSupport = HasSupport(); - if (hasSupport) - { - // - result = bar.close > support.lower && - !IsBreaked(support, X_PRICE_CLOSE); - if (!result) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.breakAt = bar.time; - support.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasResistance(); - if (hasResistance) - { - // - result = bar.close < resistance.upper && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!result) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.breakAt = bar.time; - resistance.Clean(); - } - } - - // - result = - (hasSupport && !HasSupport()) || - (hasResistance && !HasResistance()); - - // - return result; - } - - // - void DrawZones() - { - // - if (!drawZones || !HasZones()) - { - return; - } - - // - if (drawSupport && HasSupport()) - { - poiDrawer.DrawZone(support, structureDrawConfig.drawConfig); - } - - // - if (drawResistance && HasResistance()) - { - poiDrawer.DrawZone(resistance, structureDrawConfig.drawConfig); - } - } - - // - void ManageZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasZones()) - { - // - if (!ValidateZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(support.breakAt)) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.Clean(); - } - - // - // Resistance ... - if (IsXValid(resistance.breakAt)) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.Clean(); - } - } - } - - // - // Detect New ... - XOHCL tmpBar; - bool has = false; - - // - // Detect Support ... - if (!HasSupport()) - { - // - has = poiDetector.HasSupport( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToSupportBox(tmpBar, support, bar.time); - has = - has && - !IsBreaked(support, X_PRICE_CLOSE); - if (!has) - { - // - if (support.IsValid()) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - support.Clean(); - } - } - } - - // - // Detect Resistance ... - if (!HasResistance()) - { - // - has = poiDetector.HasResistance( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToResistanceBox(tmpBar, resistance, bar.time); - has = - has && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!has) - { - // - if (resistance.IsValid()) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - resistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasZones()) - { - // - if (HasSupport()) - { - // - support.to = bar.time; - support.type = "XFIMASup"; - } - - // - if (HasResistance()) - { - // - resistance.to = bar.time; - resistance.type = "XFIMARes"; - } - - // - DrawZones(); - } - - // - // Cleanup ... - tmpBar.Clean(); - } - - // - XBoxZone iSupport; - XBoxZone iResistance; - bool drawIZones; - bool drawISupport; - bool manageIZones; - bool drawIResistance; - - // - bool HasIZones() - { - // - return HasISupport() || - HasIResistance(); - } - - // - bool HasISupport() - { - return iSupport.IsValid(); - } - - // - bool HasIResistance() - { - return iResistance.IsValid(); - } - - // - void DrawIZones() - { - // - if (!drawIZones || !HasIZones()) - { - return; - } - - // - if (drawISupport && HasISupport()) - { - poiDrawer.DrawZone(iSupport, structureDrawConfig.drawConfig); - } - - // - if (drawIResistance && HasIResistance()) - { - poiDrawer.DrawZone(iResistance, structureDrawConfig.drawConfig); - } - } - - // - bool ValidateIZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasIZones(); - if (!result) - { - return result; - } - - // - - // - // Support ... - bool hasSupport = HasISupport(); - if (hasSupport) - { - // - result = bar.close > iSupport.lower && - !IsBreaked(iSupport, X_PRICE_CLOSE); - if (!result) - { - // - iSupport.breakAt = bar.time; - iSupport.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasIResistance(); - if (hasResistance) - { - // - result = bar.close < iResistance.upper && - !IsBreaked(iResistance, X_PRICE_CLOSE); - if (!result) - { - // - iResistance.breakAt = bar.time; - iResistance.Clean(); - } - } - - // - result = - (hasSupport && !HasISupport()) || - (hasResistance && !HasIResistance()); - - // - return result; - } - - // - void ManageIZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasIZones()) - { - // - if (!ValidateIZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(iSupport.breakAt)) - { - iSupport.Clean(); - } - - // - // Resistance ... - if (IsXValid(iResistance.breakAt)) - { - iResistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasIZones()) - { - // - if (HasISupport()) - { - // - iSupport.to = bar.time; - iSupport.type = "XFIMAISup"; - } - - // - if (HasIResistance()) - { - // - iResistance.to = bar.time; - iResistance.type = "XFIMAIRes"; - } - - // - DrawIZones(); - } - } - - // - // Trends ... - - // - XTrend scTrend; - XTrend mcTrend; - XTrend lcTrend; - XTrend hcTrend; - - // - bool drawTrends; - bool drawSCTrend; - bool drawMCTrend; - bool drawLCTrend; - bool drawHCTrend; - bool manageTrends; - - // - bool HasTrend() - { - // - bool result = - HasSCTrend() || - HasMCTrend() || - HasLCTrend() || - HasHCTrend(); - - // - return result; - } - - // - bool HasSCTrend() - { - return scTrend.IsValid() && - scTrend.HasTrend(); - } - - // - bool HasMCTrend() - { - return mcTrend.IsValid() && - mcTrend.HasTrend(); - } - - // - bool HasLCTrend() - { - return lcTrend.IsValid() && - lcTrend.HasTrend(); - } - - // - bool HasHCTrend() - { - return hcTrend.IsValid() && - hcTrend.HasTrend(); - } - - // - void DrawTrends() - { - // - if (!drawTrends || !HasTrend()) - { - return; - } - - // - // SC ... - if (drawSCTrend && HasSCTrend()) - { - poiDrawer.DrawTrendLine(scTrend, structureDrawConfig.drawConfig); - } - - // - // MC ... - if (drawMCTrend && HasMCTrend()) - { - poiDrawer.DrawTrendLine(mcTrend, structureDrawConfig.drawConfig); - } - - // - // LC ... - if (drawLCTrend && HasLCTrend()) - { - poiDrawer.DrawTrendLine(lcTrend, structureDrawConfig.drawConfig); - } - - // - // HC ... - if (drawHCTrend && HasHCTrend()) - { - poiDrawer.DrawTrendLine(hcTrend, structureDrawConfig.drawConfig); - } - } - - // - void ManageTrends(XOHCL &bar) - { - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XTrend tmpTrend; - - // - // SC ... - tmpTrend.Clean(); - has = fimaParser.HasSCTrend(tmpTrend, bar.Index()); - if (has) - { - scTrend = tmpTrend; - } - - // - // MC ... - tmpTrend.Clean(); - has = fimaParser.HasMCTrend(tmpTrend, bar.Index()); - if (has) - { - mcTrend = tmpTrend; - } - - // - // LC ... - tmpTrend.Clean(); - has = fimaParser.HasLCTrend(tmpTrend, bar.Index()); - if (has) - { - lcTrend = tmpTrend; - } - - // - // HC ... - tmpTrend.Clean(); - has = fimaParser.HasHCTrend(tmpTrend, bar.Index()); - if (has) - { - hcTrend = tmpTrend; - } - - // - DrawTrends(); - - // - // Cleanup ... - tmpTrend.Clean(); - } - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Configuration Flags ... - - // - // Signaller Flags ... - bool useSignaller1 = true; - bool useSignaller2 = false; - bool useSignaller3 = false; - bool useSignaller4 = false; - - // - XBoxZone tmpZone; - string provider = NULL; - ENUM_X_DIRECTION tmpDir; - - // - bool signaller1HasSignal = false; - bool signaller2HasSignal = false; - bool signaller3HasSignal = false; - bool signaller4HasSignal = false; - - // - // Validator Flags ... - bool validateByOrderFlow = false; - - // - // Target Flags ... - bool hasPartialCloseOnTp1 = false; - - // - bool doRFOnEntryOnTP1 = false; - - // - // Draw Flags ... - bool draw = true; - bool drawZone = true; - bool drawMarketStructurePivots = false; - bool drawMarketStructureAnalysis = false; - bool drawMarketStructureOrderFlow = false; - XPOIDrawConfig iDrawConfig; - - // - drawZones = false; - drawIZones = false; - drawTrends = false; - drawSCTrend = false; - drawMCTrend = false; - drawLCTrend = false; - drawHCTrend = false; - drawSupport = false; - drawISupport = false; - drawOrderFlow = false; - drawResistance = false; - drawIResistance = false; - - // - // Signal Checking ... - - // - // Analyse Market Strucutre ... - XFIMAMarketStructure marketStructure; - - // - // Signal Detection Flags ... - - // - // Signaller 1 ... - if (useSignaller1) - { - // - signaller1HasSignal = Strategy1HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller1HasSignal) - { - // - provider += "1"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 2 ... - if (useSignaller2) - { - // - signaller2HasSignal = Strategy2HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller2HasSignal) - { - // - provider += "2"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 3 ... - if (useSignaller3) - { - // - signaller3HasSignal = Strategy3HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller3HasSignal) - { - // - provider += "3"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 4 ... - if (useSignaller4) - { - // - signaller4HasSignal = Strategy4HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller4HasSignal) - { - // - provider += "4"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Summarize Signallers Result ... - result = signaller1HasSignal || - signaller2HasSignal || - signaller3HasSignal || - signaller4HasSignal; - - // - // Signal Validating ... - - // - // Validate Signals by Order Flow ... - if (result && validateByOrderFlow) - { - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - - // - bool isBullish = IsXBullish(dir) && - marketStructure.HasBullishOrderFlow(); - - // - bool isBearish = IsXBearish(dir) && - marketStructure.HasBearishOrderFlow(); - - // - // Summarizing result ... - result = isBullish || - isBearish; - } - - // - // Targets, Restrictions and Risk Management ... - if (result) - { - // - // Requirements ... - XTarget iTarget; - - // - // Checking Direction of Signal ... - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, dir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? zone.lower - slAddition - : zone.upper + slAddition; - - // - // Calculate Risk ... - double risk = MathAbs(entry - sl); - - // - // Calculate Reward ... - double reward = defaultSignalR2R * risk; - - // - // Calculate TP1 ... - double tp1 = isBullish - ? entry + risk - : entry - risk; - double tp2 = isBullish - ? entry + (2 * risk) - : entry - (2 * risk); - - // - // Calculate TP ... - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Check Max Allowed Risk ... - bool hasTooMuchRisk = maxAllowedRiskDistance <= 0 - ? false - : risk >= (maxAllowedRiskDistance * points); - if (hasTooMuchRisk) - { - // - // Clean Signal if Too much Risk ... - zone.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Common Targets ... - - // - // Partial Close on TP 1 ... - if (hasPartialCloseOnTp1) - { - // - iTarget.Clean(); - iTarget.target = tp1; - iTarget.actingDistance = 5; - iTarget.volumeMultiplier = 0.8; - iTarget.doRFOnEntry = doRFOnEntryOnTP1; - - // - AddRef(iTarget, targets); - } - - // - // Custom Signaller Targets ... - - // - // Restrictions Handling ... - if (risk > 0 && HasRestrictions()) - { - // - // Reset Restricitons if necessary ... - ResetRestrictions(); - - // - // Handle Custom Restrictions Senario ... - } - - // - // Ignore Targets ... - if (ignoreTargets) - { - XClean(targets); - } - - // - // Summarize Result ... - result = zone.IsValid() && - HasDirection(dir); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Draws ... - if (result && draw) - { - // - // Prepare Draw Config ... - iDrawConfig = structureDrawConfig.drawConfig; - iDrawConfig.zonesWidth = 3; - iDrawConfig.zonesStyle = STYLE_DASH; - iDrawConfig.bullishColor = clrYellow; - iDrawConfig.bearishColor = clrDarkOrange; - - // - // Draw Zone ... - if (drawZone) - { - poiDrawer.DrawZone(zone, iDrawConfig); - } - - // - // Draw Market Structure ... - - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - if (marketStructure.IsValid()) - { - // - // Order Flow ... - if (drawMarketStructureOrderFlow && marketStructure.HasOrderFlow()) - { - poiDrawer.DrawZones(marketStructure.orderFlow, iDrawConfig); - } - - // - // Pivots ... - if (drawMarketStructurePivots) - { - // - XPivot pivots[]; - int pivotsCount = marketStructure.CollectPivots( - pivots, - true // Contains Patterns ... - ); - if (IsValidSize(pivotsCount)) - { - poiDrawer.DrawPivots(pivots, iDrawConfig); - } - - // - XClean(pivots); - } - - // - // Analysis ... - if (drawMarketStructureAnalysis) - { - // - } - } - - // - // Other Drawing Materials ... - Print("Signaller Providers: ", provider); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - - // - // Cleanup ... - tmpZone.Clean(); - iDrawConfig.Clean(); - marketStructure.Clean(); - - // - return result; - } - - // - // Custom Signal Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone atrBox; - XBoxZone zones[]; - XBoxZone tmpZone; - XBoxZone scPVZone; - XBoxZone mcPVZone; - XBoxZone lcPVZone; - XBoxZone hcPVZone; - XBoxZone tmpZones[]; - XBoxZone pinBarZone; - XBoxZone supports[]; - XBoxZone resistances[]; - XBoxZone affectedZone; - XTrend pinBarZoneTrend; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION tmpDir; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysis p3BarPatterns; - XPatternAnalysisConfig iPatternsConfig; - - // - // Reading Bars ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Reading Bar Patterns ... - iPatternsConfig.Default(); - iPatternsConfig.FullPattern(); - result = - result && - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - iPatternsConfig // - ); - result = - result && - poiDetector.AnalyseBarPatterns( - p3Bar, - p3BarPatterns, - iPatternsConfig // - ); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } - - // - // Detect Directional Candlestic Patterns ... - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isP2BarHasBullishPatterns = - (bar.close > p2Bar.low || - bar.open > p2Bar.low) && - ( - // - p2BarPatterns.IsPinned(X_DIRECTION_BULLISH) || - p2BarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - p2BarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - p2BarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - p2BarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isP3BarHasBullishPatterns = - (bar.close > p3Bar.low || - bar.open > p3Bar.low) && - ( - // - p3BarPatterns.IsPinned(X_DIRECTION_BULLISH) || - p3BarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - p3BarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - p3BarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - p3BarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - bool isP2BarHasBearishPatterns = - (bar.close < p2Bar.high || - bar.open < p2Bar.high) && - ( - // - p2BarPatterns.IsPinned(X_DIRECTION_BEARISH) || - p2BarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - p2BarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - p2BarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - p2BarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - bool isP3BarHasBearishPatterns = - (bar.close < p3Bar.high || - bar.open < p3Bar.high) && - ( - // - p3BarPatterns.IsPinned(X_DIRECTION_BEARISH) || - p3BarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - p3BarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - p3BarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - p3BarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Checking Support and Resistances ... - - // - // Support ... - bool hasSupport = pBarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = pBarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p2BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - hasSupport = p3BarPatterns.IsSupport(); - if (hasSupport) - { - // - hasSupport = p3BarPatterns.GetSupport(tmpBar, tmpPivot, tmpZone); - if (hasSupport) - { - AddIfNotExists(tmpZone, supports); - } - } - - // - // Resistance ... - bool hasResistance = pBarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = pBarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p2BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - hasResistance = p3BarPatterns.IsResistance(); - if (hasResistance) - { - // - hasResistance = p3BarPatterns.GetResistance(tmpBar, tmpPivot, tmpZone); - if (hasResistance) - { - AddIfNotExists(tmpZone, resistances); - } - } - - // - // Collecting Zones ... - - // - int collectedZonesCount = poiDetector.DetectZones( - bar, - zones, - true, // Validated Zones ... - false, // Remove Used Zones ... - false, // Contains Order Blocks ... - true, // Contains Fair Value Gaps ... - true, // Contains Supports ... - true, // Contains Resistances ... - X_DIRECTION_NONE, // For Dir (Contains All Direction Zones) ... - X_SORT_BY_DATE, // Sort By ... - X_DIRECTION_BEARISH, // Sort Dir ... - 3, // Zones Loopback ... - 3, // Zones Validation Length ... - 0, // Count (All Zones) ... - 100 // Loop back for Detection ... - ); - bool hasCollectedZones = IsValidSize(collectedZonesCount) && - collectedZonesCount > 1; - int affectedZonesCount = 0; - bool hasAffectedZone = false; - int collectedZonesBullishCount = 0; - int collectedZonesBearishCount = 0; - bool hasBullishAffectedZone = false; - bool hasBearishAffectedZone = false; - bool hasBullishCollectedZones = false; - bool hasBearishCollectedZones = false; - if (hasCollectedZones) - { - // - // Bullish ... - XClean(tmpZones); - collectedZonesBullishCount = ExtractByDirection(tmpZones, zones, X_DIRECTION_BULLISH); - hasBullishCollectedZones = IsValidSize(collectedZonesBullishCount); - - // - // Bearish ... - XClean(tmpZones); - collectedZonesBearishCount = ExtractByDirection(tmpZones, zones, X_DIRECTION_BEARISH); - hasBearishCollectedZones = IsValidSize(collectedZonesBearishCount); - - // - // Extract Affected Zones ... - XClean(tmpZones); - int affectedZonesCount = ExtractAffectedZones(p2Bar, zones, tmpZones); - int idx = GetYoungest(tmpZones); - if (IsValidIndex(idx)) - { - affectedZone = tmpZones[idx]; - } - hasAffectedZone = affectedZone.IsValid(); - hasBullishAffectedZone = hasAffectedZone && affectedZone.IsBullish(); - hasBearishAffectedZone = hasAffectedZone && affectedZone.IsBearish(); - } - - // - // Reading Cycle PVS ... - bool hasSCPV = poiDetector.GetSCZone(pBar, scPVZone); - bool hasMCPV = poiDetector.GetMCZone(pBar, mcPVZone); - bool hasLCPV = poiDetector.GetLCZone(pBar, lcPVZone); - bool hasHCPV = poiDetector.GetHCZone(pBar, hcPVZone); - bool isCyclePVBullish = - hasMCPV && mcPVZone.IsBullish() && - hasLCPV && lcPVZone.IsBullish() && - hasHCPV && hcPVZone.IsBullish(); - bool isCyclePVBearish = - hasMCPV && mcPVZone.IsBearish() && - hasLCPV && lcPVZone.IsBearish() && - hasHCPV && hcPVZone.IsBearish(); - - // - // Validating Market Direction ... - // by Checking HC and LC States ... - - // - bool isLCBullish = fimaParser.IsLCMABullish(pBar.Index()); - bool isHCBullish = fimaParser.IsHCMABullish(pBar.Index()); - bool isLCHigherLow = - (fimaParser.IsLCHigherLow(pBar.Index()) || - fimaParser.IsLCHigherLow(p2Bar.Index()) || - fimaParser.IsLCHigherLow(p3Bar.Index())); - bool isCyclesBullish = - isLCBullish && - isHCBullish && - isLCHigherLow; - - // - bool isLCBearish = fimaParser.IsLCMABearish(pBar.Index()); - bool isHCBearish = fimaParser.IsHCMABearish(pBar.Index()); - bool isLCLowerHigh = - (fimaParser.IsLCLowerHigh(pBar.Index()) || - fimaParser.IsLCLowerHigh(p2Bar.Index()) || - fimaParser.IsLCLowerHigh(p3Bar.Index())); - bool isCyclesBearish = - isLCBearish && - isHCBearish && - isLCLowerHigh; - - // - // Looking For a Pin Bar in P2Bar ... - bool isP2BarIsPinBar = poiDetector.IsPinnedBar( - p2Bar, - tmpDir, - 4, // Shadow Multiplier ... - 4, // Minimum Range Multiplier ... - true // Force Pin Bar Direction ... - ); - if (isP2BarIsPinBar) - { - // - isP2BarIsPinBar = ToBox( - p2Bar, - pinBarZone, - tmpDir, - X_BAR_PATTERN_PINNED // - ); - if (isP2BarIsPinBar) - { - // - pinBarZone.to = bar.time; - isP2BarIsPinBar = poiDetector.HasBoundaryTrend( - pinBarZone, - pinBarZoneTrend, - false // - ); - isP2BarIsPinBar = - isP2BarIsPinBar && - tmpDir == pinBarZoneTrend.dir; - } - } - bool isP2BarPinnedBullish = isP2BarIsPinBar && IsXBullish(tmpDir); - bool isP2BarPinnedBearish = isP2BarIsPinBar && IsXBearish(tmpDir); - - // - // Checking ATR Box ... - bool hasATRBox = fimaParser.GetATRBox( - atrBox, - bar.Index() // - ); - bool hasATRBoxBullish = hasATRBox && atrBox.IsBullish(); - bool hasATRBoxBearish = hasATRBox && atrBox.IsBearish(); - - // - // Checking Double Patterns ... - ENUM_X_DIRECTION iDBDir; - XPatternAnalysis iPatterns; - XPatternAnalysis iPPatterns; - ENUM_X_BAR_PATTERN doublePatterns[]; - GetCandlestickPatterns(doublePatterns); - bool hasDoublePatterns = poiDetector.HasDoublePatterns( - pBar, - iDBDir, - iPatterns, - iPPatterns, - doublePatterns, - iPatternsConfig, - 5 // - ); - bool hasBullishDoublePatterns = hasDoublePatterns && IsXBullish(iDBDir); - bool hasBearishDoublePatterns = hasDoublePatterns && IsXBearish(iDBDir); - - // - isBullish = - // - hasSupport && - hasResistance && - isCyclesBullish && - hasATRBoxBullish && - isCyclePVBullish && - isP2BarPinnedBullish && - hasBullishAffectedZone && - isPBarHasBullishPatterns && - hasBullishCollectedZones && - isP2BarHasBullishPatterns && - collectedZonesBullishCount > collectedZonesBearishCount && - true - // - ; - - // - isBearish = - // - hasSupport && - hasResistance && - isCyclesBearish && - hasATRBoxBearish && - isCyclePVBearish && - isP2BarPinnedBearish && - hasBearishAffectedZone && - isPBarHasBearishPatterns && - hasBearishCollectedZones && - isP2BarHasBearishPatterns && - collectedZonesBearishCount > collectedZonesBullishCount && - true - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - zone = pinBarZone; - - // - result = zone.IsValid(); - } - - // - // Draws ... - if (result) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - XPatternAnalysisDrawConfig iPatternsConfig = structureDrawConfig.barAnalysisDrawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - // poiDrawer.DrawZone(scPVZone, iConfig); - // poiDrawer.DrawZone(mcPVZone, iConfig); - // poiDrawer.DrawZone(lcPVZone, iConfig); - // poiDrawer.DrawZone(hcPVZone, iConfig); - - // - poiDrawer.DrawPatternAnalysis(pBarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p2BarPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(p3BarPatterns, iPatternsConfig); - - // - poiDrawer.DrawZone(pinBarZone, iConfig); - poiDrawer.DrawZone(affectedZone, iConfig); - poiDrawer.DrawTrendLine(pinBarZoneTrend, iConfig); - - // - // poiDrawer.DrawZones(zones, iConfig); - poiDrawer.DrawZones(supports, iConfig); - poiDrawer.DrawZones(resistances, iConfig); - - // - if (hasATRBox) - { - poiDrawer.DrawZone(atrBox, iConfig); - } - - // - if (hasDoublePatterns) - { - // - poiDrawer.DrawPatternAnalysis(iPatterns, iPatternsConfig); - poiDrawer.DrawPatternAnalysis(iPPatterns, iPatternsConfig); - } - - // - iConfig.Clean(); - iPatternsConfig.Clean(); - - // - DebugBreak(); - - // // - // result = false; - // isBullish = false; - // isBearish = false; - // zone.Clean(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(zones); - tmpBar.Clean(); - tmpZone.Clean(); - XClean(supports); - XClean(tmpZones); - scPVZone.Clean(); - mcPVZone.Clean(); - lcPVZone.Clean(); - hcPVZone.Clean(); - tmpPivot.Clean(); - pinBarZone.Clean(); - XClean(resistances); - affectedZone.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - p3BarPatterns.Clean(); - pinBarZoneTrend.Clean(); - iPatternsConfig.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 2 ... - * - * Strategy 2: - * =========== - * - Works Based On PBar Patterns Focused on PinBar ... - * - Looking for a Bar Directional Pattern Happens ... - * - Validate Fast Ma Over/Under Slow ... - * - Validate P2Peak/Vale doesnt Under or Over Last (InDirectional) ... - * - Validate P2Bar Has Directional Market Strucuture Zone (OB, FVG, Support/Resistance) ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarPatterns; - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - structureConfig.barsAnalysisConfig // - ); - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Check Boundary Trend ... - XTrend boundaryTrend; - bool hasBoundaryTrend = fimaParser.HasBoundaryTrend(boundaryTrend, pBar.Index()); - bool hasBoundaryBullishTrend = hasBoundaryTrend && boundaryTrend.IsBullish(); - bool hasBoundaryBearishTrend = hasBoundaryTrend && boundaryTrend.IsBearish(); - - // - // Check Bar Patterns ... - - // - // Bars Sequences ... - bool hasBullishSequence = p3Bar.IsBearish() && - pBar.IsBullish(); - bool hasBearishSequence = p3Bar.IsBullish() && - pBar.IsBearish(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - double peak = fimaHelper.GetPeak(bar.Index()); - double vale = fimaHelper.GetVale(bar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - double p2Peak = fimaHelper.GetPeak(p2Bar.Index()); - double p2Vale = fimaHelper.GetVale(p2Bar.Index()); - bool isPPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isPValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - bool isP2PeakOverLast = fimaParser.IsPeakOverLast(p2Bar.Index()); - bool isP2ValeUnderLast = fimaParser.IsValeUnderLast(p2Bar.Index()); - bool isPeakOverLast = isPPeakOverLast || - isP2PeakOverLast; - bool isValeUnderLast = isPValeUnderLast || - isP2ValeUnderLast; - bool isP2ValeOverLast = pVale > p2Vale; - bool isP2PeakUnderLast = pPeak < p2Peak; - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - bool isFastOverLast = fimaHelper.GetMAFast(pBar.Index()) > fimaHelper.GetMAFast(p2Bar.Index()); - bool isFastUnderLast = fimaHelper.GetMAFast(pBar.Index()) < fimaHelper.GetMAFast(p2Bar.Index()); - - // - // Force P2Bar is Pin Bar ... - ENUM_X_DIRECTION p2Dir; - bool isP2BarPinned = poiDetector.IsPinnedBar( - p2Bar, - p2Dir // - ); - bool isP2BarBullishPinned = - isP2BarPinned && - IsXBullish(p2Dir); - bool isP2BarBearishPinned = - isP2BarPinned && - IsXBearish(p2Dir); - - // - // Check Based On LC and HC MA State ... - - // - bool isLCMABullish = fimaParser.IsLCMABullish(pBar.Index()); - bool isHCMABullish = fimaParser.IsHCMABullish(pBar.Index()); - bool isCycleMABullish = isLCMABullish && isHCMABullish; - - // - bool isLCMABearish = fimaParser.IsLCMABearish(pBar.Index()); - bool isHCMABearish = fimaParser.IsHCMABearish(pBar.Index()); - bool isCycleMABearish = isLCMABearish && isHCMABearish; - - // - // Do ... - - // - isBullish = - // - hasSupport && - isFastOverLast && - isValeUnderLast && - isCycleMABullish && - hasBullishSequence && - !isP2PeakUnderLast && - isPBarCloseOverFast && - isP2BarBullishPinned && - hasBoundaryBullishTrend && - isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - hasResistance && - isPeakOverLast && - isFastUnderLast && - isCycleMABearish && - !isP2ValeOverLast && - hasBearishSequence && - isPBarCloseUnderFast && - isP2BarBearishPinned && - hasBoundaryBearishTrend && - isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Draws ... - if (result) - { - // - // XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - // iConfig.trendRayLeft = false; - // iConfig.trendRayRight = false; - // poiDrawer.DrawTrendLine(boundaryTrend, iConfig); - // poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - // iConfig.Clean(); - - // - // DebugBreak(); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * Strategy 3: - * =========== - * - Works Based On Breaked Support or Resistances ... - * - Looking for a Support or Resistance to Breaked ... - * - Validate Breaker Bar to Change Peak or Vale ... - * - Validate Bar Opposit Side of Breaker Bar's Shadow ... - * - Validate by Checking Market Strucutre to Has Directional Zone - * (Support for Resistance Break / Resistance for Support Break) ... - * - Validate Breaker Bar to Has Directional FVG ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - - // - bool validateByPVChanges = true; - bool validateByGapExists = true; - bool validateByBarShadows = true; - bool validateHasDirectionalZone = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XBoxZone _fvg; - XBoxZone _support; - XBoxZone _resistance; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - patternConfig // - ); - - // - // Price Must Break Support or Resistance ... - - // - // Extract Support and Resistance ... - bool hasSupport = p2BarPatterns.IsSupport(); - bool hasResistance = p2BarPatterns.IsResistance(); - if (hasSupport) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, _support); - tmpBar.Clean(); - tmpPivot.Clean(); - } - if (hasResistance) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - tmpBar.Clean(); - tmpPivot.Clean(); - } - - // - bool hasBreakedSupport = hasSupport && - pBar.close < _support.lower && - p2Bar.close > _support.lower; - bool hasBreakedResistance = hasResistance && - pBar.close > _resistance.upper && - p2Bar.close < _resistance.upper; - - // - isBullish = hasBreakedResistance; - isBearish = hasBreakedSupport; - - // - result = isBullish || isBearish; - - // - // Validate By PV Changed ... - // Breaker Bar must Change Peak or Value ... - if (result && validateByPVChanges) - { - // - bool isPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - - // - isBullish = - isBullish && - isPeakOverLast; - - // - isBearish = - isBearish && - isValeUnderLast; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate by Bar Shadows ... - // Breakre Bar Side Shadow must not Reached ... - if (result && validateByBarShadows) - { - // - isBullish = - isBullish && - pBar.low > p2Bar.low; - - // - isBearish = - isBearish && - pBar.high < p2Bar.high; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Has Directional Zone ... - if (result && validateHasDirectionalZone) - { - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate By Gap Exists ... - if (result && validateByGapExists) - { - // - ENUM_X_DIRECTION tmpDir; - bool hasFVG = poiDetector.HasFVG( - pBar, - tmpDir, - _fvg // - ); - - // - isBullish = - isBullish && - hasFVG && - IsXBullish(tmpDir); - - // - isBearish = - isBearish && - hasFVG && - IsXBearish(tmpDir); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Prepare Direction and Zone ... - if (result) - { - // - if (isBullish) - { - // - zone = _resistance; - zone.dir = Opposit(_resistance.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - if (isBearish) - { - // - zone = _support; - zone.dir = Opposit(_support.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - // Zone Validation Base ... - result = zone.IsValid(); - if (result) - { - // - // Validate By Trend of Zone ... - XTrend zoneTrend; - XTrend zoneToTrend; - - // - // Detecting Trends ... - result = poiDetector.HasBoundaryTrend(zone, zoneTrend, false); - result = result && - poiDetector.HasBoundaryTrend(zone, zoneToTrend, true); - - // - // Validate Trend ... - result = - result && - zone.dir == zoneTrend.dir && - zone.dir == zoneToTrend.dir; - - // - // Draw ... - if (result) - { - // // - // XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - // iConfig.trendRayLeft = false; - // iConfig.trendRayRight = false; - - // // - // poiDrawer.DrawTrendLine(zoneTrend, iConfig); - // poiDrawer.DrawTrendLine(zoneToTrend, iConfig); - - // // - // iConfig.Clean(); - } - - // - // Cleanup ... - zoneTrend.Clean(); - zoneToTrend.Clean(); - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - isBullish = false; - isBearish = false; - } - } - - // - result = zone.IsValid(); - } - - // - if (result) - { - // - if (_support.IsValid()) - { - poiDrawer.DrawZone(_support, structureDrawConfig.drawConfig); - } - - // - if (_resistance.IsValid()) - { - poiDrawer.DrawZone(_resistance, structureDrawConfig.drawConfig); - } - - // - if (pBarPatterns.IsValid()) - { - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - } - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - patternConfig.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * Strategy 4: - * =========== - * - Works Based on Order Flow ... - * - Looking for new and Fresh Order Flow ... - * - Validate Bar is Inside Order Flow ... - * - Validate Bar has Proper Pattern ... - * - Validate Bar Based on ATR Band in two Step: - * - Step 1: Bars is Inside ATR Band (Middle) ... - * - Step 2: Trigger Bars Close Price based on ATR Band ... - * - Validate Order Flow based on Market Structure Zone ... - * - Validate Trigger Bar based on InDirectional Market Structure Zones ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateBarInsideZone = true; - bool validateByBarPatterns = true; - bool validateByXFIMABoundary = true; - bool validateByBarInsideATRBand = true; - bool validateByBarBasedOnATRBand = true; - bool validateByXFIMABoundaryTrend = true; - bool validateMarketStructureHasDirectionalZone = true; - bool validateMarketStructureDirectionalZoneInsideOrderFlow = true; - bool validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - - // - // Detecting OrderFlow ... - XBoxZone oFlow[]; - bool hasOrderFlow = poiDetector.HasOrderFlow( - p3Bar, - dir, - oFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - - // - XTrend boundaryTrend; - XTrend boundaryZoneTrend; - - // - double atrBandUpper = EMPTY_VALUE; - double atrBandLower = EMPTY_VALUE; - double atrBandMiddle = EMPTY_VALUE; - - // - isBullish = hasOrderFlow && - IsXBullish(dir); - - // - isBearish = hasOrderFlow && - IsXBearish(dir); - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Force Price of p2Bar is Inside Order Flow ... - if (result && validateBarInsideZone) - { - // - double orderFlowUpper = 0; - double orderFlowLower = 0; - - // - int idx = -1; - idx = GetHighest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowUpper = oFlow[idx].upper; - } - idx = GetLowest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowLower = oFlow[idx].lower; - } - - // - result = NotEmptyZero(orderFlowUpper) && - NotEmptyZero(orderFlowLower) && - orderFlowUpper > orderFlowLower && - (isBullish - ? p2Bar.low < orderFlowUpper - : p2Bar.high > orderFlowLower); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Has Pattern ... - if (result && validateByBarPatterns) - { - // - // Analyse Bar Patterns ... - result = pBarPatterns.IsValid(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - result && - // (bar.close > pBar.low || - // bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - result && - // (bar.close < pBar.high || - // bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force P2Bar Place Checking based on ATR Band ... - if (result && validateByBarInsideATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(p2Bar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(p2Bar.Index()); - - // - atrBandMiddle = atrBandLower + ((atrBandUpper - atrBandLower) / 2); - - // - isBullish = - isBullish && - NotEmptyZero(atrBandMiddle) && - p2Bar.low < atrBandMiddle; - - // - isBearish = - isBearish && - NotEmptyZero(atrBandMiddle) && - p2Bar.high > atrBandMiddle; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Place Checking based on ATR Band ... - if (result && validateByBarBasedOnATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(pBar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(pBar.Index()); - - // - result = - NotEmptyZero(atrBandUpper) && - NotEmptyZero(atrBandLower) && - (isBullish - ? pBar.close > atrBandLower - : pBar.close < atrBandUpper); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // for Bullish has Support ... - // for Bearish has Resistance ... - if (result && validateMarketStructureHasDirectionalZone) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Validate Support and Resistance by Order Flow ... - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - // Check Market Strucutre Support and Resistance Validation ... - if (validateMarketStructureDirectionalZoneInsideOrderFlow) - { - // - hasSupport = - hasOFBox && - hasSupport && - ofZone.lower < _support.lower && - ofZone.upper > _support.upper; - - // - hasResistance = - hasOFBox && - hasResistance && - ofZone.lower < _resistance.lower && - ofZone.upper > _resistance.upper; - } - - // - // Validate Directional Support or Resistance Exists ... - - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Makret Structure Has Not Indirectional Zone ... - if (result && validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - bool hasIndirectionalZone = - (isBullish && hasResistance) || - (isBearish && hasSupport); - if (hasIndirectionalZone) - { - // - // Here we Have to Validate Zone Place ... - - // - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? oFlow[0].lower : oFlow[0].upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Bullish ... - if (isBullish && hasResistance) - { - hasResistance = _resistance.lower <= tp; - } - - // - // Bearish ... - if (isBearish && hasSupport) - { - hasSupport = _support.upper >= tp; - } - } - - // - isBullish = - isBullish && - !hasResistance; - - // - isBearish = - isBearish && - !hasSupport; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate ... - result = isBullish || isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone and do Zone Based Validations ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Refine Zone ... - zone.to = bar.time; - zone.upper = MathMax(zone.upper, atrBandMiddle); - zone.lower = MathMin(zone.lower, atrBandMiddle); - - // - // Validate by XFIMA Boundary ... - if (result && validateByXFIMABoundary) - { - // - // Try to Retrieve Boundary To Trend ... - result = poiDetector.HasBoundaryTrend( - zone, - boundaryTrend, - true // - ); - - // - // Try to Retrieve Boundary Zone Trend ... - result = - result && - poiDetector.HasBoundaryTrend( - zone, - boundaryZoneTrend, - false // - ); - - // - // Check and Validate Trend Direction ... - result = - result && - zone.dir == boundaryTrend.dir && - zone.dir == boundaryZoneTrend.dir; - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - result = false; - isBullish = false; - isBearish = false; - } - } - - // - // Manage Stops ... - if (result) - { - // - // Since Stop Management Changes Zones Edge(s) ... - // we do it here for Refining Zone ... - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - XTarget iTarget; - - // - // Calculate Requirements ... - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? zone.lower : zone.upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // High Risk Target is Used to Protect In Profit Positiions - // from Reversal Patterns ... - double highRiskR2r = (defaultSignalR2R / 5) * 4; - double highRiskReward = highRiskR2r * risk; - double highRiskTP = isBullish - ? entry + highRiskReward - : entry - highRiskReward; - iTarget.Clean(); - iTarget.actingDistance = 5; - iTarget.doRFOnEntry = true; - iTarget.target = highRiskTP; - iTarget.volumeMultiplier = 0.8; - // AddRef(iTarget, targets); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(oFlow); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - patternConfig.Clean(); - boundaryZoneTrend.Clean(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy.mq5 b/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy.mq5 deleted file mode 100644 index 65f73531..00000000 --- a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class copy.mq5 +++ /dev/null @@ -1,3485 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.parser.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - CArrayObj drawnObjects; // Drawing Objects Holder ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAHelperParser *fimaParser; // XFIMA Helper Parser ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - XFIMAMarketStructureConfig structureConfig; // XFIMA Market Structure Detector Config ... - XFIMAMarketStructureDrawerConfig structureDrawConfig; // XFIMA Market Structure Draw Config ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - // Instantiate XFIMA Helper Parser ... - fimaParser = new XCXFIMAHelperParser(fimaHelper); - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper, fimaParser); - - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - structureConfig.Clean(); - structureDrawConfig.Clean(); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure ... - drawLeg = true; - drawZones = true; - drawIZones = true; - drawTrends = true; - drawSCTrend = true; - drawMCTrend = true; - drawLCTrend = true; - drawHCTrend = true; - drawSupport = true; - drawISupport = true; - drawOrderFlow = true; - drawResistance = true; - drawIResistance = true; - - // - manageLegs = true; - manageZones = true; - manageIZones = true; - manageTrends = false; - manageOrderFlow = true; - - // - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Manage ... - Manage(iBar); - - // - // Strategy X ... - has = HasSignal( - iBar, - iZone, - iTargets, - iDir // - ); - - // - // Handle Resting Signals ... - has = HasDirection(iDir) && - iZone.IsValid(); - - // - // Prepare Signal ... - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, iDir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Signal ... - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - sl, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - } - - // - // Notify On Signal Event ... - if (has) - { - NotifySignalEventListeners(iSignal); - } - - // - // Cleanup ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - XClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - XClean(guards); - return result; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Requirements ... - XGuard iGuard; - bool has = false; - int samePeaks = 0; - int sameVales = 0; - double iValue = 0; - double points10 = 0; - double points50 = 0; - double points100 = 0; - int samePVValidation = 5; - bool isPeakOverLast = false; - bool isValeUnderLast = false; - - // - for (int i = 0; i < positionsCount; i++) - { - // - points10 = 10 * positions[i].GetPointsValue(); - points50 = 50 * positions[i].GetPointsValue(); - points100 = 100 * positions[i].GetPointsValue(); - - // - // Near to TP Guard ... - has = positions[i].profit > 0; - if (has) - { - // - // Has Same Peaks or Vales ... - samePeaks = fimaParser.CountSamePeaks(barIndex); - sameVales = fimaParser.CountSameVales(barIndex); - isPeakOverLast = (fimaParser.IsPeakOverLast(barIndex) || - fimaParser.IsPeakOverLast(barIndex + 1)); - isValeUnderLast = (fimaParser.IsValeUnderLast(barIndex) || - fimaParser.IsValeUnderLast(barIndex + 1)); - has = (positions[i].IsBullish() - ? ( - isPeakOverLast && - sameVales >= samePVValidation && - fimaHelper.GetVale(barIndex) > positions[i].sl) - : positions[i].IsBearish() - ? ( - isValeUnderLast && - samePeaks >= samePVValidation && - fimaHelper.GetPeak(barIndex) < positions[i].sl) - : false); - if (has) - { - // - iGuard.Clean(); - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.sl = positions[i].IsBullish() - ? fimaHelper.GetVale(barIndex) - points10 - : fimaHelper.GetPeak(barIndex) + points10; - iGuard.action = X_GUARD_ACTION_TRAIL_STOP; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - - // - // Remove TP if in Profit SL ... - iValue = (positions[i].IsBullish() ? positions[i].entry + points10 : positions[i].entry - points10); - has = - (positions[i].IsBullish() && HasResistance()) - ? (iGuard.sl >= iValue && - positions[i].tp < resistance.lower) - : (positions[i].IsBearish() && HasSupport()) - ? (iGuard.sl <= iValue && - positions[i].tp > support.upper) - : false; - if (has) - { - // - iGuard.Clean(); - iGuard.force = false; - iGuard.tp = positions[i].IsBullish() - ? resistance.lower - : support.upper; - iGuard.time = TimeCurrent(); - iGuard.symbol = positions[i].symbol; - iGuard.period = positions[i].period; - iGuard.ticket = positions[i].ticket; - iGuard.provider = positions[i].provider; - iGuard.action = X_GUARD_ACTION_TRAIL_TARGET; - - // - has = iGuard.IsValid(); - if (has) - { - AddRef(iGuard, guards); - } - } - } - } - } - } - - // - result = ArraySize(guards); - - // - // Cleanup ... - iGuard.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - void Manage(XOHCL &bar) - { - // - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - has = bar.GetPreviousBar(pBar); - has = has && - pBar.GetPreviousBar(p2Bar); - has = has && - p2Bar.GetPreviousBar(p3Bar); - if (!has) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - ManageLeg(bar); - ManageTrends(bar); - ManageZones(p2Bar); - ManageIZones(p2Bar); - ManageOrderFlow(p3Bar); - - // - // Cleanup ... - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - // Private ... - private: - // - // Props ... - - // - // Leg ... - - XLeg leg; // Exists Leg ... - bool drawLeg; // Draw Leg ... - bool manageLegs; - - // - bool HasLeg() - { - return leg.IsValid(); - } - - // - bool ValidateLeg(XOHCL &bar) - { - // - bool result = false; - - // - result = HasLeg() && - bar.IsValid(); - if (!result) - { - return result; - } - - // - result = - leg.IsBullish() - ? bar.low > leg.lower - : leg.IsBearish() - ? bar.high < leg.upper - : false; - - // - return result; - } - - // - void DrawLeg() - { - // - if (!drawLeg) - { - return; - } - - // - if (!HasLeg()) - { - return; - } - - // - // Update to Times ... - leg.UpdateTimes(); - - // - // Draw Leg Box ... - XBoxZone legZone; - leg.ToBox(legZone); - if (legZone.IsValid()) - { - // - legZone.to = TimeCurrent(); - poiDrawer.DrawZone(legZone, structureDrawConfig.drawConfig); - } - - // - // Draw Legs Other Stufs ... - return; - - // - // FVGs ... - poiDrawer.DrawZones(leg.bullishFVGs, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.bearishFVGs, structureDrawConfig.drawConfig); - - // - // Support and Resistances ... - poiDrawer.DrawZones(leg.supports, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.resistances, structureDrawConfig.drawConfig); - - // - // Patterns ... - poiDrawer.DrawPatternAnalysises(leg.patterns, structureDrawConfig.barAnalysisDrawConfig); - } - - // - void ManageLeg(XOHCL &bar) - { - // - // Validate Exists ... - if (HasLeg()) - { - // - if (!ValidateLeg(bar)) - { - // - // Invalidate XLeg ... - leg.Clean(); - } - } - - // - // Detect New ... - if (!HasLeg()) - { - poiDetector.IsLegPattern(bar, leg); - } - - // - // Update Exists ... - if (HasLeg()) - { - // - // Update to Times ... - leg.UpdateTimes(); - - // - DrawLeg(); - } - } - - // - // Order Flow ... - - // - bool drawOrderFlow; - XBoxZone orderFlow[]; - bool manageOrderFlow; - ENUM_X_DIRECTION orderFlowDir; - - // - bool HasOrderFlow() - { - // - return HasChild(orderFlow) && - HasDirection(orderFlowDir); - } - - // - bool HasBullishOrderFlow() - { - return HasOrderFlow() && - IsXBullish(orderFlowDir); - } - - // - bool HasBearishOrderFlow() - { - return HasOrderFlow() && - IsXBearish(orderFlowDir); - } - - // - bool GetOrderFlowBoundary( - double &upper, - double &lower // - ) - { - // - bool result = false; - - // - // Prepare ... - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - - // - // Validate ... - result = HasOrderFlow(); - if (!result) - { - return result; - } - - // - int idx = -1; - - // - // Upper ... - idx = GetHighest(orderFlow); - if (IsValidIndex(idx)) - { - upper = orderFlow[idx].upper; - } - - // - // Lower ... - idx = GetLowest(orderFlow); - if (IsValidIndex(idx)) - { - lower = orderFlow[idx].lower; - } - - // - result = NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - // Cleanup ... - if (!result) - { - // - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - } - - // - return result; - } - - // - bool ValidateOrderFlow(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasOrderFlow(); - if (!result) - { - return result; - } - - // - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - result = GetOrderFlowBoundary(upper, lower); - result = result && - HasBullishOrderFlow() - ? bar.low > lower - : bar.high < upper; - - // - return result; - } - - // - void DrawOrderFlow() - { - // - if (!drawOrderFlow || !HasOrderFlow()) - { - return; - } - - // - poiDrawer.DrawZones(orderFlow, structureDrawConfig.drawConfig); - } - - // - void ManageOrderFlow(XOHCL &bar) - { - // - // Validate Exists ... - if (HasOrderFlow()) - { - // - if (!ValidateOrderFlow(bar)) - { - // - // Invalidate OrderFlow ... - XClean(orderFlow); - orderFlowDir = X_DIRECTION_NONE; - } - } - - // - // Detect New ... - if (!HasOrderFlow()) - { - // - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - // patternConfig.Default(); - // patternConfig.supportAndResistanceLoopbackLength = 21; - // patternConfig.supportAndResistanceValidationLength = 7; - - // - poiDetector.HasOrderFlow( - bar, - orderFlowDir, - orderFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - } - - // - // Update Exists ... - if (HasOrderFlow()) - { - // - // Update to Times ... - UpdateToTime(orderFlow, TimeCurrent()); - - // - DrawOrderFlow(); - } - } - - // - // Zone ... - - // - XBoxZone support; - XBoxZone resistance; - bool drawZones; - bool drawSupport; - bool manageZones; - bool drawResistance; - - // - bool HasZones() - { - return HasSupport() || - HasResistance(); - } - - // - bool HasSupport() - { - return support.IsValid(); - } - - // - bool HasResistance() - { - return resistance.IsValid(); - } - - // - bool ValidateZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasZones(); - if (!result) - { - return result; - } - - // - // Support ... - bool hasSupport = HasSupport(); - if (hasSupport) - { - // - result = bar.close > support.lower && - !IsBreaked(support, X_PRICE_CLOSE); - if (!result) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.breakAt = bar.time; - support.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasResistance(); - if (hasResistance) - { - // - result = bar.close < resistance.upper && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!result) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.breakAt = bar.time; - resistance.Clean(); - } - } - - // - result = - (hasSupport && !HasSupport()) || - (hasResistance && !HasResistance()); - - // - return result; - } - - // - void DrawZones() - { - // - if (!drawZones || !HasZones()) - { - return; - } - - // - if (drawSupport && HasSupport()) - { - poiDrawer.DrawZone(support, structureDrawConfig.drawConfig); - } - - // - if (drawResistance && HasResistance()) - { - poiDrawer.DrawZone(resistance, structureDrawConfig.drawConfig); - } - } - - // - void ManageZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasZones()) - { - // - if (!ValidateZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(support.breakAt)) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - - // - support.Clean(); - } - - // - // Resistance ... - if (IsXValid(resistance.breakAt)) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - - // - resistance.Clean(); - } - } - } - - // - // Detect New ... - XOHCL tmpBar; - bool has = false; - - // - // Detect Support ... - if (!HasSupport()) - { - // - has = poiDetector.HasSupport( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToSupportBox(tmpBar, support, bar.time); - has = - has && - !IsBreaked(support, X_PRICE_CLOSE); - if (!has) - { - // - if (support.IsValid()) - { - // - iResistance = support; - iResistance.breakAt = NULL; - iResistance.dir = X_DIRECTION_BEARISH; - iResistance.to = bar.time + (PeriodSeconds(bar.period)); - iResistance.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - support.Clean(); - } - } - } - - // - // Detect Resistance ... - if (!HasResistance()) - { - // - has = poiDetector.HasResistance( - bar, - tmpBar, - structureConfig.barsAnalysisConfig.supportAndResistanceValidationLength, - structureConfig.barsAnalysisConfig.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToResistanceBox(tmpBar, resistance, bar.time); - has = - has && - !IsBreaked(resistance, X_PRICE_CLOSE); - if (!has) - { - // - if (resistance.IsValid()) - { - // - iSupport = resistance; - iSupport.breakAt = NULL; - iSupport.dir = X_DIRECTION_BULLISH; - iSupport.to = bar.time + (PeriodSeconds(bar.period)); - iSupport.from = bar.time - (PeriodSeconds(bar.period)); - } - - // - resistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasZones()) - { - // - if (HasSupport()) - { - // - support.to = bar.time; - support.type = "XFIMASup"; - } - - // - if (HasResistance()) - { - // - resistance.to = bar.time; - resistance.type = "XFIMARes"; - } - - // - DrawZones(); - } - - // - // Cleanup ... - tmpBar.Clean(); - } - - // - XBoxZone iSupport; - XBoxZone iResistance; - bool drawIZones; - bool drawISupport; - bool manageIZones; - bool drawIResistance; - - // - bool HasIZones() - { - // - return HasISupport() || - HasIResistance(); - } - - // - bool HasISupport() - { - return iSupport.IsValid(); - } - - // - bool HasIResistance() - { - return iResistance.IsValid(); - } - - // - void DrawIZones() - { - // - if (!drawIZones || !HasIZones()) - { - return; - } - - // - if (drawISupport && HasISupport()) - { - poiDrawer.DrawZone(iSupport, structureDrawConfig.drawConfig); - } - - // - if (drawIResistance && HasIResistance()) - { - poiDrawer.DrawZone(iResistance, structureDrawConfig.drawConfig); - } - } - - // - bool ValidateIZones(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasIZones(); - if (!result) - { - return result; - } - - // - - // - // Support ... - bool hasSupport = HasISupport(); - if (hasSupport) - { - // - result = bar.close > iSupport.lower && - !IsBreaked(iSupport, X_PRICE_CLOSE); - if (!result) - { - // - iSupport.breakAt = bar.time; - iSupport.Clean(); - } - } - - // - // Resistance ... - bool hasResistance = HasIResistance(); - if (hasResistance) - { - // - result = bar.close < iResistance.upper && - !IsBreaked(iResistance, X_PRICE_CLOSE); - if (!result) - { - // - iResistance.breakAt = bar.time; - iResistance.Clean(); - } - } - - // - result = - (hasSupport && !HasISupport()) || - (hasResistance && !HasIResistance()); - - // - return result; - } - - // - void ManageIZones(XOHCL &bar) - { - // - // Validate Exists ... - if (HasIZones()) - { - // - if (!ValidateIZones(bar)) - { - // - // Invalidate Zones ... - - // - // Support ... - if (IsXValid(iSupport.breakAt)) - { - iSupport.Clean(); - } - - // - // Resistance ... - if (IsXValid(iResistance.breakAt)) - { - iResistance.Clean(); - } - } - } - - // - // Update Exists ... - if (HasIZones()) - { - // - if (HasISupport()) - { - // - iSupport.to = bar.time; - iSupport.type = "XFIMAISup"; - } - - // - if (HasIResistance()) - { - // - iResistance.to = bar.time; - iResistance.type = "XFIMAIRes"; - } - - // - DrawIZones(); - } - } - - // - // Trends ... - - // - XTrend scTrend; - XTrend mcTrend; - XTrend lcTrend; - XTrend hcTrend; - - // - bool drawTrends; - bool drawSCTrend; - bool drawMCTrend; - bool drawLCTrend; - bool drawHCTrend; - bool manageTrends; - - // - bool HasTrend() - { - // - bool result = - HasSCTrend() || - HasMCTrend() || - HasLCTrend() || - HasHCTrend(); - - // - return result; - } - - // - bool HasSCTrend() - { - return scTrend.IsValid() && - scTrend.HasTrend(); - } - - // - bool HasMCTrend() - { - return mcTrend.IsValid() && - mcTrend.HasTrend(); - } - - // - bool HasLCTrend() - { - return lcTrend.IsValid() && - lcTrend.HasTrend(); - } - - // - bool HasHCTrend() - { - return hcTrend.IsValid() && - hcTrend.HasTrend(); - } - - // - void DrawTrends() - { - // - if (!drawTrends || !HasTrend()) - { - return; - } - - // - // SC ... - if (drawSCTrend && HasSCTrend()) - { - poiDrawer.DrawTrendLine(scTrend, structureDrawConfig.drawConfig); - } - - // - // MC ... - if (drawMCTrend && HasMCTrend()) - { - poiDrawer.DrawTrendLine(mcTrend, structureDrawConfig.drawConfig); - } - - // - // LC ... - if (drawLCTrend && HasLCTrend()) - { - poiDrawer.DrawTrendLine(lcTrend, structureDrawConfig.drawConfig); - } - - // - // HC ... - if (drawHCTrend && HasHCTrend()) - { - poiDrawer.DrawTrendLine(hcTrend, structureDrawConfig.drawConfig); - } - } - - // - void ManageTrends(XOHCL &bar) - { - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XTrend tmpTrend; - - // - // SC ... - tmpTrend.Clean(); - has = fimaParser.HasSCTrend(tmpTrend, bar.Index()); - if (has) - { - scTrend = tmpTrend; - } - - // - // MC ... - tmpTrend.Clean(); - has = fimaParser.HasMCTrend(tmpTrend, bar.Index()); - if (has) - { - mcTrend = tmpTrend; - } - - // - // LC ... - tmpTrend.Clean(); - has = fimaParser.HasLCTrend(tmpTrend, bar.Index()); - if (has) - { - lcTrend = tmpTrend; - } - - // - // HC ... - tmpTrend.Clean(); - has = fimaParser.HasHCTrend(tmpTrend, bar.Index()); - if (has) - { - hcTrend = tmpTrend; - } - - // - DrawTrends(); - - // - // Cleanup ... - tmpTrend.Clean(); - } - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Configuration Flags ... - - // - // Signaller Flags ... - bool useSignaller1 = false; - bool useSignaller2 = true; - bool useSignaller3 = true; - bool useSignaller4 = true; - - // - // Validator Flags ... - string provider = NULL; - bool validateByOrderFlow = false; - - // - // Target Flags ... - bool hasPartialCloseOnTp1 = false; - - // - bool doRFOnEntryOnTP1 = false; - - // - // Draw Flags ... - bool draw = true; - bool drawZone = true; - bool drawMarketStructurePivots = false; - bool drawMarketStructureAnalysis = false; - bool drawMarketStructureOrderFlow = false; - XPOIDrawConfig iDrawConfig; - - // - drawLeg = false; - drawZones = false; - drawIZones = false; - drawTrends = false; - drawSCTrend = false; - drawMCTrend = false; - drawLCTrend = false; - drawHCTrend = false; - drawSupport = false; - drawISupport = false; - drawOrderFlow = false; - drawResistance = false; - drawIResistance = false; - - // - // Signal Checking ... - - // - // Analyse Market Strucutre ... - XFIMAMarketStructure marketStructure; - - // - // Signaller 1 ... - if (!result && useSignaller1) - { - // - result = Strategy1HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "1"; - } - } - - // - // Signaller 2 ... - if (!result && useSignaller2) - { - // - result = Strategy2HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "2"; - } - } - - // - // Signaller 3 ... - if (!result && useSignaller3) - { - // - result = Strategy3HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "3"; - } - } - - // - // Signaller 4 ... - if (!result && useSignaller4) - { - // - result = Strategy4HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "4"; - } - } - - // - // Signal Validating ... - - // - // Validate Signals by Order Flow ... - if (result && validateByOrderFlow) - { - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - - // - bool isBullish = IsXBullish(dir) && - marketStructure.HasBullishOrderFlow(); - - // - bool isBearish = IsXBearish(dir) && - marketStructure.HasBearishOrderFlow(); - - // - // Summarizing result ... - result = isBullish || - isBearish; - } - - // - // Targets, Restrictions and Risk Management ... - if (result) - { - // - // Requirements ... - XTarget iTarget; - - // - // Checking Direction of Signal ... - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, dir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? zone.lower - slAddition - : zone.upper + slAddition; - - // - // Calculate Risk ... - double risk = MathAbs(entry - sl); - - // - // Calculate Reward ... - double reward = defaultSignalR2R * risk; - - // - // Calculate TP1 ... - double tp1 = isBullish - ? entry + risk - : entry - risk; - double tp2 = isBullish - ? entry + (2 * risk) - : entry - (2 * risk); - - // - // Calculate TP ... - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Check Max Allowed Risk ... - bool hasTooMuchRisk = maxAllowedRiskDistance <= 0 - ? false - : risk >= (maxAllowedRiskDistance * points); - if (hasTooMuchRisk) - { - // - // Clean Signal if Too much Risk ... - zone.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Common Targets ... - - // - // Partial Close on TP 1 ... - if (hasPartialCloseOnTp1) - { - // - iTarget.Clean(); - iTarget.target = tp1; - iTarget.actingDistance = 5; - iTarget.volumeMultiplier = 0.8; - iTarget.doRFOnEntry = doRFOnEntryOnTP1; - - // - AddRef(iTarget, targets); - } - - // - // Custom Signaller Targets ... - - // - // Restrictions Handling ... - if (risk > 0 && HasRestrictions()) - { - // - // Reset Restricitons if necessary ... - ResetRestrictions(); - - // - // Handle Custom Restrictions Senario ... - } - - // - // Ignore Targets ... - if (ignoreTargets) - { - XClean(targets); - } - - // - // Summarize Result ... - result = zone.IsValid() && - HasDirection(dir); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Draws ... - if (result && draw) - { - // - // Prepare Draw Config ... - iDrawConfig = structureDrawConfig.drawConfig; - iDrawConfig.zonesWidth = 3; - iDrawConfig.zonesStyle = STYLE_DASH; - iDrawConfig.bullishColor = clrYellow; - iDrawConfig.bearishColor = clrDarkOrange; - - // - // Draw Zone ... - if (drawZone) - { - poiDrawer.DrawZone(zone, iDrawConfig); - } - - // - // Draw Market Structure ... - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - if (marketStructure.IsValid()) - { - // - // Order Flow ... - if (drawMarketStructureOrderFlow && marketStructure.HasOrderFlow()) - { - poiDrawer.DrawZones(marketStructure.orderFlow, iDrawConfig); - } - - // - // Pivots ... - if (drawMarketStructurePivots) - { - // - XPivot pivots[]; - int pivotsCount = marketStructure.CollectPivots( - pivots, - true // Contains Patterns ... - ); - if (IsValidSize(pivotsCount)) - { - poiDrawer.DrawPivots(pivots, iDrawConfig); - } - - // - XClean(pivots); - } - - // - // Analysis ... - if (drawMarketStructureAnalysis) - { - // - } - } - - // - // Other Drawing Materials ... - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - - // - // Cleanup ... - iDrawConfig.Clean(); - marketStructure.Clean(); - - // - return result; - } - - // - // Custom Signal Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Reading Conditions ... - int pullBackStartBar = -1; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - zone, - dir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(dir); - bool isPullbackBearish = isPullBack && - IsXBearish(dir); - if (isPullBack) - { - pullBackStartBar = zone.FromIndex(); - } - - // - // Reading HK Band ... - - // - double pHKBandUpper = fimaHelper.GetHKBandUpper(pBar.Index()); - double pHKBandLower = fimaHelper.GetHKBandLower(pBar.Index()); - int overHKBandUpperCount = fimaParser.CountOverHKBandUpper(pullBackStartBar, X_PRICE_LOW); - int underHKBandLowerCount = fimaParser.CountUnderHKBandLower(pullBackStartBar, X_PRICE_HIGH); - - // - // Reading PV Requirements ... - - // - int lastPeakOverLastIDX = -1; - int lastValeUnderLastIDX = -1; - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - int samePeaks = fimaParser.CountSamePeaks(pBar.Index()); - int sameVales = fimaParser.CountSameVales(pBar.Index()); - fimaParser.FindLastPeakOverLast(lastPeakOverLastIDX, pBar.Index()); - fimaParser.FindLastValeUnderLast(lastValeUnderLastIDX, pBar.Index()); - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - - // - // Try To Find Affected Zone ... - - // - // Collecting Zones ... - XBoxZone zones[]; - XBoxZone affectedZones[]; - XBoxZone affectedZonesBullish[]; - XBoxZone affectedZonesBearish[]; - int zonesCount = poiDetector.CollectZones( - pBar, - zones, // - 5, // Zones Loopback ... - 3 // Zones Validation Length ... - // Required Zones ... - // Loopback ... - ); - int affectedZonesCount = ExtractAffectedZones( - pBar, - zones, - affectedZones // - ); - int affectedZonesBullishCount = ExtractByDirection( - affectedZonesBullish, - affectedZones, - X_DIRECTION_BULLISH // - ); - int affectedZonesBearishCount = ExtractByDirection( - affectedZonesBearish, - affectedZones, - X_DIRECTION_BEARISH // - ); - - // - int insideBullishIDX = -1; - int insideBearishIDX = -1; - bool hasBullishInside = - pBar.IsBullish() && - HasInside( - insideBullishIDX, - pBar, - affectedZonesBullish // - ); - bool hasBearishInside = - pBar.IsBearish() && - HasInside( - insideBearishIDX, - pBar, - affectedZonesBearish // - ); - - // - // Do ... - - // - isBullish = - // - hasBullishInside && - isPullbackBullish && - isPBarHasBullishPatterns && - fimaParser.IsSARBullish(pBar.Index()) && - (pVale >= affectedZonesBullish[insideBullishIDX].lower && - pVale <= affectedZonesBullish[insideBullishIDX].upper) - // - ; - - // - isBearish = - // - hasBearishInside && - isPullbackBearish && - isPBarHasBearishPatterns && - fimaParser.IsSARBearish(pBar.Index()) && - (pPeak >= affectedZonesBearish[insideBearishIDX].lower && - pPeak <= affectedZonesBearish[insideBearishIDX].upper) - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - if (isBullish) - { - zone = affectedZonesBullish[insideBullishIDX]; - } - else - { - zone = affectedZonesBearish[insideBearishIDX]; - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - XClean(zones); - pBarAnalysis.Clean(); - XClean(affectedZones); - XClean(affectedZonesBullish); - XClean(affectedZonesBearish); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - double peak = fimaHelper.GetPeak(bar.Index()); - double vale = fimaHelper.GetVale(bar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - double p2Peak = fimaHelper.GetPeak(p2Bar.Index()); - double p2Vale = fimaHelper.GetVale(p2Bar.Index()); - bool isPPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isPValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - bool isP2PeakOverLast = fimaParser.IsPeakOverLast(p2Bar.Index()); - bool isP2ValeUnderLast = fimaParser.IsValeUnderLast(p2Bar.Index()); - bool isPeakOverLast = isPPeakOverLast || - isP2PeakOverLast; - bool isValeUnderLast = isPValeUnderLast || - isP2ValeUnderLast; - bool isP2ValeOverLast = pVale > p2Vale; - bool isP2PeakUnderLast = pPeak < p2Peak; - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - bool isFastOverLast = fimaHelper.GetMAFast(pBar.Index()) > fimaHelper.GetMAFast(p2Bar.Index()); - bool isFastUnderLast = fimaHelper.GetMAFast(pBar.Index()) < fimaHelper.GetMAFast(p2Bar.Index()); - - // - // Force P2Bar is Pin Bar ... - ENUM_X_DIRECTION p2Dir; - bool isP2BarPinned = poiDetector.IsPinnedBar( - p2Bar, - p2Dir // - ); - bool isP2BarBullishPinned = - isP2BarPinned && - IsXBullish(p2Dir); - bool isP2BarBearishPinned = - isP2BarPinned && - IsXBearish(p2Dir); - - // - // Do ... - - // - isBullish = - // - isFastOverLast && - isValeUnderLast && - !isP2PeakUnderLast && - isPBarCloseOverFast && - isP2BarBullishPinned && - isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - isPeakOverLast && - isFastUnderLast && - !isP2ValeOverLast && - isPBarCloseUnderFast && - isP2BarBearishPinned && - isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Manage Stops ... - if (result) - { - // - double entry = GetEntry(zone.symbol, zone.dir); - double riskSide = zone.IsBullish() ? zone.lower : zone.upper; - double risk = MathAbs(entry - riskSide); - - // - // Collecting Affected Zones ... - XBoxZone tmps[]; - XBoxZone zones[]; - XBoxZone actedZones[]; - XBoxZone insideZones[]; - XBoxZone breakedZones[]; - XBoxZone affectedZones[]; - - // - // Support and Resistances ... - poiDetector.CollectZones(bar, tmps); - Copy(tmps, zones, false); - - // - // OBS ... - poiDetector.CollectOBs(bar, tmps); - Copy(tmps, zones, false); - - // - // FVGs ... - poiDetector.CollectFVGs(bar, tmps); - Copy(tmps, zones, false); - - // - ExtractAffectedZones(bar, zones, affectedZones); - - // - // Acteds Zones ... - ExtractActeds(bar, actedZones, affectedZones); - - // - // Inside Zones ... - ExtractInsides(bar, insideZones, affectedZones); - - // - // Breaked Zones ... - ExtractBreakeds(bar, breakedZones, affectedZones); - - // - // Cleanup ... - XClean(tmps); - XClean(zones); - XClean(actedZones); - XClean(insideZones); - XClean(breakedZones); - XClean(affectedZones); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * Strategy 3: - * =========== - * - Works Based On Breaked Support or Resistances ... - * - Looking for a Support or Resistance to Breaked ... - * - Validate Breaker Bar to Change Peak or Vale ... - * - Validate Bar Opposit Side of Breaker Bar's Shadow ... - * - Validate by Checking Market Strucutre to Has Directional Zone - * (Support for Resistance Break / Resistance for Support Break) ... - * - Validate Breaker Bar to Has Directional FVG ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - - // - bool validateByPVChanges = true; - bool validateByGapExists = true; - bool validateByBarShadows = true; - bool validateHasDirectionalZone = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XBoxZone _fvg; - XBoxZone _support; - XBoxZone _resistance; - XPatternAnalysis pBarPatterns; - XPatternAnalysis p2BarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - poiDetector.AnalyseBarPatterns( - p2Bar, - p2BarPatterns, - patternConfig // - ); - - // - // Price Must Break Support or Resistance ... - - // - // Extract Support and Resistance ... - bool hasSupport = p2BarPatterns.IsSupport(); - bool hasResistance = p2BarPatterns.IsResistance(); - if (hasSupport) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasSupport = p2BarPatterns.GetSupport(tmpBar, tmpPivot, _support); - tmpBar.Clean(); - tmpPivot.Clean(); - } - if (hasResistance) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - hasResistance = p2BarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - tmpBar.Clean(); - tmpPivot.Clean(); - } - - // - bool hasBreakedSupport = hasSupport && - pBar.close < _support.lower && - p2Bar.close > _support.lower; - bool hasBreakedResistance = hasResistance && - pBar.close > _resistance.upper && - p2Bar.close < _resistance.upper; - - // - isBullish = hasBreakedResistance; - isBearish = hasBreakedSupport; - - // - result = isBullish || isBearish; - - // - // Validate By PV Changed ... - // Breaker Bar must Change Peak or Value ... - if (result && validateByPVChanges) - { - // - bool isPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - - // - isBullish = - isBullish && - isPeakOverLast; - - // - isBearish = - isBearish && - isValeUnderLast; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate by Bar Shadows ... - // Breakre Bar Side Shadow must not Reached ... - if (result && validateByBarShadows) - { - // - isBullish = - isBullish && - pBar.low > p2Bar.low; - - // - isBearish = - isBearish && - pBar.high < p2Bar.high; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Has Directional Zone ... - if (result && validateHasDirectionalZone) - { - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate By Gap Exists ... - if (result && validateByGapExists) - { - // - ENUM_X_DIRECTION tmpDir; - bool hasFVG = poiDetector.HasFVG( - pBar, - tmpDir, - _fvg // - ); - - // - isBullish = - isBullish && - hasFVG && - IsXBullish(tmpDir); - - // - isBearish = - isBearish && - hasFVG && - IsXBearish(tmpDir); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Prepare Direction and Zone ... - if (result) - { - // - if (isBullish) - { - // - zone = _resistance; - zone.dir = Opposit(_resistance.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - if (isBearish) - { - // - zone = _support; - zone.dir = Opposit(_support.dir); - dir = zone.dir; - zone.upper = MathMax(zone.upper, _fvg.upper); - zone.lower = MathMin(zone.lower, _fvg.lower); - } - - // - // Zone Validation Base ... - result = zone.IsValid(); - if (result) - { - // - // Validate By Trend of Zone ... - XTrend zoneTrend; - XTrend zoneToTrend; - - // - // Detecting Trends ... - result = poiDetector.HasBoundaryTrend(zone, zoneTrend, false); - result = result && - poiDetector.HasBoundaryTrend(zone, zoneToTrend, true); - - // - // Validate Trend ... - result = - result && - zone.dir == zoneTrend.dir && - zone.dir == zoneToTrend.dir; - - // - // Draw ... - if (result) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - iConfig.trendRayLeft = false; - iConfig.trendRayRight = false; - - // - poiDrawer.DrawTrendLine(zoneTrend, iConfig); - poiDrawer.DrawTrendLine(zoneToTrend, iConfig); - - // - iConfig.Clean(); - } - - // - // Cleanup ... - zoneTrend.Clean(); - zoneToTrend.Clean(); - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - isBullish = false; - isBearish = false; - } - } - - // - result = zone.IsValid(); - } - - // - if (result) - { - // - if (_support.IsValid()) - { - poiDrawer.DrawZone(_support, structureDrawConfig.drawConfig); - } - - // - if (_resistance.IsValid()) - { - poiDrawer.DrawZone(_resistance, structureDrawConfig.drawConfig); - } - - // - if (pBarPatterns.IsValid()) - { - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - } - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - pBarPatterns.Clean(); - p2BarPatterns.Clean(); - patternConfig.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * Strategy 4: - * =========== - * - Works Based on Order Flow ... - * - Looking for new and Fresh Order Flow ... - * - Validate Bar is Inside Order Flow ... - * - Validate Bar has Proper Pattern ... - * - Validate Bar Based on ATR Band in two Step: - * - Step 1: Bars is Inside ATR Band (Middle) ... - * - Step 2: Trigger Bars Close Price based on ATR Band ... - * - Validate Order Flow based on Market Structure Zone ... - * - Validate Trigger Bar based on InDirectional Market Structure Zones ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateBarInsideZone = true; - bool validateByBarPatterns = true; - bool validateByXFIMABoundary = true; - bool validateByBarInsideATRBand = true; - bool validateByBarBasedOnATRBand = true; - bool validateByXFIMABoundaryTrend = true; - bool validateMarketStructureHasDirectionalZone = true; - bool validateMarketStructureDirectionalZoneInsideOrderFlow = true; - bool validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - - // - // Detecting OrderFlow ... - XBoxZone oFlow[]; - bool hasOrderFlow = poiDetector.HasOrderFlow( - p3Bar, - dir, - oFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - - // - XTrend boundaryTrend; - XTrend boundaryZoneTrend; - - // - double atrBandUpper = EMPTY_VALUE; - double atrBandLower = EMPTY_VALUE; - double atrBandMiddle = EMPTY_VALUE; - - // - isBullish = hasOrderFlow && - IsXBullish(dir); - - // - isBearish = hasOrderFlow && - IsXBearish(dir); - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Force Price of p2Bar is Inside Order Flow ... - if (result && validateBarInsideZone) - { - // - double orderFlowUpper = 0; - double orderFlowLower = 0; - - // - int idx = -1; - idx = GetHighest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowUpper = oFlow[idx].upper; - } - idx = GetLowest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowLower = oFlow[idx].lower; - } - - // - result = NotEmptyZero(orderFlowUpper) && - NotEmptyZero(orderFlowLower) && - orderFlowUpper > orderFlowLower && - (isBullish - ? p2Bar.low < orderFlowUpper - : p2Bar.high > orderFlowLower); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Has Pattern ... - if (result && validateByBarPatterns) - { - // - // Analyse Bar Patterns ... - result = pBarPatterns.IsValid(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - result && - // (bar.close > pBar.low || - // bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - result && - // (bar.close < pBar.high || - // bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force P2Bar Place Checking based on ATR Band ... - if (result && validateByBarInsideATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(p2Bar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(p2Bar.Index()); - - // - atrBandMiddle = atrBandLower + ((atrBandUpper - atrBandLower) / 2); - - // - isBullish = - isBullish && - NotEmptyZero(atrBandMiddle) && - p2Bar.low < atrBandMiddle; - - // - isBearish = - isBearish && - NotEmptyZero(atrBandMiddle) && - p2Bar.high > atrBandMiddle; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Place Checking based on ATR Band ... - if (result && validateByBarBasedOnATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(pBar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(pBar.Index()); - - // - result = - NotEmptyZero(atrBandUpper) && - NotEmptyZero(atrBandLower) && - (isBullish - ? pBar.close > atrBandLower - : pBar.close < atrBandUpper); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // for Bullish has Support ... - // for Bearish has Resistance ... - if (result && validateMarketStructureHasDirectionalZone) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Validate Support and Resistance by Order Flow ... - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - // Check Market Strucutre Support and Resistance Validation ... - if (validateMarketStructureDirectionalZoneInsideOrderFlow) - { - // - hasSupport = - hasOFBox && - hasSupport && - ofZone.lower < _support.lower && - ofZone.upper > _support.upper; - - // - hasResistance = - hasOFBox && - hasResistance && - ofZone.lower < _resistance.lower && - ofZone.upper > _resistance.upper; - } - - // - // Validate Directional Support or Resistance Exists ... - - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Makret Structure Has Not Indirectional Zone ... - if (result && validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone _support; - XBoxZone _resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, _support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, _resistance); - } - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - bool hasIndirectionalZone = - (isBullish && hasResistance) || - (isBearish && hasSupport); - if (hasIndirectionalZone) - { - // - // Here we Have to Validate Zone Place ... - - // - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? oFlow[0].lower : oFlow[0].upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Bullish ... - if (isBullish && hasResistance) - { - hasResistance = _resistance.lower <= tp; - } - - // - // Bearish ... - if (isBearish && hasSupport) - { - hasSupport = _support.upper >= tp; - } - } - - // - isBullish = - isBullish && - !hasResistance; - - // - isBearish = - isBearish && - !hasSupport; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - _support.Clean(); - tmpPivot.Clean(); - _resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate ... - result = isBullish || isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone and do Zone Based Validations ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Refine Zone ... - zone.to = bar.time; - zone.upper = MathMax(zone.upper, atrBandMiddle); - zone.lower = MathMin(zone.lower, atrBandMiddle); - - // - // Validate by XFIMA Boundary ... - if (result && validateByXFIMABoundary) - { - // - // Try to Retrieve Boundary To Trend ... - result = poiDetector.HasBoundaryTrend( - zone, - boundaryTrend, - true // - ); - - // - // Try to Retrieve Boundary Zone Trend ... - result = - result && - poiDetector.HasBoundaryTrend( - zone, - boundaryZoneTrend, - false // - ); - - // - // Check and Validate Trend Direction ... - result = - result && - zone.dir == boundaryTrend.dir && - zone.dir == boundaryZoneTrend.dir; - - // - // Reset Flags ... - if (!result) - { - // - zone.Clean(); - result = false; - isBullish = false; - isBearish = false; - } - } - - // - // Manage Stops ... - if (result) - { - // - // Since Stop Management Changes Zones Edge(s) ... - // we do it here for Refining Zone ... - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - XTarget iTarget; - - // - // Calculate Requirements ... - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? zone.lower : zone.upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // High Risk Target is Used to Protect In Profit Positiions - // from Reversal Patterns ... - double highRiskR2r = (defaultSignalR2R / 5) * 4; - double highRiskReward = highRiskR2r * risk; - double highRiskTP = isBullish - ? entry + highRiskReward - : entry - highRiskReward; - iTarget.Clean(); - iTarget.actingDistance = 5; - iTarget.doRFOnEntry = true; - iTarget.target = highRiskTP; - iTarget.volumeMultiplier = 0.8; - // AddRef(iTarget, targets); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(oFlow); - pBarPatterns.Clean(); - boundaryTrend.Clean(); - patternConfig.Clean(); - boundaryZoneTrend.Clean(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class.mq5 b/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class.mq5 deleted file mode 100644 index 5d1c13bb..00000000 --- a/Documents/BKP/XFIMA Signals/x-saherelm.xfima.signaller.class.mq5 +++ /dev/null @@ -1,2621 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.parser.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - CArrayObj drawnObjects; // Drawing Objects Holder ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAHelperParser *fimaParser; // XFIMA Helper Parser ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - XFIMAMarketStructureConfig structureConfig; // XFIMA Market Structure Detector Config ... - XFIMAMarketStructureDrawerConfig structureDrawConfig; // XFIMA Market Structure Draw Config ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - // Instantiate XFIMA Helper Parser ... - fimaParser = new XCXFIMAHelperParser(fimaHelper); - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper, fimaParser); - - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - structureConfig.Clean(); - structureDrawConfig.Clean(); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure ... - drawLeg = true; - drawOrderFlow = true; - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Manage ... - Manage(iBar); - - // - // Strategy X ... - has = HasSignal( - iBar, - iZone, - iTargets, - iDir // - ); - - // - // Handle Resting Signals ... - has = HasDirection(iDir) && - iZone.IsValid(); - - // - // Prepare Signal ... - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, iDir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Signal ... - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - sl, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - } - - // - // Notify On Signal Event ... - if (has) - { - NotifySignalEventListeners(iSignal); - } - - // - // Cleanup ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - XClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - XClean(guards); - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Requirements ... - XGuard iGuard; - bool has = false; - - // - // Force Hedging ... - // bool forceHedging = (positionsCount >= 2); - // if (forceHedging) - // { - // // - // // Minimum Required Reward ... - // double minRequiredReward = 1.5; - - // // - // // Summarizing Risk and Reward of Collections ... - // // double risk = 0; - // // double volume = 0; - // // double reward = 0; - // // for (int i = 0; i < positionsCount; i++) - // // { - // // // - // // risk += positions[i].GetRisk() + positions[i].commission + (-1 * positions[i].swap); - // // reward += positions[i].profit; - // // volume += positions[i].volume; - // // } - - // // // - // // risk *= volume; - // // reward *= volume; - - // // // - // // // Calculating Can Hedge rops ... - // // has = reward >= (risk * minRequiredReward); - // // if (has) - // // { - // // // - // // iGuard.Clean(); - // // iGuard.force = true; - // // iGuard.symbol = symbol; - // // iGuard.period = period; - // // iGuard.provider = name; - // // iGuard.time = TimeCurrent(); - // // iGuard.action = X_GUARD_ACTION_HEDGE; - - // // // - // // // Validate Guard ... - // // has = iGuard.IsValid(); - // // if (has) - // // { - // // // - // // AddRef( - // // iGuard, - // // guards // - // // ); - // // } - // // } - // } - - // - result = ArraySize(guards); - - // - // Cleanup ... - iGuard.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - void Manage(XOHCL &bar) - { - // - bool has = bar.IsValid(); - if (!has) - { - return; - } - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - has = bar.GetPreviousBar(pBar); - has = has && - pBar.GetPreviousBar(p2Bar); - has = has && - p2Bar.GetPreviousBar(p3Bar); - if (!has) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - ManageLeg(bar); - ManageOrderFlow(p3Bar); - - // - // Cleanup ... - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - } - - // - // Private ... - private: - // - // Props ... - - // - // Leg ... - - XLeg leg; // Exists Leg ... - bool drawLeg; // Draw Leg ... - - // - bool HasLeg() - { - return leg.IsValid(); - } - - // - bool ValidateLeg(XOHCL &bar) - { - // - bool result = false; - - // - result = HasLeg() && - bar.IsValid(); - if (!result) - { - return result; - } - - // - result = - leg.IsBullish() - ? bar.low > leg.lower - : leg.IsBearish() - ? bar.high < leg.upper - : false; - - // - return result; - } - - // - void DrawLeg() - { - // - if (!drawLeg) - { - return; - } - - // - if (!HasLeg()) - { - return; - } - - // - // Update to Times ... - leg.UpdateTimes(); - - // - // Draw Leg Box ... - XBoxZone legZone; - leg.ToBox(legZone); - if (legZone.IsValid()) - { - // - legZone.to = TimeCurrent(); - poiDrawer.DrawZone(legZone, structureDrawConfig.drawConfig); - } - - // - // Draw Legs Other Stufs ... - return; - - // - // FVGs ... - poiDrawer.DrawZones(leg.bullishFVGs, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.bearishFVGs, structureDrawConfig.drawConfig); - - // - // Support and Resistances ... - poiDrawer.DrawZones(leg.supports, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.resistances, structureDrawConfig.drawConfig); - - // - // Patterns ... - poiDrawer.DrawPatternAnalysises(leg.patterns, structureDrawConfig.barAnalysisDrawConfig); - } - - // - void ManageLeg(XOHCL &bar) - { - // - // Validate Exists ... - if (HasLeg()) - { - // - if (!ValidateLeg(bar)) - { - // - // Invalidate XLeg ... - leg.Clean(); - } - } - - // - // Detect New ... - if (!HasLeg()) - { - poiDetector.IsLegPattern(bar, leg); - } - - // - // Update Exists ... - if (HasLeg()) - { - // - // Update to Times ... - leg.UpdateTimes(); - - // - DrawLeg(); - } - } - - // - // Order Flow ... - - // - bool drawOrderFlow; - XBoxZone orderFlow[]; - ENUM_X_DIRECTION orderFlowDir; - - // - bool HasOrderFlow() - { - // - return HasChild(orderFlow) && - HasDirection(orderFlowDir); - } - - bool HasBullishOrderFlow() - { - return HasOrderFlow() && - IsXBullish(orderFlowDir); - } - - bool HasBearishOrderFlow() - { - return HasOrderFlow() && - IsXBearish(orderFlowDir); - } - - bool GetOrderFlowBoundary( - double &upper, - double &lower // - ) - { - // - bool result = false; - - // - // Prepare ... - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - - // - // Validate ... - result = HasOrderFlow(); - if (!result) - { - return result; - } - - // - int idx = -1; - - // - // Upper ... - idx = GetHighest(orderFlow); - if (IsValidIndex(idx)) - { - upper = orderFlow[idx].upper; - } - - // - // Lower ... - idx = GetLowest(orderFlow); - if (IsValidIndex(idx)) - { - lower = orderFlow[idx].lower; - } - - // - result = NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - // Cleanup ... - if (!result) - { - // - upper = EMPTY_VALUE; - lower = EMPTY_VALUE; - } - - // - return result; - } - - bool ValidateOrderFlow(XOHCL &bar) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasOrderFlow(); - if (!result) - { - return result; - } - - // - double upper = EMPTY_VALUE; - double lower = EMPTY_VALUE; - result = GetOrderFlowBoundary(upper, lower); - result = result && - HasBullishOrderFlow() - ? bar.low > lower - : bar.high < upper; - - // - return result; - } - - void DrawOrderFlow() - { - // - if (!drawOrderFlow || !HasOrderFlow()) - { - return; - } - - // - poiDrawer.DrawZones(orderFlow, structureDrawConfig.drawConfig); - } - - void ManageOrderFlow(XOHCL &bar) - { - // - // Validate Exists ... - if (HasOrderFlow()) - { - // - if (!ValidateOrderFlow(bar)) - { - // - // Invalidate OrderFlow ... - XClean(orderFlow); - orderFlowDir = X_DIRECTION_NONE; - } - } - - // - // Detect New ... - if (!HasOrderFlow()) - { - // - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - // patternConfig.Default(); - // patternConfig.supportAndResistanceLoopbackLength = 21; - // patternConfig.supportAndResistanceValidationLength = 7; - - // - poiDetector.HasOrderFlow( - bar, - orderFlowDir, - orderFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - } - - // - // Update Exists ... - if (HasOrderFlow()) - { - // - // Update to Times ... - UpdateToTime(orderFlow, TimeCurrent()); - - // - DrawOrderFlow(); - } - } - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Configuration Flags ... - - // - // Signaller Flags ... - bool useSignaller1 = false; - bool useSignaller2 = false; - bool useSignaller3 = false; - bool useSignaller4 = true; - - // - // Validator Flags ... - string provider = NULL; - bool validateByOrderFlow = false; - - // - // Target Flags ... - bool hasPartialCloseOnTp1 = false; - - // - bool doRFOnEntryOnTP1 = false; - - // - // Draw Flags ... - bool draw = true; - bool drawZone = true; - bool drawMarketStructurePivots = true; - bool drawMarketStructureAnalysis = true; - bool drawMarketStructureOrderFlow = true; - XPOIDrawConfig iDrawConfig; - - // - drawLeg = false; - drawOrderFlow = false; - - // - // Signal Checking ... - - // - // Analyse Market Strucutre ... - XFIMAMarketStructure marketStructure; - - // - // Check Market ... - // result = HasLeg() && - // HasOrderFlow() && - // orderFlowDir == leg.dir; - // result = HasBearishOrderFlow(); - // if (result) - // { - // // - // result = false; - // DebugBreak(); - // } - - // - // Signaller 1 ... - if (!result && useSignaller1) - { - // - result = Strategy1HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "1"; - } - } - - // - // Signaller 2 ... - if (!result && useSignaller2) - { - // - result = Strategy2HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "2"; - } - } - - // - // Signaller 3 ... - if (!result && useSignaller3) - { - // - result = Strategy3HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "3"; - } - } - - // - // Signaller 4 ... - if (!result && useSignaller4) - { - // - result = Strategy4HasSignal( - bar, - zone, - targets, - dir // - ); - - // - if (result) - { - provider = "4"; - } - } - - // - // Signal Validating ... - - // - // Validate Signals by Order Flow ... - if (result && validateByOrderFlow) - { - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - - // - bool isBullish = IsXBullish(dir) && - marketStructure.HasBullishOrderFlow(); - - // - bool isBearish = IsXBearish(dir) && - marketStructure.HasBearishOrderFlow(); - - // - // Summarizing result ... - result = isBullish || - isBearish; - } - - // - // Targets, Restrictions and Risk Management ... - if (result) - { - // - // Requirements ... - XTarget iTarget; - - // - // Checking Direction of Signal ... - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, dir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? zone.lower - slAddition - : zone.upper + slAddition; - - // - // Calculate Risk ... - double risk = MathAbs(entry - sl); - - // - // Calculate Reward ... - double reward = defaultSignalR2R * risk; - - // - // Calculate TP1 ... - double tp1 = isBullish - ? entry + risk - : entry - risk; - double tp2 = isBullish - ? entry + (2 * risk) - : entry - (2 * risk); - - // - // Calculate TP ... - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Check Max Allowed Risk ... - bool hasTooMuchRisk = maxAllowedRiskDistance <= 0 - ? false - : risk >= (maxAllowedRiskDistance * points); - if (hasTooMuchRisk) - { - // - // Clean Signal if Too much Risk ... - zone.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Common Targets ... - - // - // Partial Close on TP 1 ... - if (hasPartialCloseOnTp1) - { - // - iTarget.Clean(); - iTarget.target = tp1; - iTarget.actingDistance = 5; - iTarget.volumeMultiplier = 0.8; - iTarget.doRFOnEntry = doRFOnEntryOnTP1; - - // - AddRef(iTarget, targets); - } - - // - // Custom Signaller Targets ... - - // - // Restrictions Handling ... - if (risk > 0 && HasRestrictions()) - { - // - // Reset Restricitons if necessary ... - ResetRestrictions(); - - // - // Handle Custom Restrictions Senario ... - } - - // - // Ignore Targets ... - if (ignoreTargets) - { - XClean(targets); - } - - // - // Summarize Result ... - result = zone.IsValid() && - HasDirection(dir); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Draws ... - if (result && draw) - { - // - // Prepare Draw Config ... - iDrawConfig = structureDrawConfig.drawConfig; - iDrawConfig.zonesWidth = 3; - iDrawConfig.zonesStyle = STYLE_DASH; - iDrawConfig.bullishColor = clrYellow; - iDrawConfig.bearishColor = clrDarkOrange; - - // - // Draw Zone ... - if (drawZone) - { - poiDrawer.DrawZone(zone, iDrawConfig); - } - - // - // Draw Market Structure ... - // - // Analyse Market Structure if Required ... - if (!marketStructure.IsValid()) - { - // - poiDetector.AnalyseMarket( - marketStructure, - structureConfig, - bar.Index() // - ); - } - if (marketStructure.IsValid()) - { - // - // Order Flow ... - if (drawMarketStructureOrderFlow && marketStructure.HasOrderFlow()) - { - poiDrawer.DrawZones(marketStructure.orderFlow, iDrawConfig); - } - - // - // Pivots ... - if (drawMarketStructurePivots) - { - // - XPivot pivots[]; - int pivotsCount = marketStructure.CollectPivots( - pivots, - true // Contains Patterns ... - ); - if (IsValidSize(pivotsCount)) - { - poiDrawer.DrawPivots(pivots, iDrawConfig); - } - - // - XClean(pivots); - } - - // - // Analysis ... - if (drawMarketStructureAnalysis) - { - // - } - } - - // - // Other Drawing Materials ... - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - - // - // Debug Breake ... - if (result) - { - DebugBreak(); - } - - // - // Cleanup ... - iDrawConfig.Clean(); - marketStructure.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Reading Conditions ... - int pullBackStartBar = -1; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - zone, - dir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(dir); - bool isPullbackBearish = isPullBack && - IsXBearish(dir); - if (isPullBack) - { - pullBackStartBar = zone.FromIndex(); - } - - // - // Reading HK Band ... - - // - double pHKBandUpper = fimaHelper.GetHKBandUpper(pBar.Index()); - double pHKBandLower = fimaHelper.GetHKBandLower(pBar.Index()); - int overHKBandUpperCount = fimaParser.CountOverHKBandUpper(pullBackStartBar, X_PRICE_LOW); - int underHKBandLowerCount = fimaParser.CountUnderHKBandLower(pullBackStartBar, X_PRICE_HIGH); - - // - // Reading PV Requirements ... - - // - int lastPeakOverLastIDX = -1; - int lastValeUnderLastIDX = -1; - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - int samePeaks = fimaParser.CountSamePeaks(pBar.Index()); - int sameVales = fimaParser.CountSameVales(pBar.Index()); - fimaParser.FindLastPeakOverLast(lastPeakOverLastIDX, pBar.Index()); - fimaParser.FindLastValeUnderLast(lastValeUnderLastIDX, pBar.Index()); - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - - // - // Try To Find Affected Zone ... - - // - // Collecting Zones ... - XBoxZone zones[]; - XBoxZone affectedZones[]; - XBoxZone affectedZonesBullish[]; - XBoxZone affectedZonesBearish[]; - int zonesCount = poiDetector.CollectZones( - pBar, - zones, // - 5, // Zones Loopback ... - 3 // Zones Validation Length ... - // Required Zones ... - // Loopback ... - ); - int affectedZonesCount = ExtractAffectedZones( - pBar, - zones, - affectedZones // - ); - int affectedZonesBullishCount = ExtractByDirection( - affectedZonesBullish, - affectedZones, - X_DIRECTION_BULLISH // - ); - int affectedZonesBearishCount = ExtractByDirection( - affectedZonesBearish, - affectedZones, - X_DIRECTION_BEARISH // - ); - - // - int insideBullishIDX = -1; - int insideBearishIDX = -1; - bool hasBullishInside = - pBar.IsBullish() && - HasInside( - insideBullishIDX, - pBar, - affectedZonesBullish // - ); - bool hasBearishInside = - pBar.IsBearish() && - HasInside( - insideBearishIDX, - pBar, - affectedZonesBearish // - ); - - // - // Do ... - - // - isBullish = - // - hasBullishInside && - isPullbackBullish && - isPBarHasBullishPatterns && - fimaParser.IsSARBullish(pBar.Index()) && - (pVale >= affectedZonesBullish[insideBullishIDX].lower && - pVale <= affectedZonesBullish[insideBullishIDX].upper) - // - ; - - // - isBearish = - // - hasBearishInside && - isPullbackBearish && - isPBarHasBearishPatterns && - fimaParser.IsSARBearish(pBar.Index()) && - (pPeak >= affectedZonesBearish[insideBearishIDX].lower && - pPeak <= affectedZonesBearish[insideBearishIDX].upper) - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - if (isBullish) - { - zone = affectedZonesBullish[insideBullishIDX]; - } - else - { - zone = affectedZonesBearish[insideBearishIDX]; - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - XClean(zones); - pBarAnalysis.Clean(); - XClean(affectedZones); - XClean(affectedZonesBullish); - XClean(affectedZonesBearish); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Bar Patterns ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - double peak = fimaHelper.GetPeak(bar.Index()); - double vale = fimaHelper.GetVale(bar.Index()); - double pPeak = fimaHelper.GetPeak(pBar.Index()); - double pVale = fimaHelper.GetVale(pBar.Index()); - double p2Peak = fimaHelper.GetPeak(p2Bar.Index()); - double p2Vale = fimaHelper.GetVale(p2Bar.Index()); - bool isPPeakOverLast = fimaParser.IsPeakOverLast(pBar.Index()); - bool isPValeUnderLast = fimaParser.IsValeUnderLast(pBar.Index()); - bool isP2PeakOverLast = fimaParser.IsPeakOverLast(p2Bar.Index()); - bool isP2ValeUnderLast = fimaParser.IsValeUnderLast(p2Bar.Index()); - bool isPeakOverLast = isPPeakOverLast || - isP2PeakOverLast; - bool isValeUnderLast = isPValeUnderLast || - isP2ValeUnderLast; - bool isP2ValeOverLast = pVale > p2Vale; - bool isP2PeakUnderLast = pPeak < p2Peak; - - // - // Check PBar Close Over Under Fast Ma ... - bool isPBarCloseOverFast = pBar.close > fimaHelper.GetMAFast(pBar.Index()); - bool isPBarCloseUnderFast = pBar.close < fimaHelper.GetMAFast(pBar.Index()); - bool isFastOverLast = fimaHelper.GetMAFast(pBar.Index()) > fimaHelper.GetMAFast(p2Bar.Index()); - bool isFastUnderLast = fimaHelper.GetMAFast(pBar.Index()) < fimaHelper.GetMAFast(p2Bar.Index()); - - // - // Force P2Bar is Pin Bar ... - ENUM_X_DIRECTION p2Dir; - bool isP2BarPinned = poiDetector.IsPinnedBar( - p2Bar, - p2Dir // - ); - bool isP2BarBullishPinned = - isP2BarPinned && - IsXBullish(p2Dir); - bool isP2BarBearishPinned = - isP2BarPinned && - IsXBearish(p2Dir); - - // - // Do ... - - // - isBullish = - // - isFastOverLast && - isValeUnderLast && - !isP2PeakUnderLast && - isPBarCloseOverFast && - isP2BarBullishPinned && - isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - isPeakOverLast && - isFastUnderLast && - !isP2ValeOverLast && - isPBarCloseUnderFast && - isP2BarBearishPinned && - isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Manage Stops ... - if (result) - { - // - double entry = GetEntry(zone.symbol, zone.dir); - double riskSide = zone.IsBullish() ? zone.lower : zone.upper; - double risk = MathAbs(entry - riskSide); - - // - // Collecting Affected Zones ... - XBoxZone tmps[]; - XBoxZone zones[]; - XBoxZone actedZones[]; - XBoxZone insideZones[]; - XBoxZone breakedZones[]; - XBoxZone affectedZones[]; - - // - // Support and Resistances ... - poiDetector.CollectZones(bar, tmps); - Copy(tmps, zones, false); - - // - // OBS ... - poiDetector.CollectOBs(bar, tmps); - Copy(tmps, zones, false); - - // - // FVGs ... - poiDetector.CollectFVGs(bar, tmps); - Copy(tmps, zones, false); - - // - ExtractAffectedZones(bar, zones, affectedZones); - - // - // Acteds Zones ... - ExtractActeds(bar, actedZones, affectedZones); - - // - // Inside Zones ... - ExtractInsides(bar, insideZones, affectedZones); - - // - // Breaked Zones ... - ExtractBreakeds(bar, breakedZones, affectedZones); - - // - // Cleanup ... - XClean(tmps); - XClean(zones); - XClean(actedZones); - XClean(insideZones); - XClean(breakedZones); - XClean(affectedZones); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Do ... - // XFIMA Consolidation ... - - // - bool isConsolidation = poiDetector.DetectPVConsolidationZone( - zone, - pBar.Index(), - true, // Force PV Break ... - true // Force Has Sar Switch ... - ); - - // - isBullish = - isConsolidation && - zone.IsBullish(); - - // - isBearish = - isConsolidation && - zone.IsBearish(); - - // - // Validate based on Bars Patterns ... - bool validateByBarPatterns = true; - if (validateByBarPatterns) - { - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - (bar.close > pBar.low || - bar.open > pBar.low) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BULLISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BULLISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BULLISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BULLISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - (bar.close < pBar.high || - bar.open < pBar.high) && - ( - // - pBarAnalysis.IsPinned(X_DIRECTION_BEARISH) || - pBarAnalysis.IsEngulfed(X_DIRECTION_BEARISH) || - pBarAnalysis.IsMomentum(X_DIRECTION_BEARISH) || - pBarAnalysis.IsPiercing(X_DIRECTION_BEARISH) || - pBarAnalysis.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || - isBearish; - } - - // - // Checking PullBack ... - bool validateByPullback = false; - if (validateByPullback) - { - // - XBoxZone pullback; - ENUM_X_DIRECTION pullbackDir; - bool isPullBack = result && - poiDetector.IsPullbackPattern( - pBar, - pullback, - pullbackDir, - 2, - false // Force Break ... - ); - bool isPullbackBullish = isPullBack && - IsXBullish(pullbackDir); - bool isPullbackBearish = isPullBack && - IsXBearish(pullbackDir); - - // - isBullish = - isBullish && - isPullbackBullish; - - // - isBearish = - isBearish && - isPullbackBearish; - - // - // Summarize Result ... - result = isBullish || - isBearish; - } - - // - // Validate ... - result = isBullish || - isBearish; - - // - // Prepare Zone ... - if (result) - { - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * Strategy 4: - * =========== - * - Works Based on Order Flow ... - * - Looking for new and Fresh Order Flow ... - * - Validate Bar is Inside Order Flow ... - * - Validate Bar has Proper Pattern ... - * - Validate Bar Based on ATR Band in two Step: - * - Step 1: Bars is Inside ATR Band (Middle) ... - * - Step 2: Trigger Bars Close Price based on ATR Band ... - * - Validate Order Flow based on Market Structure Zone ... - * - Validate Trigger Bar based on InDirectional Market Structure Zones ... - * - * Manipulations: - * ================ - * there are Some Flags properties to Change Validations in Strategy ... - * we can use them for Testing Purposes ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Validation Flags ... - bool validateBarInsideZone = true; - bool validateByBarPatterns = true; - bool validateByBarInsideATRBand = true; - bool validateByBarBasedOnATRBand = true; - bool validateMarketStructureHasDirectionalZone = true; - bool validateMarketStructureDirectionalZoneInsideOrderFlow = true; - bool validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP = true; - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - bool isBullish = false; - bool isBearish = false; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Do ... - - // - // Retrieve pBar Patterns ... - XPatternAnalysis pBarPatterns; - XPatternAnalysisConfig patternConfig = structureConfig.barsAnalysisConfig; - - // - poiDetector.AnalyseBarPatterns( - pBar, - pBarPatterns, - patternConfig // - ); - - // - // Detecting OrderFlow ... - XBoxZone oFlow[]; - bool hasOrderFlow = poiDetector.HasOrderFlow( - p3Bar, - dir, - oFlow, - structureConfig.orderFlowValidation, - structureConfig.orderFlowUseOB, - structureConfig.orderFlowUseFVG, - structureConfig.orderFlowUseSupportAndResistance, - patternConfig.supportAndResistanceLoopbackLength, - patternConfig.supportAndResistanceValidationLength, - structureConfig.loopback // - ); - - // - double atrBandUpper = EMPTY_VALUE; - double atrBandLower = EMPTY_VALUE; - double atrBandMiddle = EMPTY_VALUE; - - // - isBullish = hasOrderFlow && - IsXBullish(dir); - - // - isBearish = hasOrderFlow && - IsXBearish(dir); - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Force Price of p2Bar is Inside Order Flow ... - if (result && validateBarInsideZone) - { - // - double orderFlowUpper = 0; - double orderFlowLower = 0; - - // - int idx = -1; - idx = GetHighest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowUpper = oFlow[idx].upper; - } - idx = GetLowest(oFlow); - if (IsValidIndex(idx)) - { - orderFlowLower = oFlow[idx].lower; - } - - // - result = NotEmptyZero(orderFlowUpper) && - NotEmptyZero(orderFlowLower) && - orderFlowUpper > orderFlowLower && - (isBullish - ? p2Bar.low < orderFlowUpper - : p2Bar.high > orderFlowLower); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Has Pattern ... - if (result && validateByBarPatterns) - { - // - // Analyse Bar Patterns ... - result = pBarPatterns.IsValid(); - - // - // Bullish ... - bool isPBarHasBullishPatterns = - result && - // (bar.close > pBar.low || - // bar.open > pBar.low) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BULLISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BULLISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BULLISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BULLISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BULLISH) - // - ); - - // - // Bearish ... - bool isPBarHasBearishPatterns = - result && - // (bar.close < pBar.high || - // bar.open < pBar.high) && - ( - // - pBarPatterns.IsPinned(X_DIRECTION_BEARISH) || - pBarPatterns.IsEngulfed(X_DIRECTION_BEARISH) || - pBarPatterns.IsMomentum(X_DIRECTION_BEARISH) || - pBarPatterns.IsPiercing(X_DIRECTION_BEARISH) || - pBarPatterns.IsSignalKey(X_DIRECTION_BEARISH) - // - ); - - // - isBullish = - isBullish && - isPBarHasBullishPatterns && - !isPBarHasBearishPatterns; - - // - isBearish = - isBearish && - isPBarHasBearishPatterns && - !isPBarHasBullishPatterns; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force P2Bar Place Checking based on ATR Band ... - if (result && validateByBarInsideATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(p2Bar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(p2Bar.Index()); - - // - atrBandMiddle = atrBandLower + ((atrBandUpper - atrBandLower) / 2); - - // - isBullish = - isBullish && - NotEmptyZero(atrBandMiddle) && - p2Bar.low < atrBandMiddle; - - // - isBearish = - isBearish && - NotEmptyZero(atrBandMiddle) && - p2Bar.high > atrBandMiddle; - - // - // Summarize Result ... - result = isBullish || isBearish; - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // Force PBar Place Checking based on ATR Band ... - if (result && validateByBarBasedOnATRBand) - { - // - atrBandUpper = fimaHelper.GetATRBandUpper(pBar.Index()); - atrBandLower = fimaHelper.GetATRBandLower(pBar.Index()); - - // - result = - NotEmptyZero(atrBandUpper) && - NotEmptyZero(atrBandLower) && - (isBullish - ? pBar.close > atrBandLower - : pBar.close < atrBandUpper); - - // - // Reset Flags ... - if (!result) - { - // - isBullish = false; - isBearish = false; - } - } - - // - // for Bullish has Support ... - // for Bearish has Resistance ... - if (result && validateMarketStructureHasDirectionalZone) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone support; - XBoxZone resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, resistance); - } - - // - // Validate Support and Resistance by Order Flow ... - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - // Check Market Strucutre Support and Resistance Validation ... - if (validateMarketStructureDirectionalZoneInsideOrderFlow) - { - // - hasSupport = - hasOFBox && - hasSupport && - ofZone.lower < support.lower && - ofZone.upper > support.upper; - - // - hasResistance = - hasOFBox && - hasResistance && - ofZone.lower < resistance.lower && - ofZone.upper > resistance.upper; - } - - // - // Validate Directional Support or Resistance Exists ... - - // - isBullish = - isBullish && - hasSupport; - - // - isBearish = - isBearish && - hasResistance; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - support.Clean(); - tmpPivot.Clean(); - resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate Makret Structure Has Not Indirectional Zone ... - if (result && validateMarketStructureHasNotInDirectionalZoneOrUnReachedTP) - { - // - XOHCL tmpBar; - XPivot tmpPivot; - XBoxZone support; - XBoxZone resistance; - - // - // Check Market Strucutre Has Support / Resistance ... - bool hasSupport = pBarPatterns.IsSupport(); - bool hasResistance = pBarPatterns.IsResistance(); - - // - // Retrieve Support / Resistance Zone ... - if (hasSupport) - { - pBarPatterns.GetSupport(tmpBar, tmpPivot, support); - } - if (hasResistance) - { - pBarPatterns.GetResistance(tmpBar, tmpPivot, resistance); - } - - // - // Converts Order Flow to Zone ... - XBoxZone ofZone; - bool hasOFBox = ToBox(ofZone, oFlow); - - // - bool hasIndirectionalZone = - (isBullish && hasResistance) || - (isBearish && hasSupport); - if (hasIndirectionalZone) - { - // - // Here we Have to Validate Zone Place ... - - // - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? oFlow[0].lower : oFlow[0].upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Bullish ... - if (isBullish && hasResistance) - { - hasResistance = resistance.lower <= tp; - } - - // - // Bearish ... - if (isBearish && hasSupport) - { - hasSupport = support.upper >= tp; - } - } - - // - isBullish = - isBullish && - !hasResistance; - - // - isBearish = - isBearish && - !hasSupport; - - // - // Cleanup ... - ofZone.Clean(); - tmpBar.Clean(); - support.Clean(); - tmpPivot.Clean(); - resistance.Clean(); - - // - // Summarize Result ... - result = isBullish || isBearish; - } - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.Clean(); - result = ToBox( - p2Bar, - zone, - dir, - X_BAR_PATTERN_PINNED // - ); - - // - // Refine Zone ... - zone.to = bar.time; - zone.upper = MathMax(zone.upper, atrBandMiddle); - zone.lower = MathMin(zone.lower, atrBandMiddle); - - // - // Manage Stops ... - if (result) - { - // - // Since Stop Management Changes Zones Edge(s) ... - // we do it here for Refining Zone ... - - // - poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - poiDrawer.DrawPatternAnalysis(pBarPatterns, structureDrawConfig.barAnalysisDrawConfig); - - // - DebugBreak(); - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - XTarget iTarget; - - // - // Calculate Requirements ... - double point = GetPoints(bar.symbol); - double entry = GetEntry(bar.symbol, dir); - double slAddition = slAdditionDistance > 0 ? slAdditionDistance : 0; - double risk = MathAbs(entry - (isBullish ? zone.lower : zone.upper)) + (slAddition * point); - double reward = (defaultSignalR2R * risk); - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // High Risk Target is Used to Protect In Profit Positiions - // from Reversal Patterns ... - double highRiskR2r = (defaultSignalR2R / 5) * 4; - double highRiskReward = highRiskR2r * risk; - double highRiskTP = isBullish - ? entry + highRiskReward - : entry - highRiskReward; - iTarget.Clean(); - iTarget.actingDistance = 5; - iTarget.doRFOnEntry = true; - iTarget.target = highRiskTP; - iTarget.volumeMultiplier = 0.8; - AddRef(iTarget, targets); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - XClean(orderFlow); - pBarPatterns.Clean(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XKI_MTF_EA.mq5 b/Documents/BKP/XKI_MTF_EA.mq5 deleted file mode 100644 index 6fa8c1e8..00000000 --- a/Documents/BKP/XKI_MTF_EA.mq5 +++ /dev/null @@ -1,547 +0,0 @@ -//+------------------------------------------------------------------+ -//| XKI_MTF_EA.mq5 -//| SaherElm IT Center - Strategy using XKI -//| Author: Hadi Khazaee Asl -//+------------------------------------------------------------------+ -#property strict - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// Inputs -input string InpSymbol = "XAUUSDb"; -input ENUM_TIMEFRAMES InpSignalTF = PERIOD_H1; // Signal timeframe (H1) -input int InpKiLength = 26; // KI length (XKI input) -input bool InpShowKI = true; // (XKI input) -input int InpCalcLastBars = 1500; // (XKI input) - -input bool InpUseRSI = true; // Use RSI confirmation -input int InpRSIPeriod = 14; -input int InpRSIPrice = PRICE_CLOSE; - -input bool InpUseH4Filter = true; // Confirm with H4 -input bool InpUseD1Filter = false; // Confirm with D1 -input bool InpRequireBothFilters = false; // If true, require BOTH H4 and D1 agreement; else either - -input double InpFixedLot = 0.10; // Fixed lot size -input double InpRiskATRMult = 0.0; // Add ATR padding to stop (0=disabled) -input int InpATRPeriod = 14; - -input double InpRR = 2.0; // Reward:Risk target -input bool InpTrailByKI = true; // Trail stop to KI -input int InpSlippagePoints = 20; // Max slippage in points -input int InpMaxSpreadPoints = 200; // Max allowed spread in points - -input bool InpAvoidAsianSession = true; // Avoid 22:00–06:00 server time -input int InpAsianStartHour = 22; -input int InpAsianEndHour = 6; - -input bool InpAvoidNewsWindow = false; // Placeholder flag -input int InpNewsWindowMinutes = 60; // Skip trades within +/- minutes - -input int InpBarsLookbackSignal = 2; // Lookback bars for signal (e.g., last closed bar) - -// Magic number and comments -input int InpMagic = 260126; -input string InpOrderComment = "XKI_MTF_EA"; - -// iCustom indicator path (relative to Indicators folder if compiled there) -string g_xkiIndicatorPath = "x-saherelm.x121.xki"; // the compiled name; adjust if different - -// Buffers indices as per the indicator -#define KI_BUFFER_INDEX 0 -#define KI_COLOR_IDX_BUFFER_INDEX 1 -#define KI_STATE_BUFFER_INDEX 2 - -// States from indicator -#define BULLISH_STATE 1 -#define NEUTURAL_STATE 0 -#define BEARISH_STATE -1 - -// Globals -int g_digits; -double g_point; -MqlTick g_tick; -int g_atrHandleH1 = INVALID_HANDLE; -int g_atrHandleH4 = INVALID_HANDLE; -int g_atrHandleD1 = INVALID_HANDLE; -int g_rsiHandleH1 = INVALID_HANDLE; -int g_rsiHandleH4 = INVALID_HANDLE; -int g_rsiHandleD1 = INVALID_HANDLE; - -//+------------------------------------------------------------------+ -// OnInit -//+------------------------------------------------------------------+ -int OnInit() -{ - // - g_digits = (int)SymbolInfoInteger(InpSymbol, SYMBOL_DIGITS); - g_point = SymbolInfoDouble(InpSymbol, SYMBOL_POINT); - - if (!SymbolInfoTick(InpSymbol, g_tick)) - { - Print("Failed to get tick for symbol: ", InpSymbol); - return INIT_FAILED; - } - - // Quick validation - if (InpKiLength < 5) - { - Print("Invalid KI length: ", InpKiLength); - return INIT_PARAMETERS_INCORRECT; - } - - // - GetOrCreateATRHandle(InpSymbol, InpSignalTF, InpATRPeriod); - if (InpUseH4Filter) - GetOrCreateATRHandle(InpSymbol, PERIOD_H4, InpATRPeriod); - if (InpUseD1Filter) - GetOrCreateATRHandle(InpSymbol, PERIOD_D1, InpATRPeriod); - - // - GetOrCreateRSIHandle(InpSymbol, InpSignalTF, InpRSIPeriod, InpRSIPrice); - if (InpUseH4Filter) - GetOrCreateRSIHandle(InpSymbol, PERIOD_H4, InpRSIPeriod, InpRSIPrice); - if (InpUseD1Filter) - GetOrCreateRSIHandle(InpSymbol, PERIOD_D1, InpRSIPeriod, InpRSIPrice); - - // - return INIT_SUCCEEDED; -} - -//+------------------------------------------------------------------+ -// OnDeinit -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - // - if (g_atrHandleH1 != INVALID_HANDLE) - { - IndicatorRelease(g_atrHandleH1); - g_atrHandleH1 = INVALID_HANDLE; - } - if (g_atrHandleH4 != INVALID_HANDLE) - { - IndicatorRelease(g_atrHandleH4); - g_atrHandleH4 = INVALID_HANDLE; - } - if (g_atrHandleD1 != INVALID_HANDLE) - { - IndicatorRelease(g_atrHandleD1); - g_atrHandleD1 = INVALID_HANDLE; - } - - // - if (g_rsiHandleH1 != INVALID_HANDLE) - { - IndicatorRelease(g_rsiHandleH1); - g_rsiHandleH1 = INVALID_HANDLE; - } - if (g_rsiHandleH4 != INVALID_HANDLE) - { - IndicatorRelease(g_rsiHandleH4); - g_rsiHandleH4 = INVALID_HANDLE; - } - if (g_rsiHandleD1 != INVALID_HANDLE) - { - IndicatorRelease(g_rsiHandleD1); - g_rsiHandleD1 = INVALID_HANDLE; - } -} - -//+------------------------------------------------------------------+ -// OnTick -//+------------------------------------------------------------------+ -void OnTick() -{ - if (_Symbol != InpSymbol) - return; - - // Basic trading safety - if (!SymbolInfoTick(InpSymbol, g_tick)) - return; - double spreadPoints = GetSpread(InpSymbol); - if (spreadPoints > InpMaxSpreadPoints) - return; - - if (InpAvoidAsianSession) - { - // - MqlDateTime now = GetCurrentTime(); - int hr = now.hour; - if (IsHourInRange(hr, InpAsianStartHour, InpAsianEndHour)) - return; - } - - if (InpAvoidNewsWindow) - { - // Placeholder: implement your own calendar integration - // Skip trading in a window near news. Here we simply return. - return; - } - - // Only process on new bar of signal timeframe - static datetime lastSignalBarTime = 0; - datetime currentSignalBarTime = GetLastClosedBarTime(InpSymbol, InpSignalTF); - if (currentSignalBarTime == 0 || currentSignalBarTime == lastSignalBarTime) - return; - lastSignalBarTime = currentSignalBarTime; - - // Get signal state and KI on signal TF (last closed bar) - int signalBarShift = InpBarsLookbackSignal; // 1=last closed, 2=previous - int stateSignal; - double kiSignal, closeSignal; - if (!GetXKIStateAndKI(InpSymbol, InpSignalTF, signalBarShift, stateSignal, kiSignal)) - return; - closeSignal = iClose(InpSymbol, InpSignalTF, signalBarShift); - - // RSI confirmation - if (InpUseRSI) - { - double rsi = GetRSIValue(InpSymbol, InpSignalTF, InpRSIPeriod, InpRSIPrice, signalBarShift); - if (rsi == EMPTY_VALUE) - return; - if (stateSignal == BULLISH_STATE && rsi <= 50.0) - return; - if (stateSignal == BEARISH_STATE && rsi >= 50.0) - return; - } - - // Higher timeframe agreement - bool agreesH4 = true, agreesD1 = true; - if (InpUseH4Filter) - agreesH4 = HigherTFAgrees(InpSymbol, PERIOD_H4, signalBarShift, stateSignal); - if (InpUseD1Filter) - agreesD1 = HigherTFAgrees(InpSymbol, PERIOD_D1, signalBarShift, stateSignal); - - bool filterOK = true; - if (InpUseH4Filter || InpUseD1Filter) - { - if (InpRequireBothFilters) - filterOK = (agreesH4 && agreesD1); - else - filterOK = ((InpUseH4Filter && agreesH4) || (InpUseD1Filter && agreesD1)); - } - if (!filterOK) - return; - - // Neutral or invalid skip - if (stateSignal == NEUTURAL_STATE) - return; - - // Ensure no open positions for this symbol/magic - if (HasOpenPosition(InpSymbol, InpMagic)) - return; - - // Prepare trade params - double atrPad = 0.0; - if (InpRiskATRMult > 0.0) - { - double atr = GetATRValue(InpSymbol, InpSignalTF, InpATRPeriod, signalBarShift); - if (atr != EMPTY_VALUE && atr > 0) - atrPad = atr * InpRiskATRMult; - } - - double sl, tp; - bool isBuy = (stateSignal == BULLISH_STATE); - if (isBuy) - { - sl = kiSignal - atrPad; - tp = closeSignal + (closeSignal - sl) * InpRR; - PlaceOrder(InpSymbol, ORDER_TYPE_BUY, InpFixedLot, sl, tp); - } - else if (stateSignal == BEARISH_STATE) - { - sl = kiSignal + atrPad; - tp = closeSignal - (sl - closeSignal) * InpRR; - PlaceOrder(InpSymbol, ORDER_TYPE_SELL, InpFixedLot, sl, tp); - } - - // After placement, trailing handled in OnTimer or OnTick below - if (InpTrailByKI) - TrailStopsByKI(); -} - -//+------------------------------------------------------------------+ -// Utilities -//+------------------------------------------------------------------+ -// -// Create or reuse an ATR handle for the given TF ... -int GetOrCreateATRHandle( - string symbol, - ENUM_TIMEFRAMES tf, - int period // -) -{ - int h = g_atrHandleH1; - if (tf == PERIOD_H4) - h = g_atrHandleH4; - else if (tf == PERIOD_D1) - h = g_atrHandleD1; - if (h == INVALID_HANDLE) - { - h = iATR(symbol, tf, period); - if (h == INVALID_HANDLE) - Print("Failed to create ATR handle: ", symbol, " ", EnumToString(tf), " period=", period); - } - return h; -} - -// -// Read ATR value for a specific bar shift (1=last closed bar) ... -double GetATRValue( - string symbol, - ENUM_TIMEFRAMES tf, - int period, - int shift // -) -{ - int h = GetOrCreateATRHandle(symbol, tf, period); - if (h == INVALID_HANDLE) - return EMPTY_VALUE; - - // - double buff[]; - - // - // Copy exactly one value at 'shift' ... - int copied = CopyBuffer(h, 0, shift, 1, buff); - if (copied != 1 || !MathIsValidNumber(buff[0])) - return EMPTY_VALUE; - - // - return buff[0]; -} - -// -// Create or reuse an RSI handle for the given TF ... -int GetOrCreateRSIHandle( - string symbol, - ENUM_TIMEFRAMES tf, - int period, - int appliedPrice // -) -{ - // - int h = g_rsiHandleH1; - if (tf == PERIOD_H4) - h = g_rsiHandleH4; - else if (tf == PERIOD_D1) - h = g_rsiHandleD1; - if (h == INVALID_HANDLE) - { - h = iRSI(symbol, tf, period, appliedPrice); - if (h == INVALID_HANDLE) - Print("Failed to create RSI handle: ", symbol, " ", EnumToString(tf), " period=", period, " price=", appliedPrice); - } - return h; -} - -// -// Read RSI value for a specific bar shift (1=last closed bar) .. -double GetRSIValue( - string symbol, - ENUM_TIMEFRAMES tf, - int period, - int appliedPrice, - int shift // -) -{ - int h = GetOrCreateRSIHandle(symbol, tf, period, appliedPrice); - if (h == INVALID_HANDLE) - return EMPTY_VALUE; - double buff[]; - int copied = CopyBuffer(h, 0, shift, 1, buff); - if (copied != 1 || !MathIsValidNumber(buff[0])) - return EMPTY_VALUE; - return buff[0]; -} - -datetime GetLastClosedBarTime(string symbol, ENUM_TIMEFRAMES tf) -{ - datetime times[]; - if (CopyTime(symbol, tf, 0, 3, times) <= 1) - return 0; - // times[0] is current open bar time; last closed is times[1] - return times[1]; -} - -bool IsHourInRange(int hr, int startHr, int endHr) -{ - // Handles wrap-around (e.g., 22 -> 6) - if (startHr <= endHr) - return (hr >= startHr && hr < endHr); - else - return (hr >= startHr || hr < endHr); -} - -bool GetXKIStateAndKI(string symbol, ENUM_TIMEFRAMES tf, int shift, int &stateOut, double &kiOut) -{ - // Prepare indicator handle for this TF - static int handleH1 = INVALID_HANDLE; - static int handleH4 = INVALID_HANDLE; - static int handleD1 = INVALID_HANDLE; - - int handleRef = handleH1; - if (tf == PERIOD_H4) - handleRef = handleH4; - else if (tf == PERIOD_D1) - handleRef = handleD1; - - if (handleRef == INVALID_HANDLE) - { - handleRef = iCustom(symbol, tf, g_xkiIndicatorPath, - InpKiLength, InpShowKI, InpCalcLastBars); - if (handleRef == INVALID_HANDLE) - { - Print("Failed to create XKI handle for TF: ", EnumToString(tf)); - return false; - } - } - - double kiBuff[]; - double stateBuff[]; - - if (CopyBuffer(handleRef, KI_BUFFER_INDEX, shift, 1, kiBuff) != 1) - return false; - if (CopyBuffer(handleRef, KI_STATE_BUFFER_INDEX, shift, 1, stateBuff) != 1) - return false; - - kiOut = kiBuff[0]; - stateOut = (int)stateBuff[0]; - - if (!MathIsValidNumber(kiOut)) - return false; - return true; -} - -bool HigherTFAgrees(string symbol, ENUM_TIMEFRAMES tf, int shift, int signalState) -{ - int stateHTF; - double kiHTF; - if (!GetXKIStateAndKI(symbol, tf, shift, stateHTF, kiHTF)) - return false; - if (signalState == BULLISH_STATE) - return (stateHTF == BULLISH_STATE); - if (signalState == BEARISH_STATE) - return (stateHTF == BEARISH_STATE); - return false; -} - -bool HasOpenPosition(string symbol, int magic) -{ - for (int i = 0; i < PositionsTotal(); i++) - { - ulong ticket = PositionGetTicket(i); - if (ticket == 0) - continue; - if (PositionSelectByTicket(ticket)) - { - string sym = PositionGetString(POSITION_SYMBOL); - long mg = (long)PositionGetInteger(POSITION_MAGIC); - if (sym == symbol && mg == magic) - return true; - } - } - return false; -} - -void PlaceOrder(string symbol, ENUM_ORDER_TYPE type, double lots, double sl, double tp) -{ - MqlTradeRequest req; - MqlTradeResult res; - ZeroMemory(req); - ZeroMemory(res); - - double price = 0.0; - if (!SymbolInfoTick(symbol, g_tick)) - return; - - if (type == ORDER_TYPE_BUY) - price = g_tick.ask; - else if (type == ORDER_TYPE_SELL) - price = g_tick.bid; - - // Normalize SL/TP - sl = NormalizeDouble(sl, g_digits); - tp = NormalizeDouble(tp, g_digits); - price = NormalizeDouble(price, g_digits); - - req.action = TRADE_ACTION_DEAL; - req.symbol = symbol; - req.volume = lots; - req.type = type; - req.price = price; - req.sl = sl; - req.tp = tp; - req.deviation = InpSlippagePoints; - req.magic = InpMagic; - req.comment = InpOrderComment; - - if (!OrderSend(req, res)) - Print("OrderSend failed: ", res.retcode); -} - -void TrailStopsByKI() -{ - // Trail per position using current signal TF KI - for (int i = 0; i < PositionsTotal(); i++) - { - ulong ticket = PositionGetTicket(i); - if (ticket == 0) - continue; - if (!PositionSelectByTicket(ticket)) - continue; - - string sym = PositionGetString(POSITION_SYMBOL); - long mg = (long)PositionGetInteger(POSITION_MAGIC); - if (sym != InpSymbol || mg != InpMagic) - continue; - - ENUM_POSITION_TYPE ptype = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); - double sl = PositionGetDouble(POSITION_SL); - double priceOpen = PositionGetDouble(POSITION_PRICE_OPEN); - - // Use last closed bar KI for stability - int shift = 1; - int state; - double ki; - if (!GetXKIStateAndKI(sym, InpSignalTF, shift, state, ki)) - continue; - - MqlTradeRequest req; - MqlTradeResult res; - ZeroMemory(req); - ZeroMemory(res); - - double newSL = sl; - - if (ptype == POSITION_TYPE_BUY) - { - double proposedSL = NormalizeDouble(ki, g_digits); - if (proposedSL > sl) - newSL = proposedSL; // only move up - } - else if (ptype == POSITION_TYPE_SELL) - { - double proposedSL = NormalizeDouble(ki, g_digits); - if (proposedSL < sl || sl == 0.0) - newSL = proposedSL; // only move down (or set if none) - } - - if (newSL != sl && newSL != 0.0) - { - req.action = TRADE_ACTION_SLTP; - req.symbol = sym; - req.sl = newSL; - req.tp = PositionGetDouble(POSITION_TP); - req.magic = InpMagic; - - if (!OrderSend(req, res)) - Print("Trail SLTP failed: ", res.retcode); - } - } -} - -//+------------------------------------------------------------------+ diff --git a/Documents/BKP/XPullbackTradeer.mq5 b/Documents/BKP/XPullbackTradeer.mq5 deleted file mode 100644 index 9692e8b5..00000000 --- a/Documents/BKP/XPullbackTradeer.mq5 +++ /dev/null @@ -1,708 +0,0 @@ -//+------------------------------------------------------------------+ -//| TrendPullbackPro.mq5| -//| Trend-following pullback EA with risk & management | -//+------------------------------------------------------------------+ -#property copyright "Hadi Strategy" -#property link "" -#property version "1.10" -#property strict - -//--- Inputs: risk & money management -input double InpRiskPerTradePercent = 1.0; // Total risk per trade (% of balance) -input int InpMagicNumber = 123456; // Magic number -input double InpStopBufferPoints = 10; // Extra buffer beyond swing high/low (points) - -//--- Inputs: indicators -input ENUM_TIMEFRAMES InpTF = PERIOD_CURRENT; // Signal timeframe -input int InpFastEMAPeriod = 20; -input int InpSlowEMAPeriod = 50; -input int InpRSIPeriod = 14; -input double InpRSILowZoneMin = 40; // Uptrend pullback zone min -input double InpRSILowZoneMax = 50; // Uptrend pullback zone max -input double InpRSIHighZoneMin = 50; // Downtrend pullback zone min -input double InpRSIHighZoneMax = 60; // Downtrend pullback zone max - -//--- Inputs: partial TP and R multiples -input bool InpUsePartialTP = true; -input double InpPartialCloseAtR = 1.0; // R at which to take partial profit -input double InpPartialClosePercent = 50.0; // % of volume to close at partial TP -input double InpFinalTargetR = 3.0; // Final target R for runner -input bool InpUseBreakEven = true; -input double InpBreakEvenRMultiple = 1.0; // Move SL to BE at this R (runner) - -//--- Inputs: trailing stop -input bool InpUseEMATrailing = true; -input double InpTrailStartR = 1.0; // Start trailing after this R -input double InpTrailOffsetPoints = 5; // Extra buffer beyond EMA (points) - -//--- Inputs: spread & time filters -input bool InpUseSpreadFilter = true; -input double InpMaxSpreadPoints = 30; // Max allowed spread (in points) - -input bool InpUseTimeFilter = false; -input int InpSessionStartHour = 8; // Trading session start (server time) -input int InpSessionEndHour = 22; // Trading session end (server time) -input bool InpAvoidRolloverHour = true; -input int InpRolloverHour = 23; // Avoid new entries at this hour - -//--- constants -#define NO_TREND 0 -#define UPTREND 1 -#define DOWNTREND -1 - -#define PARTIAL_COMMENT "TrendPullbackEA_Partial" -#define RUNNER_COMMENT "TrendPullbackEA_Runner" - -//--- Global indicator handles -int rsi_handle; -int ema_fast_handle; -int ema_slow_handle; - -//--- Tick storage -MqlTick last_tick; - -//+------------------------------------------------------------------+ -//| OnInit | -//+------------------------------------------------------------------+ -int OnInit() -{ - rsi_handle = iRSI(_Symbol, InpTF, InpRSIPeriod, PRICE_CLOSE); - if(rsi_handle == INVALID_HANDLE) - { - Print("Error creating RSI handle. Error: ", GetLastError()); - return(INIT_FAILED); - } - - ema_fast_handle = iMA(_Symbol, InpTF, InpFastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE); - if(ema_fast_handle == INVALID_HANDLE) - { - Print("Error creating fast EMA handle. Error: ", GetLastError()); - return(INIT_FAILED); - } - - ema_slow_handle = iMA(_Symbol, InpTF, InpSlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE); - if(ema_slow_handle == INVALID_HANDLE) - { - Print("Error creating slow EMA handle. Error: ", GetLastError()); - return(INIT_FAILED); - } - - SymbolInfoTick(_Symbol, last_tick); - return(INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| OnDeinit | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - IndicatorRelease(rsi_handle); - IndicatorRelease(ema_fast_handle); - IndicatorRelease(ema_slow_handle); -} - -//+------------------------------------------------------------------+ -//| OnTick | -//+------------------------------------------------------------------+ -void OnTick() -{ - if(!SymbolInfoTick(_Symbol, last_tick)) - return; - - // Run main logic once per bar on signal timeframe - static datetime last_bar_time = 0; - datetime cur_bar_time = iTime(_Symbol, InpTF, 0); - if(cur_bar_time == last_bar_time) - return; - last_bar_time = cur_bar_time; - - ManageOpenPositions(); - - // Avoid new entries if no time/spread conditions - if(!CanOpenNewTrades()) - return; - - CheckOpenSignals(); -} - -//+------------------------------------------------------------------+ -//| Check if we can open new trades (time & spread) | -//+------------------------------------------------------------------+ -bool CanOpenNewTrades() -{ - // Spread filter - if(InpUseSpreadFilter) - { - double spread_points = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) - / SymbolInfoDouble(_Symbol, SYMBOL_POINT); - if(spread_points > InpMaxSpreadPoints) - { - //Print("Spread too high: ", spread_points, " > ", InpMaxSpreadPoints); - return(false); - } - } - - // Time filter - if(InpUseTimeFilter) - { - datetime now = TimeCurrent(); - MqlDateTime dt; - TimeToStruct(now, dt); - - // avoid rollover hour - if(InpAvoidRolloverHour && dt.hour == InpRolloverHour) - return(false); - - // session window - bool inSession = (dt.hour >= InpSessionStartHour && dt.hour < InpSessionEndHour); - if(!inSession) - return(false); - } - - return(true); -} - -//+------------------------------------------------------------------+ -//| Check for new entry signals | -//+------------------------------------------------------------------+ -void CheckOpenSignals() -{ - if(HasOpenPosition()) - return; - - int trend = GetTrendDirection(); - if(trend == NO_TREND) - return; - - double rsi_value; - if(!GetRSI(1, rsi_value)) - return; - - MqlRates rates[]; - if(CopyRates(_Symbol, InpTF, 0, 3, rates) < 3) - return; - // rates[0] current, [1] closed 1, [2] closed 2 - MqlRates candle = rates[1]; - MqlRates prev = rates[2]; - - bool longSignal = false; - bool shortSignal = false; - - if(trend == UPTREND) - { - if(rsi_value >= InpRSILowZoneMin && rsi_value <= InpRSILowZoneMax) - { - if(IsBullishPattern(candle, prev)) - longSignal = true; - } - } - else if(trend == DOWNTREND) - { - if(rsi_value >= InpRSIHighZoneMin && rsi_value <= InpRSIHighZoneMax) - { - if(IsBearishPattern(candle, prev)) - shortSignal = true; - } - } - - if(longSignal) - OpenTrade(ORDER_TYPE_BUY, candle); - else if(shortSignal) - OpenTrade(ORDER_TYPE_SELL, candle); -} - -//+------------------------------------------------------------------+ -//| Manage open positions (partial TP, BE, trailing) | -//+------------------------------------------------------------------+ -void ManageOpenPositions() -{ - double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); - - for(int i = PositionsTotal()-1; i >= 0; i--) - { - ulong ticket = PositionGetTicket(i); - if(!PositionSelectByTicket(ticket)) - continue; - - if(PositionGetInteger(POSITION_MAGIC) != InpMagicNumber) - continue; - if(PositionGetString(POSITION_SYMBOL) != _Symbol) - continue; - - long type = PositionGetInteger(POSITION_TYPE); - double volume = PositionGetDouble(POSITION_VOLUME); - double sl = PositionGetDouble(POSITION_SL); - double tp = PositionGetDouble(POSITION_TP); - double price_open = PositionGetDouble(POSITION_PRICE_OPEN); - string comment = PositionGetString(POSITION_COMMENT); - - MqlTick tick; - SymbolInfoTick(_Symbol, tick); - double current_price = (type == POSITION_TYPE_BUY ? tick.bid : tick.ask); - - double riskPoints; - if(type == POSITION_TYPE_BUY) - riskPoints = (price_open - sl) / point; - else - riskPoints = (sl - price_open) / point; - - if(riskPoints <= 0) - continue; - - double profitPoints; - if(type == POSITION_TYPE_BUY) - profitPoints = (current_price - price_open) / point; - else - profitPoints = (price_open - current_price) / point; - - double rMultiple = profitPoints / riskPoints; - - // 1) Partial TP logic for "partial" leg - if(InpUsePartialTP && comment == PARTIAL_COMMENT) - { - if(rMultiple >= InpPartialCloseAtR) - { - // Close this position fully (it's the partial leg) - ClosePosition(ticket); - continue; - } - } - - // 2) Break-even & trailing for runner leg - if(comment == RUNNER_COMMENT) - { - // Break-even - if(InpUseBreakEven && rMultiple >= InpBreakEvenRMultiple) - { - if(type == POSITION_TYPE_BUY && sl < price_open) - ModifyPositionSL(ticket, price_open); - else if(type == POSITION_TYPE_SELL && sl > price_open) - ModifyPositionSL(ticket, price_open); - } - - // EMA trailing after a certain R - if(InpUseEMATrailing && rMultiple >= InpTrailStartR) - { - double emaFast; - if(!GetEMA(ema_fast_handle, 1, emaFast)) - continue; - - double newSL; - double offset = InpTrailOffsetPoints * point; - if(type == POSITION_TYPE_BUY) - { - newSL = emaFast - offset; - if(newSL > sl && newSL < current_price) // only tighten SL - ModifyPositionSL(ticket, newSL); - } - else - { - newSL = emaFast + offset; - if(newSL < sl && newSL > current_price) - ModifyPositionSL(ticket, newSL); - } - } - - // Optionally: ensure TP aligns with final target R - // If user wants to rely only on trailing, they can disable or adjust final R. - // We keep TP as set at entry. - } - } -} - -//+------------------------------------------------------------------+ -//| Get trend direction from EMAs | -//+------------------------------------------------------------------+ -int GetTrendDirection() -{ - double ema_fast[3], ema_slow[3]; - if(CopyBuffer(ema_fast_handle, 0, 0, 3, ema_fast) < 3) - return NO_TREND; - if(CopyBuffer(ema_slow_handle, 0, 0, 3, ema_slow) < 3) - return NO_TREND; - - double fast = ema_fast[1]; - double slow = ema_slow[1]; - - if(fast > slow) - return UPTREND; - else if(fast < slow) - return DOWNTREND; - return NO_TREND; -} - -//+------------------------------------------------------------------+ -//| Get RSI value at bar index | -//+------------------------------------------------------------------+ -bool GetRSI(int index, double &value) -{ - double buffer[1]; - int copied = CopyBuffer(rsi_handle, 0, index, 1, buffer); - if(copied != 1) - return false; - - value = buffer[0]; - return true; -} - -//+------------------------------------------------------------------+ -//| Get EMA value from handle | -//+------------------------------------------------------------------+ -bool GetEMA(int handle, int index, double &value) -{ - double buffer[1]; - int copied = CopyBuffer(handle, 0, index, 1, buffer); - if(copied != 1) - return false; - value = buffer[0]; - return true; -} - -//+------------------------------------------------------------------+ -//| Bullish pattern: engulfing + pin-bar-ish | -//+------------------------------------------------------------------+ -bool IsBullishPattern(const MqlRates &c, const MqlRates &prev) -{ - double bodyC = MathAbs(c.close - c.open); - double bodyP = MathAbs(prev.close - prev.open); - double rangeC = c.high - c.low; - - if(rangeC <= 0) - return false; - - // Basic bullish: close > open - if(c.close <= c.open) - return false; - - // Engulfing body: current body >= previous body, and covers its open/close - bool engulfing = (bodyC >= bodyP && c.open <= prev.close && c.close >= prev.open); - - // Pin-bar-ish: long lower wick - double lowerWick = MathMin(c.open, c.close) - c.low; - bool longLowerWick = (lowerWick >= rangeC * 0.4); // tweak - - if(engulfing || longLowerWick) - return true; - - return false; -} - -//+------------------------------------------------------------------+ -//| Bearish pattern: engulfing + pin-bar-ish | -//+------------------------------------------------------------------+ -bool IsBearishPattern(const MqlRates &c, const MqlRates &prev) -{ - double bodyC = MathAbs(c.close - c.open); - double bodyP = MathAbs(prev.close - prev.open); - double rangeC = c.high - c.low; - - if(rangeC <= 0) - return false; - - // Basic bearish: close < open - if(c.close >= c.open) - return false; - - // Engulfing body - bool engulfing = (bodyC >= bodyP && c.open >= prev.close && c.close <= prev.open); - - // Pin-bar-ish: long upper wick - double upperWick = c.high - MathMax(c.open, c.close); - bool longUpperWick = (upperWick >= rangeC * 0.4); // tweak - - if(engulfing || longUpperWick) - return true; - - return false; -} - -//+------------------------------------------------------------------+ -//| Check if there is already an open position | -//+------------------------------------------------------------------+ -bool HasOpenPosition() -{ - for(int i = PositionsTotal()-1; i >= 0; i--) - { - ulong ticket = PositionGetTicket(i); - if(!PositionSelectByTicket(ticket)) - continue; - - if(PositionGetInteger(POSITION_MAGIC) != InpMagicNumber) - continue; - - if(PositionGetString(POSITION_SYMBOL) == _Symbol) - return true; - } - return false; -} - -//+------------------------------------------------------------------+ -//| Calculate lot size based on total risk % | -//+------------------------------------------------------------------+ -double CalculateTotalVolume(double stopLossPrice, ENUM_ORDER_TYPE type) -{ - double balance = AccountInfoDouble(ACCOUNT_BALANCE); - double riskMoney = balance * InpRiskPerTradePercent / 100.0; - - double entryPrice = (type == ORDER_TYPE_BUY ? last_tick.ask : last_tick.bid); - - double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); - double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); - double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); - - if(tick_size <= 0 || tick_value <= 0) - return(0.0); - - double slDistance = (type == ORDER_TYPE_BUY ? entryPrice - stopLossPrice : stopLossPrice - entryPrice); - if(slDistance <= 0) - return(0.0); - - double moneyPerPointPerLot = tick_value / tick_size * point; - double stopPoints = slDistance / point; - - double volume = riskMoney / (stopPoints * moneyPerPointPerLot); - - double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); - double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); - double lotStep= SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); - - volume = MathFloor(volume / lotStep) * lotStep; - - if(volume < minLot) - volume = 0.0; - if(volume > maxLot) - volume = maxLot; - - return(volume); -} - -//+------------------------------------------------------------------+ -//| Open trade: split into partial + runner | -//+------------------------------------------------------------------+ -void OpenTrade(ENUM_ORDER_TYPE type, const MqlRates &signalCandle) -{ - MqlTick tick; - if(!SymbolInfoTick(_Symbol, tick)) - return; - - double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); - double entryPrice = (type == ORDER_TYPE_BUY ? tick.ask : tick.bid); - - double slPrice; - if(type == ORDER_TYPE_BUY) - slPrice = signalCandle.low - InpStopBufferPoints * point; - else - slPrice = signalCandle.high + InpStopBufferPoints * point; - - if(slPrice <= 0) - return; - - double totalVolume = CalculateTotalVolume(slPrice, type); - if(totalVolume <= 0) - { - Print("Calculated total volume <= 0, skipping trade."); - return; - } - - double slDistance = (type == ORDER_TYPE_BUY ? entryPrice - slPrice : slPrice - entryPrice); - - // final TP at FinalTargetR - double finalTPDistance = slDistance * InpFinalTargetR; - double runnerTP; - if(type == ORDER_TYPE_BUY) - runnerTP = entryPrice + finalTPDistance; - else - runnerTP = entryPrice - finalTPDistance; - - // partial volume - double partialVolume = totalVolume; - double runnerVolume = 0.0; - - if(InpUsePartialTP && InpPartialClosePercent > 0 && InpPartialClosePercent < 100) - { - partialVolume = totalVolume * (InpPartialClosePercent / 100.0); - runnerVolume = totalVolume - partialVolume; - } - else - { - // no partial: everything is runner - partialVolume = 0.0; - runnerVolume = totalVolume; - } - - // normalized volumes - double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); - partialVolume = MathFloor(partialVolume / lotStep) * lotStep; - runnerVolume = MathFloor(runnerVolume / lotStep) * lotStep; - - if(partialVolume < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) - partialVolume = 0.0; - if(runnerVolume < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) - runnerVolume = 0.0; - - // Partial TP price at PartialCloseAtR - double partialTPPrice = 0.0; - if(InpUsePartialTP && partialVolume > 0 && InpPartialCloseAtR > 0) - { - double partialTPDist = slDistance * InpPartialCloseAtR; - if(type == ORDER_TYPE_BUY) - partialTPPrice = entryPrice + partialTPDist; - else - partialTPPrice = entryPrice - partialTPDist; - } - - // 1) Open partial leg - if(partialVolume > 0.0) - { - SendOrder(type, partialVolume, slPrice, partialTPPrice, PARTIAL_COMMENT); - } - - // 2) Open runner leg - if(runnerVolume > 0.0) - { - SendOrder(type, runnerVolume, slPrice, runnerTP, RUNNER_COMMENT); - } -} - -//+------------------------------------------------------------------+ -//| Send market order | -//+------------------------------------------------------------------+ -bool SendOrder(ENUM_ORDER_TYPE type, double volume, double sl, double tp, string comment) -{ - if(volume <= 0.0) - return(false); - - MqlTick tick; - if(!SymbolInfoTick(_Symbol, tick)) - return(false); - - MqlTradeRequest request; - MqlTradeResult result; - ZeroMemory(request); - ZeroMemory(result); - - request.action = TRADE_ACTION_DEAL; - request.magic = InpMagicNumber; - request.symbol = _Symbol; - request.volume = volume; - request.type = type; - request.deviation = 20; // points - request.type_filling= ORDER_FILLING_FOK; - request.price = (type == ORDER_TYPE_BUY ? tick.ask : tick.bid); - request.sl = sl; - request.tp = tp; - request.comment = comment; - - if(!OrderSend(request, result)) - { - Print("OrderSend failed. Error: ", GetLastError()); - return(false); - } - if(result.retcode != TRADE_RETCODE_DONE) - { - Print("OrderSend retcode: ", result.retcode); - return(false); - } - - Print("Opened ", (type == ORDER_TYPE_BUY ? "BUY" : "SELL"), - " ticket #", result.order, " vol=", DoubleToString(volume,2), - " SL=", DoubleToString(sl,_Digits)," TP=", DoubleToString(tp,_Digits), - " comment=", comment); - return(true); -} - -//+------------------------------------------------------------------+ -//| Modify SL for position | -//+------------------------------------------------------------------+ -bool ModifyPositionSL(ulong ticket, double newSL) -{ - if(!PositionSelectByTicket(ticket)) - return(false); - - string sym = PositionGetString(POSITION_SYMBOL); - long type = PositionGetInteger(POSITION_TYPE); - double volume = PositionGetDouble(POSITION_VOLUME); - double price = PositionGetDouble(POSITION_PRICE_OPEN); - double tp = PositionGetDouble(POSITION_TP); - - MqlTradeRequest request; - MqlTradeResult result; - ZeroMemory(request); - ZeroMemory(result); - - request.action = TRADE_ACTION_SLTP; - request.magic = InpMagicNumber; - request.symbol = sym; - request.volume = volume; - request.type = (ENUM_ORDER_TYPE)type; - request.price = price; - request.sl = newSL; - request.tp = tp; - - if(!OrderSend(request, result)) - { - Print("ModifyPositionSL OrderSend failed. Error: ", GetLastError()); - return(false); - } - if(result.retcode != TRADE_RETCODE_DONE) - { - Print("ModifyPositionSL retcode: ", result.retcode); - return(false); - } - - Print("Modified SL for ticket #", ticket, " to ", DoubleToString(newSL,_Digits)); - return(true); -} - -//+------------------------------------------------------------------+ -//| Close position | -//+------------------------------------------------------------------+ -bool ClosePosition(ulong ticket) -{ - if(!PositionSelectByTicket(ticket)) - return(false); - - string sym = PositionGetString(POSITION_SYMBOL); - long type = PositionGetInteger(POSITION_TYPE); - double volume = PositionGetDouble(POSITION_VOLUME); - double price = 0.0; - - MqlTick tick; - if(!SymbolInfoTick(sym, tick)) - return(false); - - if(type == POSITION_TYPE_BUY) - price = tick.bid; - else - price = tick.ask; - - MqlTradeRequest request; - MqlTradeResult result; - ZeroMemory(request); - ZeroMemory(result); - - request.action = TRADE_ACTION_DEAL; - request.magic = InpMagicNumber; - request.symbol = sym; - request.volume = volume; - request.type = (type == POSITION_TYPE_BUY ? ORDER_TYPE_SELL : ORDER_TYPE_BUY); - request.price = price; - request.deviation = 20; - request.type_filling= ORDER_FILLING_FOK; - request.comment = "Close"; - - if(!OrderSend(request, result)) - { - Print("ClosePosition OrderSend failed. Error: ", GetLastError()); - return(false); - } - if(result.retcode != TRADE_RETCODE_DONE) - { - Print("ClosePosition retcode: ", result.retcode); - return(false); - } - - Print("Closed ticket #", ticket); - return(true); -} -//+------------------------------------------------------------------+ diff --git a/Documents/BKP/XZoneEa.mq5 b/Documents/BKP/XZoneEa.mq5 deleted file mode 100644 index cbf151b7..00000000 --- a/Documents/BKP/XZoneEa.mq5 +++ /dev/null @@ -1,525 +0,0 @@ -//+------------------------------------------------------------------+ -//| XRR_Pullback.mq5 | -//| Author: Hadi (for XAUUSD,M15) | -//+------------------------------------------------------------------+ -#property strict -#property version "0.1" -#property description "M15 pullback EA: Major zone (HH/LL), minor same-direction zone, pullback entry, SL under minor, TP at 2R, 1% risk." - -//------------------------------- Inputs ----------------------------- - -input string Inp_Symbol = "XAUUSD"; -input ENUM_TIMEFRAMES Inp_WorkTF = PERIOD_M15; - -// Zone detection params -input int Inp_MajorLookbackBars = 400; // bars to scan for HH/LL major zone -input int Inp_MinorWindowBars = 80; // window to find first same-direction minor zone post-major -input int Inp_ZonePadPoints = 50; // padding around zones (points) - -// Confirmation / filters -input bool Inp_UseHTFConfluence = true; -input ENUM_TIMEFRAMES Inp_HTF = PERIOD_H1; // confluence timeframe -input int Inp_HTFShiftBars = 3; // HTF confirmation window -input bool Inp_UseEngulfingConfirm = true; -input bool Inp_UseRSIDivergence = false; -input int Inp_RSI_Period = 14; -input bool Inp_UseVolumeSpike = false; -input double Inp_VolSpikeFactor = 1.5; // vs 20-bar average - -// Risk management -input double Inp_RiskPercent = 1.0; // 1% per trade -input bool Inp_UseATRforSL = false; -input int Inp_ATR_Period = 14; -input double Inp_ATR_Mult = 1.5; -input double Inp_MinSLPoints = 200; // floor SL (points) -input double Inp_R_MultipleTP = 2.0; // fixed R:R=1:2 - -// Risk-free (optional) -input bool Inp_MoveToBEatTP1 = true; -input double Inp_TP1_R = 1.0; // move to BE at 1R -input double Inp_BE_OffsetPoints = 10; // lock-in small +offset - -// Sessions -input bool Inp_UseSessionFilter = true; -input int Inp_LondonOpenHour = 8; // broker time -input int Inp_LondonCloseHour = 17; -input int Inp_NYOpenHour = 13; -input int Inp_NYCloseHour = 21; -input bool Inp_AllowNYOverlapOnly = false; - -// Entry placement -input bool Inp_UseLimitAtZone = true; // limit order at minor zone -input int Inp_MaxSlippagePoints = 100; -input int Inp_MinRetestWickPoints = 30; - -// Safety / engine -input int Inp_MinBarsLoaded = 600; -input int Inp_SignalCoolOffBars = 20; // avoid rapid re-entries -input bool Inp_OnePositionOnly = true; - -//------------------------------- Structures ------------------------- -struct Zone -{ - bool isValid; - double priceLow; - double priceHigh; - int barIndex; // starting bar index of zone - bool isSupply; // true: resistance (HH), false: support (LL) -}; - -struct MinorZone -{ - bool isValid; - double priceLow; - double priceHigh; - int barIndex; - bool isSupply; // same direction as major -}; - -datetime lastSignalTimeBuy = 0; -datetime lastSignalTimeSell = 0; - -// -int atrHandler = INVALID_HANDLE; - -//------------------------------- Helpers ---------------------------- -int DigitsAdjust() -{ - return (int)SymbolInfoInteger(Inp_Symbol, SYMBOL_DIGITS); -} -double PointAdjust() -{ - return SymbolInfoDouble(Inp_Symbol, SYMBOL_POINT); -} -double TickValue() -{ - double v; - SymbolInfoDouble(Inp_Symbol, SYMBOL_TRADE_TICK_VALUE, v); - return v; -} -double TickSize() -{ - double s; - SymbolInfoDouble(Inp_Symbol, SYMBOL_TRADE_TICK_SIZE, s); - return s; -} - -bool IsSessionAllowed() -{ - if (!Inp_UseSessionFilter) - return true; - MqlDateTime t; - TimeToStruct(TimeCurrent(), t); - int hour = t.hour; - bool london = (hour >= Inp_LondonOpenHour && hour < Inp_LondonCloseHour); - bool ny = (hour >= Inp_NYOpenHour && hour < Inp_NYCloseHour); - if (Inp_AllowNYOverlapOnly) - return (london && ny); - return (london || ny); -} - -bool EngulfingBearish(int shift) -{ - double o0 = iOpen(Inp_Symbol, Inp_WorkTF, shift), c0 = iClose(Inp_Symbol, Inp_WorkTF, shift); - double o1 = iOpen(Inp_Symbol, Inp_WorkTF, shift + 1), c1 = iClose(Inp_Symbol, Inp_WorkTF, shift + 1); - return (c0 < o0 && c1 > o1 && o0 < c1 && c0 < o1 && (o0 - o1) > 0 && (c1 - c0) > 0 && (o1 < c0)); // rough engulfing -} -bool EngulfingBullish(int shift) -{ - double o0 = iOpen(Inp_Symbol, Inp_WorkTF, shift), c0 = iClose(Inp_Symbol, Inp_WorkTF, shift); - double o1 = iOpen(Inp_Symbol, Inp_WorkTF, shift + 1), c1 = iClose(Inp_Symbol, Inp_WorkTF, shift + 1); - return (c0 > o0 && c1 < o1 && o0 > c1 && c0 > o1 && (o0 - o1) > 0 && (c0 - c1) > 0 && (o1 > c0)); // rough engulfing inverse -} - -bool VolumeSpike(int shift) -{ - if (!Inp_UseVolumeSpike) - return true; - double avg = 0; - int n = 20; - for (int i = shift + 1; i < shift + 1 + n; i++) - avg += (double)iVolume(Inp_Symbol, Inp_WorkTF, i); - avg /= n; - double v0 = (double)iVolume(Inp_Symbol, Inp_WorkTF, shift); - return (v0 >= avg * Inp_VolSpikeFactor); -} - -bool HTFConfluence(bool wantSupply) -{ - if (!Inp_UseHTFConfluence) - return true; - // Simple HTF direction: last HTF candle close vs open - double o = iOpen(Inp_Symbol, Inp_HTF, Inp_HTFShiftBars), c = iClose(Inp_Symbol, Inp_HTF, Inp_HTFShiftBars); - bool htfDown = (c < o), htfUp = (c > o); - return wantSupply ? htfDown : htfUp; -} - -//------------------------------- Zone detection --------------------- -Zone FindMajorZone() -{ - Zone z; - z.isValid = false; - z.isSupply = false; - z.priceLow = 0; - z.priceHigh = 0; - z.barIndex = -1; - int bars = iBars(Inp_Symbol, Inp_WorkTF); - if (bars < Inp_MinBarsLoaded) - return z; - - // Highest high / lowest low over lookback - double hh = -DBL_MAX, ll = DBL_MAX; - int hhBar = -1, llBar = -1; - for (int i = 1; i <= Inp_MajorLookbackBars; i++) - { - double h = iHigh(Inp_Symbol, Inp_WorkTF, i), l = iLow(Inp_Symbol, Inp_WorkTF, i); - if (h > hh) - { - hh = h; - hhBar = i; - } - if (l < ll) - { - ll = l; - llBar = i; - } - } - - // Decide which one is closest to current action: use most recent extreme - if (hhBar < llBar) - { - z.isSupply = true; - z.isValid = true; - z.barIndex = hhBar; - z.priceLow = hh - Inp_ZonePadPoints * PointAdjust(); - z.priceHigh = hh + Inp_ZonePadPoints * PointAdjust(); - } - else - { - z.isSupply = false; - z.isValid = true; - z.barIndex = llBar; - z.priceLow = ll - Inp_ZonePadPoints * PointAdjust(); - z.priceHigh = ll + Inp_ZonePadPoints * PointAdjust(); - } - return z; -} - -MinorZone FindFirstMinorSameDirection(const Zone &major) -{ - MinorZone mz; - mz.isValid = false; - mz.isSupply = major.isSupply; - mz.priceLow = 0; - mz.priceHigh = 0; - mz.barIndex = -1; - if (!major.isValid) - return mz; - - // Scan forward from major's bar toward current for first reaction zone aligned with major - int start = major.barIndex - 1; - int end = MathMax(1, start - Inp_MinorWindowBars); - - // Heuristic: supply minor = bearish impulse followed by base; demand minor = bullish impulse followed by base - for (int i = start; i >= end; i--) - { - double o = iOpen(Inp_Symbol, Inp_WorkTF, i), c = iClose(Inp_Symbol, Inp_WorkTF, i); - double h = iHigh(Inp_Symbol, Inp_WorkTF, i), l = iLow(Inp_Symbol, Inp_WorkTF, i); - - bool bearImpulse = (c < o && (o - c) > (h - l) * 0.5); - bool bullImpulse = (c > o && (c - o) > (h - l) * 0.5); - - if (major.isSupply && bearImpulse) - { - // Base zone from next candle tight range - double h1 = iHigh(Inp_Symbol, Inp_WorkTF, i - 1), l1 = iLow(Inp_Symbol, Inp_WorkTF, i - 1); - mz.isValid = true; - mz.barIndex = i - 1; - mz.priceLow = l1 - Inp_ZonePadPoints * PointAdjust(); - mz.priceHigh = h1 + Inp_ZonePadPoints * PointAdjust(); - break; - } - if (!major.isSupply && bullImpulse) - { - double h1 = iHigh(Inp_Symbol, Inp_WorkTF, i - 1), l1 = iLow(Inp_Symbol, Inp_WorkTF, i - 1); - mz.isValid = true; - mz.barIndex = i - 1; - mz.priceLow = l1 - Inp_ZonePadPoints * PointAdjust(); - mz.priceHigh = h1 + Inp_ZonePadPoints * PointAdjust(); - break; - } - } - return mz; -} - -//------------------------------- Signal logic ----------------------- -bool PriceRetestedZone(const MinorZone &mz, bool supply, int shift = 0) -{ - if (!mz.isValid) - return false; - double high = iHigh(Inp_Symbol, Inp_WorkTF, shift), low = iLow(Inp_Symbol, Inp_WorkTF, shift); - // For supply: retest when high touches zone; for demand: retest when low touches zone - if (supply) - return (high >= mz.priceLow && high <= mz.priceHigh && (high - iClose(Inp_Symbol, Inp_WorkTF, shift)) * 1.0 / PointAdjust() >= Inp_MinRetestWickPoints); - else - return (low <= mz.priceHigh && low >= mz.priceLow && (iClose(Inp_Symbol, Inp_WorkTF, shift) - low) * 1.0 / PointAdjust() >= Inp_MinRetestWickPoints); -} - -bool ConfirmAtZone(bool supply) -{ - int shift = 0; - if (Inp_UseEngulfingConfirm) - { - if (supply) - { - if (!EngulfingBearish(shift)) - return false; - } - else - { - if (!EngulfingBullish(shift)) - return false; - } - } - if (!VolumeSpike(shift)) - return false; - if (!HTFConfluence(supply)) - return false; - // Optional: RSI divergence could be added here if enabled. - return true; -} - -//------------------------------- Risk & orders ----------------------- -double CalcPositionSize(double sl_points) -{ - double riskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * (Inp_RiskPercent / 100.0); - double tickValue = TickValue(); - double tickSize = TickSize(); - // Convert SL points to quoted ticks - double ticks = sl_points * PointAdjust() / tickSize; - if (ticks <= 0.0) - return 0.0; - double lots = riskMoney / (ticks * tickValue); - // Normalize to symbol step - double minLot = SymbolInfoDouble(Inp_Symbol, SYMBOL_VOLUME_MIN); - double lotStep = SymbolInfoDouble(Inp_Symbol, SYMBOL_VOLUME_STEP); - double maxLot = SymbolInfoDouble(Inp_Symbol, SYMBOL_VOLUME_MAX); - lots = MathFloor(lots / lotStep) * lotStep; - lots = MathMax(minLot, MathMin(lots, maxLot)); - return lots; -} - -bool PlaceEntry(const MinorZone &mz, bool supply) -{ - double bid = SymbolInfoDouble(Inp_Symbol, SYMBOL_BID); - double ask = SymbolInfoDouble(Inp_Symbol, SYMBOL_ASK); - double point = PointAdjust(); - - // SL beneath/above minor zone (or ATR-based) - double sl, entry, tp; - double sl_points; - - if (supply) - { - entry = Inp_UseLimitAtZone ? mz.priceLow : bid; // sell near zone top/low - double baseSL = mz.priceHigh + Inp_ZonePadPoints * point; - if (Inp_UseATRforSL) - { - // - double atrs[]; - CopyBuffer(atrHandler, MAIN_LINE, 0, 1, atrs); - double atr = atrs[0]; - baseSL = MathMax(baseSL, entry + (atr * Inp_ATR_Mult)); - } - sl = baseSL; - sl_points = (sl - entry) / point; - sl_points = MathMax(sl_points, Inp_MinSLPoints); - tp = entry - (sl_points * point * Inp_R_MultipleTP); - // Position sizing - double lots = CalcPositionSize(sl_points); - if (lots <= 0) - return false; - - MqlTradeRequest req; - MqlTradeResult res; - ZeroMemory(req); - ZeroMemory(res); - req.action = TRADE_ACTION_DEAL; - req.symbol = Inp_Symbol; - req.type = ORDER_TYPE_SELL; - req.volume = lots; - req.price = Inp_UseLimitAtZone ? entry : bid; - req.sl = sl; - req.tp = tp; - req.deviation = Inp_MaxSlippagePoints; - bool ok = OrderSend(req, res); - if (ok) - { - lastSignalTimeSell = TimeCurrent(); - } - return ok; - } - else - { - entry = Inp_UseLimitAtZone ? mz.priceHigh : ask; // buy near zone top/high - double baseSL = mz.priceLow - Inp_ZonePadPoints * point; - if (Inp_UseATRforSL) - { - // - double atrs[]; - CopyBuffer(atrHandler, MAIN_LINE, 0, 1, atrs); - double atr = atrs[0]; - baseSL = MathMin(baseSL, entry - (atr * Inp_ATR_Mult)); - } - sl = baseSL; - sl_points = (entry - sl) / point; - sl_points = MathMax(sl_points, Inp_MinSLPoints); - tp = entry + (sl_points * point * Inp_R_MultipleTP); - double lots = CalcPositionSize(sl_points); - if (lots <= 0) - return false; - - MqlTradeRequest req; - MqlTradeResult res; - ZeroMemory(req); - ZeroMemory(res); - req.action = TRADE_ACTION_DEAL; - req.symbol = Inp_Symbol; - req.type = ORDER_TYPE_BUY; - req.volume = lots; - req.price = Inp_UseLimitAtZone ? entry : ask; - req.sl = sl; - req.tp = tp; - req.deviation = Inp_MaxSlippagePoints; - bool ok = OrderSend(req, res); - if (ok) - { - lastSignalTimeBuy = TimeCurrent(); - } - return ok; - } -} - -//------------------------------- Position management ---------------- -void ManageOpenPositions() -{ - int total = PositionsTotal(); - double point = PointAdjust(); - - for (int i = 0; i < total; i++) - { - string sym = PositionGetSymbol(i); - if (sym != Inp_Symbol) - continue; - if (!PositionSelect(sym)) - continue; - - long type = (long)PositionGetInteger(POSITION_TYPE); - double price = PositionGetDouble(POSITION_PRICE_OPEN); - double sl = PositionGetDouble(POSITION_SL); - double tp = PositionGetDouble(POSITION_TP); - double current = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(sym, SYMBOL_BID) : SymbolInfoDouble(sym, SYMBOL_ASK); - - // Risk-free move to BE at TP1 (= 1R) - if (Inp_MoveToBEatTP1 && tp > 0 && sl > 0) - { - double rDist = MathAbs(tp - price) / Inp_R_MultipleTP; - bool hitTP1 = (type == POSITION_TYPE_BUY ? (current >= price + rDist) : (current <= price - rDist)); - - if (hitTP1) - { - double newSL = (type == POSITION_TYPE_BUY ? price + Inp_BE_OffsetPoints * point : price - Inp_BE_OffsetPoints * point); - if ((type == POSITION_TYPE_BUY && newSL > sl) || (type == POSITION_TYPE_SELL && newSL < sl)) - { - MqlTradeRequest req; - MqlTradeResult res; - ZeroMemory(req); - ZeroMemory(res); - req.action = TRADE_ACTION_SLTP; - req.symbol = sym; - req.position = (ulong)PositionGetInteger(POSITION_TICKET); - req.sl = newSL; - req.tp = tp; - OrderSend(req, res); - } - } - } - } -} - -//------------------------------- Engine ------------------------------ -bool CoolOffOk(bool supply) -{ - datetime last = supply ? lastSignalTimeSell : lastSignalTimeBuy; - if (last == 0) - return true; - // Convert bars to seconds approximate using last M15 duration - int seconds = Inp_SignalCoolOffBars * 15 * 60; - return (TimeCurrent() - last) >= seconds; -} - -void TrySignal() -{ - if (!IsSessionAllowed()) - return; - - Zone major = FindMajorZone(); - if (!major.isValid) - return; - - MinorZone minor = FindFirstMinorSameDirection(major); - if (!minor.isValid) - return; - - // Only act on retest + confirmation - bool retest = PriceRetestedZone(minor, major.isSupply, 0); - if (!retest) - return; - if (!ConfirmAtZone(major.isSupply)) - return; - if (Inp_OnePositionOnly && PositionsTotal() > 0) - return; - - if (!CoolOffOk(major.isSupply)) - return; - - PlaceEntry(minor, major.isSupply); -} - -//------------------------------- Standard events -------------------- -int OnInit() -{ - // - if (Symbol() != Inp_Symbol) - { - SymbolSelect(Inp_Symbol, true); - } - - // - atrHandler = iATR(Inp_Symbol, Inp_WorkTF, Inp_ATR_Period); - return (INIT_SUCCEEDED); -} - -void OnDeinit(const int reason) -{ -} - -void OnTick() -{ - static datetime lastBarTime = 0; - MqlRates rates[]; - int copied = CopyRates(Inp_Symbol, Inp_WorkTF, 0, Inp_MinBarsLoaded, rates); - if (copied < Inp_MinBarsLoaded) - return; - - datetime curBarTime = rates[0].time; - if (curBarTime != lastBarTime) - { - // New bar on M15: evaluate signal - TrySignal(); - lastBarTime = curBarTime; - } - - // Manage open positions continuously - ManageOpenPositions(); -} diff --git a/Documents/BKP/ZigZagLinearRegression/TestRegresser.mq5 b/Documents/BKP/ZigZagLinearRegression/TestRegresser.mq5 deleted file mode 100644 index 6b54b003..00000000 --- a/Documents/BKP/ZigZagLinearRegression/TestRegresser.mq5 +++ /dev/null @@ -1,1108 +0,0 @@ -//+------------------------------------------------------------------+ -//| TestRegresser.mq5 | -//| SaherElm IT Center | -//| https://www.saherelm.ir | -//+------------------------------------------------------------------+ -#property copyright "SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" - -// -// Imports ... -#include "../Classes/x-saherelm.x-cobject.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" -#include - -// -// Inputs ... - -// -// Calculation ... -input int zigzagDepth = 12; // Depth -input int zigzagDeviation = 5; // Deviation -input int zigzagBackStep = 3; // Back Step -input int mLoopbackLength = 200; // Loopback Length for Calculation -input int mRequiredPivots = 50; // Required Peaks for Calculation (0 > use loopback ) - -// -// Variables ... - -// -double mZigZagBuffer[]; // ZigZag Values Buffer ... -XBarTracker mBarTracker; // Bar Tracker ... -bool mZigZagPivotIsPeaks[]; // Check ZigZag Pivot Peak or Vale ... -double mZigZagPivotPrices[]; // ZigZag Pivot Prices ... -double mZigZagPivotIndexes[]; // ZigZag Pivot Indexes ... -datetime mZigZagPivotTimes[]; // ZigZag Pivot Times ... -CChartObjectTrend *mUpperTrend; // Trend Line Upper ... -CChartObjectTrend *mLowerTrend; // Trend Line Lower ... -int mZigZagHandler = INVALID_HANDLE; // ZigZag Indicator Handler ... - -// -double mPeakSlope; -double mPeakIntercept; -double mZigZagPeaks[]; -double mZigZagPeakIndexes[]; -datetime mZigZagPeakTimes[]; - -// -double mValeSlope; -double mValeIntercept; -double mZigZagVales[]; -double mZigZagValeIndexes[]; -datetime mZigZagValeTimes[]; - -// -datetime mToTime; -datetime mFromTime; - -// -// Predictions ... - -// -double mPeakTo; -double mValeTo; -double mPeakFrom; -double mValeFrom; - -// -ENUM_X_DIRECTION mUpperTrendDir; -ENUM_X_DIRECTION mLowerTrendDir; - -// -// Support and Resistances ... - -// -XBoxZone mSupportBox; -double mMinorSupport; -double mMajorSupport; -XCBoxObject *mSupportObj; - -// -XBoxZone mResistanceBox; -double mMinorResistance; -double mMajorResistance; -XCBoxObject *mResistanceObj; - -//+------------------------------------------------------------------+ -//| Expert initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - // - // Initialize Bar Tracker ... - mBarTracker.Init( - _Symbol, - _Period // - ); - - // - // Initialize ZigZag Handler ... - mZigZagHandler = iCustom( - _Symbol, - _Period, - "ZigZag", - zigzagDepth, - zigzagDeviation, - zigzagBackStep // - ); - if (mZigZagHandler == INVALID_HANDLE) - { - Print("Error creating ZigZag handle"); - return (INIT_FAILED); - } - - // - return (INIT_SUCCEEDED); -} -//+------------------------------------------------------------------+ -//| Expert deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - // - IndicatorRelease(mZigZagHandler); -} -//+------------------------------------------------------------------+ -//| Expert tick function | -//+------------------------------------------------------------------+ -void OnTick() -{ - // - if (!mBarTracker.IsNewBar()) - { - return; - } - - // - int readedZigZagsCount = 0; - bool readZigZagsBasedOnPivots = mRequiredPivots > 0; - - // - // Reading ZigZag Values Based on Loopback Length ... - if (!readZigZagsBasedOnPivots) - { - readedZigZagsCount = ReadZigZagValues(); - } - // - // Reading ZigZag Pivots based on required Pivots ... - else - { - // - readedZigZagsCount = ReadingZigZagPivots( - 0, // BarIndex ... - mRequiredPivots, // Required Pivots ... - 1500 // Max Allowed Loopback Length ... - ); - } - - // - // Validate Reading Succeed ... - if (readedZigZagsCount <= 0) - { - return; - } - - // - // Try to Detect ZigZag Peaks and Vales ... - ProcessZigZagsPeaksAndVales(); - - // - // Try to Calculate ZigZag Supports and Resistances ... - ProcessZigZagsSupportsAnsResistances(); - - // - // Try to Calculate Peaks and Vales Linear Regression Based - // Slope and Intercept (s) and also Detect From and To Times then - // Predict Peaks and Vales Values for them then ... - // Prepare Support and Resistance Boxes based on Calculated Support - // and Resistances ... - if (!CalculateZigZagLinearRegressionParameters()) - { - return; - } - - // - // Draw Peaks and Vales Based Trend Lines ... - DrawAnalysis(); - - // - // Process ZigZag Values ... - Print(""); - - // -} -//+------------------------------------------------------------------+ - -// -int ReadZigZagValues(int barIndex = 0) -{ - // - int result = 0; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - if (mZigZagHandler == INVALID_HANDLE) - { - return result; - } - - // - // Copy ZigZag Values to Buffers ... - result = CopyBuffer(mZigZagHandler, MAIN_LINE, 0, mLoopbackLength, mZigZagBuffer); - - // - // Set ZigZag Buffers as Series ... - ArraySetAsSeries(mZigZagBuffer, true); - - // - if (result <= 0) - { - return result; - } - - // - // Filling ZigZag Pivots ... - - // - // Clean Buffers ... - SpecifiedClean(mZigZagPivotTimes); - SpecifiedClean(mZigZagPivotPrices); - SpecifiedClean(mZigZagPivotIsPeaks); - SpecifiedClean(mZigZagPivotIndexes); - - // - // Looping Through ZigZag Buffers ... - XOHCL iBar; - bool has = false; - double iZigZag = 0; - bool isIZigZagPeak = false; - int count = ArraySize(mZigZagBuffer); - for (int i = 0; i < count; i++) - { - // - // Reading ZigZag Value ... - iZigZag = mZigZagBuffer[i]; - - // - // Validate ZigZag Values ... - if (!NotEmptyZero(iZigZag)) - { - continue; - } - - // - // Check ZigZag Value Is Peak or Vale ... - - // - // Initialize iBar ... - has = iBar.Init( - _Symbol, - _Period, - i // - ); - - // - // Validate Bar and also Exclude Most Recent Swing ... - if (!has || iBar.Index() == 0) - { - // - iBar.Clean(); - continue; - } - - // - isIZigZagPeak = iZigZag == iBar.high; - - // - // Filling Buffers ... - Add( - iBar.time, - mZigZagPivotTimes // - ); - Add( - iZigZag, - mZigZagPivotPrices // - ); - Add( - isIZigZagPeak, - mZigZagPivotIsPeaks // - ); - Add( - (double)iBar.Index(), - mZigZagPivotIndexes // - ); - - // - // Cleanup Resources ... - iBar.Clean(); - } - - // - return result; -} - -// -int ReadingZigZagPivots( - int barIndex = 0, - int requiredPivots = 15, - int maxAllowedLoopback = 1500 // -) -{ - // - int result = 0; - - // - // Cleanup Resources ... - SpecifiedClean(mZigZagPivotTimes); - SpecifiedClean(mZigZagPivotPrices); - SpecifiedClean(mZigZagPivotIsPeaks); - SpecifiedClean(mZigZagPivotIndexes); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredPivots = NormalizeInt(requiredPivots, 2); - maxAllowedLoopback = NormalizeInt(maxAllowedLoopback, 100); - - // - XOHCL iBar; - bool has = false; - double iZigZag = 0; - bool isPeak = false; - int idx = barIndex - 1; - double tmpZigZagBuffer[]; - int maxAllowed = barIndex + maxAllowedLoopback; - while (idx < maxAllowed && - ArraySize(mZigZagPivotPrices) < requiredPivots) - { - // - idx++; - - // - // Initializing Bar ... - has = iBar.Init( - _Symbol, - _Period, - idx // - ); - if (!has) - { - continue; - } - - // - // Reading ZigZag Value ... - if (CopyBuffer(mZigZagHandler, MAIN_LINE, idx, 1, tmpZigZagBuffer) < 1) - { - // - iBar.Clean(); - continue; - } - - // - // Read ZigZag Value and Validate it ... - iZigZag = tmpZigZagBuffer[0]; - has = NotEmptyZero(iZigZag); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - continue; - } - - // - isPeak = iZigZag == iBar.high; - - // - // Validate ZigZag Value for Ignore Zero ... - if (iBar.Index() == barIndex) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - continue; - } - - // - // Filling Pivots ... - - // - Add( - iZigZag, - mZigZagPivotPrices // - ); - - // - Add( - isPeak, - mZigZagPivotIsPeaks // - ); - - // - Add( - iBar.time, - mZigZagPivotTimes // - ); - - // - Add( - (double)iBar.Index(), - mZigZagPivotIndexes // - ); - - // - // Cleanup Resources ... - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Check Can Break Loop ... - has = idx >= maxAllowed || - ArraySize(mZigZagPivotPrices) == requiredPivots; - if (has) - { - break; - } - } - - // - // Cleanup Resources ... - SpecifiedClean(tmpZigZagBuffer); - - // - result = ArraySize(mZigZagPivotPrices); - - // - return result; -} - -// -void ProcessZigZagsPeaksAndVales() -{ - // - // Here we Parse ZigZag Values to Detect Peak or Vale ... - - // - int count = 0; - bool has = false; - - // - // Extract mZigZag Peaks and Vales ... - SpecifiedClean(mZigZagPeaks); - SpecifiedClean(mZigZagVales); - SpecifiedClean(mZigZagPeakTimes); - SpecifiedClean(mZigZagValeTimes); - SpecifiedClean(mZigZagPeakIndexes); - SpecifiedClean(mZigZagValeIndexes); - count = ArraySize(mZigZagPivotPrices); - has = IsValidSize(count); - if (!has) - { - return; - } - - // - double iZigZag = 0; - double iZigZagIDX = -1; - bool isIZigZagPeak = false; - datetime iZigZagTime = NULL; - for (int i = 0; i < count; i++) - { - // - // Reading Required Values ... - iZigZag = mZigZagPivotPrices[i]; - iZigZagTime = mZigZagPivotTimes[i]; - iZigZagIDX = mZigZagPivotIndexes[i]; - isIZigZagPeak = mZigZagPivotIsPeaks[i]; - - // - if (isIZigZagPeak) - { - // - Add( - iZigZag, - mZigZagPeaks // - ); - - // - Add( - iZigZagTime, - mZigZagPeakTimes // - ); - - // - Add( - iZigZagIDX, - mZigZagPeakIndexes // - ); - } - else - { - // - Add( - iZigZag, - mZigZagVales // - ); - - // - Add( - iZigZagTime, - mZigZagValeTimes // - ); - - // - Add( - iZigZagIDX, - mZigZagValeIndexes // - ); - } - } -} - -// -void ProcessZigZagsSupportsAnsResistances() -{ - // - int count = 0; - bool has = false; - double iValue = EMPTY_VALUE; - double tmpValue = EMPTY_VALUE; - - // - // Support ... - // Supports Calculated based on Vales ... - - // - tmpValue = EMPTY_VALUE; - mMinorSupport = EMPTY_VALUE; - mMajorSupport = EMPTY_VALUE; - count = ArraySize(mZigZagVales); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - // Reading Indexed Value ... - iValue = mZigZagVales[i]; - - // - // Check Can Change Major Support ... - has = !NotEmpty(mMajorSupport) || - mMajorSupport > iValue; - if (has) - { - // - tmpValue = mMajorSupport; - mMajorSupport = iValue; - } - else - { - // - // Check Minor Support ... - has = !NotEmpty(tmpValue) || - tmpValue > iValue; - if (has) - { - tmpValue = iValue; - } - } - } - - // - has = NotEmpty(tmpValue); - if (has) - { - mMinorSupport = tmpValue; - } - } - - // - // Resistance ... - // Resistances Calculated based on Peaks ... - - // - tmpValue = EMPTY_VALUE; - mMinorResistance = EMPTY_VALUE; - mMajorResistance = EMPTY_VALUE; - count = ArraySize(mZigZagPeaks); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - // Reading Indexed Value ... - iValue = mZigZagPeaks[i]; - - // - // Check Can Change Major Resistance ... - has = !NotEmpty(mMajorResistance) || - mMajorResistance < iValue; - if (has) - { - // - tmpValue = mMajorResistance; - mMajorResistance = iValue; - } - elsetmp - { - // - // Check Minor Resistance ... - has = !NotEmpty(tmpValue) || - tmpValue < iValue; - if (has) - { - tmpValue = iValue; - } - } - } - - // - has = NotEmpty(tmpValue); - if (has) - { - mMinorResistance = tmpValue; - } - } -} - -// -bool CalculateZigZagLinearRegressionParameters() -{ - // - bool result = false; - mUpperTrendDir = X_DIRECTION_NONE; - mLowerTrendDir = X_DIRECTION_NONE; - - // - // Peaks ... - CalculateSlopeAndIntercept( - mPeakSlope, - mPeakIntercept, - mZigZagPeakIndexes, - mZigZagPeaks // - ); - - // - // Vales ... - CalculateSlopeAndIntercept( - mValeSlope, - mValeIntercept, - mZigZagValeIndexes, - mZigZagVales // - ); - - // - result = - (NotEmpty(mPeakSlope) && - NotEmpty(mPeakIntercept)) || - (NotEmpty(mValeSlope) && - NotEmpty(mValeIntercept)); - if (!result) - { - return result; - } - - // - // Detect Oldest and Youngest Time of Pivots ... - - // - int idx = -1; - bool has = false; - - // - // Oldest ... - has = FindOldestIndex( - idx, - mZigZagPivotTimes // - ); - if (has) - { - mFromTime = mZigZagPivotTimes[idx]; - } - - // - // Youngest ... - has = FindYoungesttIndex( - idx, - mZigZagPivotTimes // - ); - if (has) - { - mToTime = mZigZagPivotTimes[idx]; - } - - // - // Validate Extracted Times ... - result = - IsSpecifiedValid(mToTime) && - IsSpecifiedValid(mFromTime); - if (!result) - { - return result; - } - - // - // Detect Extracted Times Bar Indexes ... - - // - int mToIDX = iBarShift( - _Symbol, - _Period, - mToTime // - ); - int mFromIDX = iBarShift( - _Symbol, - _Period, - mFromTime // - ); - - // - // Validate Detected Bar Indexes ... - result = - IsValidIndex(mToIDX) && - IsValidIndex(mFromIDX); - if (!result) - { - return result; - } - - // - // Calculate Predictions ... - - // - // Peak ... - mPeakTo = PredictValue( - mPeakSlope, - mPeakIntercept, - mToIDX // - ); - mPeakFrom = PredictValue( - mPeakSlope, - mPeakIntercept, - mFromIDX // - ); - - // - // Vale ... - mValeTo = PredictValue( - mValeSlope, - mValeIntercept, - mToIDX // - ); - mValeFrom = PredictValue( - mValeSlope, - mValeIntercept, - mFromIDX // - ); - - // - mUpperTrendDir = - mPeakFrom < mPeakTo - ? X_DIRECTION_BULLISH - : mPeakFrom > mPeakTo - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - mLowerTrendDir = - mValeFrom < mValeTo - ? X_DIRECTION_BULLISH - : mValeFrom > mValeTo - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - // Prepare Support and Resistance Boxes ... - - // - // Support ... - - // - mSupportBox.Clean(); - has = NotEmptyZero(mMinorSupport) && - NotEmptyZero(mMajorSupport); - if (has) - { - // - mSupportBox.to = mToTime; - mSupportBox.from = mFromTime; - mSupportBox.symbol = _Symbol; - mSupportBox.period = _Period; - mSupportBox.type = "Support"; - mSupportBox.upper = mMinorSupport; - mSupportBox.lower = mMajorSupport; - mSupportBox.dir = X_DIRECTION_BULLISH; - } - - // - // Resistance ... - - // - mResistanceBox.Clean(); - has = NotEmptyZero(mMinorResistance) && - NotEmptyZero(mMajorResistance); - if (has) - { - // - mResistanceBox.to = mToTime; - mResistanceBox.from = mFromTime; - mResistanceBox.symbol = _Symbol; - mResistanceBox.period = _Period; - mResistanceBox.type = "Resistance"; - mResistanceBox.upper = mMajorResistance; - mResistanceBox.lower = mMinorResistance; - mResistanceBox.dir = X_DIRECTION_BEARISH; - } - - // - result = - mSupportBox.IsValid() || - mResistanceBox.IsValid(); - - // - return result; -} - -// -void DrawAnalysis() -{ - // - bool isCreated = false; - - // - // Peak ... - - // - // Cleanup Upper Object ... - if (mUpperTrend != NULL) - { - // - mUpperTrend.Delete(); - mUpperTrend.Detach(); - delete mUpperTrend; - ZeroMemory(mUpperTrend); - } - - // - mUpperTrend = new CChartObjectTrend(); - isCreated = mUpperTrend.Create( - ChartID(), - "UpperTrend", - 0, - mFromTime, - mPeakFrom, - mToTime, - mPeakTo // - ); - if (isCreated) - { - // - // Apply Styles ... - - // - color upperColor = - IsSpecifiedBullish(mUpperTrendDir) - ? clrAqua - : IsSpecifiedBearish(mUpperTrendDir) - ? clrMagenta - : clrGray; // Neutural ... - - // - mUpperTrend.Width(2); - mUpperTrend.RayRight(true); - mUpperTrend.Color(upperColor); - } - - // - // Vale ... - - // - // Cleanup Lower Object ... - if (mLowerTrend != NULL) - { - // - mLowerTrend.Delete(); - mLowerTrend.Detach(); - delete mLowerTrend; - ZeroMemory(mLowerTrend); - } - - // - mLowerTrend = new CChartObjectTrend(); - isCreated = mLowerTrend.Create( - ChartID(), - "LowerTrend", - 0, - mFromTime, - mValeFrom, - mToTime, - mValeTo // - ); - if (isCreated) - { - // - // Apply Styles ... - - // - color lowerColor = - IsSpecifiedBullish(mLowerTrendDir) - ? clrAqua - : IsSpecifiedBearish(mLowerTrendDir) - ? clrMagenta - : clrGray; // Neutural ... - - // - mLowerTrend.Width(2); - mLowerTrend.RayRight(true); - mLowerTrend.Color(lowerColor); - } - - // - // Support ... - - // - // Cleanup Support Object ... - if (mSupportObj != NULL) - { - // - mSupportObj.Delete(); - mSupportObj.Detach(); - delete mSupportObj; - ZeroMemory(mSupportObj); - } - - // - isCreated = mSupportBox.IsValid(); - if (isCreated) - { - // - datetime to = TimeCurrent(); - mSupportObj = new XCBoxObject(); - isCreated = mSupportObj.Create( - ChartID(), - 0, - "Support", - mSupportBox.upper, - mSupportBox.lower, - mSupportBox.from, - to // - ); - if (isCreated) - { - // - // Apply Style ... - mSupportObj.BoxWidth(2); - mSupportObj.BoxColor(clrAqua); - } - } - - // - // Resistance ... - - // - // Cleanup Resistance Object ... - if (mResistanceObj != NULL) - { - // - mResistanceObj.Delete(); - mResistanceObj.Detach(); - delete mResistanceObj; - ZeroMemory(mResistanceObj); - } - - // - isCreated = mResistanceBox.IsValid(); - if (isCreated) - { - // - datetime to = TimeCurrent(); - mResistanceObj = new XCBoxObject(); - isCreated = mResistanceObj.Create( - ChartID(), - 0, - "Resistance", - mResistanceBox.upper, - mResistanceBox.lower, - mResistanceBox.from, - to // - ); - if (isCreated) - { - // - // Apply Style ... - mResistanceObj.BoxWidth(2); - mResistanceObj.BoxColor(clrMagenta); - } - } -} - -// -int FindOldestIndex( - int &index, - datetime ×[] // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Validate ... - if (!HasChild(times)) - { - return result; - } - - // - bool has = false; - datetime tmpTime = NULL; - for (int i = 0; i < ArraySize(times); i++) - { - // - has = - !IsSpecifiedValid(tmpTime) - ? true - : tmpTime > times[i]; - if (has) - { - // - index = i; - tmpTime = times[i]; - } - } - - // - // Validate result ... - result = - IsValidIndex(index) && - IsSpecifiedValid(tmpTime); - - // - return result; -} - -// -int FindYoungesttIndex( - int &index, - datetime ×[] // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Validate ... - if (!HasChild(times)) - { - return result; - } - - // - bool has = false; - datetime tmpTime = NULL; - for (int i = 0; i < ArraySize(times); i++) - { - // - has = - !IsSpecifiedValid(tmpTime) - ? true - : tmpTime < times[i]; - if (has) - { - // - index = i; - tmpTime = times[i]; - } - } - - // - // Validate result ... - result = - IsValidIndex(index) && - IsSpecifiedValid(tmpTime); - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/ZigZagLinearRegression/ZigZag.mq5 b/Documents/BKP/ZigZagLinearRegression/ZigZag.mq5 deleted file mode 100644 index 3863bd7aff92ac295fcb08c7843b2df30f7bb69e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18826 zcmeHP?{6E&5#7%P`afJ$M38DJj$QOiDhiNor52#Xs^zqB1cT5IN)|#om=_e|9a>ix(9B30X`4h@7?d9%|rLItA5qb z_wL-Cx$oT}etzLD+&|r)G5*hU(dVhVbXV?2H}qq?bvKaw*nR0g>;CF7Mq9((Z(I*g z58dC~JM_81Z`ZiHi>ni8H7|W8S(X~!K;vuomG{Ma$B$U04^6*t$I$K~(r1zI^9SfY z^fvF|`v#V;yvB7OEV+4kX366uHEth1AGjZ&LHI1WQVZwh-U1s#c<3DS9E@ZyxkvB~ zah2~!ZBEeZ7%00z-=XW``YnE=rMmF5w7A3-V=*Q=H>)B=s1-4c%+6G4D_3k86+n{#eI-==2&)vh8(zfvX*8J&pZ{ zj1x$GJJL@)Os-ZR5f@j$0r~C9BkB+=K}Hi)a5US7*KE7v`#nReD=%LorGt?kyT5pE zaU9xN+f0^qi?N7tiI5I>OC(jE(?nL>rd{R}NIOO()3Vf}avh*NmZ@zj;6PeYX5B_{ z{8d1ujUDzlfxqA3KK-ZGu(*F>dK|bnV=bhu*y;lM(!#O)ob=~tdj{WrgI-szO}pWc+w};aJi2->9$(@kJ^B$Ob3NmVr5dQG zi9Y+;_S(OMzU0R~ep(;fmSTkg{BYq}We7Q!;J*sJ4n0Ov+MJ>dThcx{!aLtXaZ1hj zuLsXjc7=!?08O;u5Pj&OOW>pDTT!Er<14le)@Sby)&k}gqV2VjLS&rbiE6~SCe}{j zNvD|MFkkgw2VA3^d-t&{GIYFO z5KFwK^hL^Ps1I}Er$7b0Bl#D-SZ5R7J4Xw$AG432@U7^gf8XKxvALtZEBy{R@gmvh z78c?9RAJp6_!WgVSQ#-6=O%GNJKFWCZoQa`E1;fycm>&v7exvAo$J~T?lKlXM2xxO zqs}sv<S+XE|*Q3G~U<8j^CgO^`Gde>v+3FPkT({Zrl{)#8B;HNbo7tAcg&pMA3T8Im-SQoIb?D%fs)jrrRtdtdIl%D%DSVZ$J ziQX{xZCG{>`n-lVfA`VzowxLtey^oEFU7E(gGG;1RJOu7&LD{hpb#|X|jy!TD69pT{&{=~DJr%RW_zh+~ zghj}*%AJAF1I|?=>3i;XGBz`cpL1oE3YP46?9QdE2_7lk9CjLY3!uh z#wL1Cp@EEj1S#~g{HD9X?s$*fg@uWz`g1|8eQL*y<4@K$kwB}8w0!$xZ*>_#ddVG) zySgs9`$2+?6+9>081FmiBbze|YTCK3&Z-OxRqjbg!H zv&O+%2df;Mi)8_+x18dM?5?#YqA^@~4&nOEER(f4X0u`uGDl!9@&9{24%@9n<1`s* zW5hQv(M~gf$}Qu=xY}&7Mw)3ke$%d^mGXr}fQ^s?jL3>&eKyitnV+2VnU7V$eY&;u zu{Lhb{Q>GM`O)at^i#pLjG(%uW!Y#sA4#k0Yh#0canLe zqdYwrd5=8K+Lzqbij}Qy1x;3y>w++wO7B3Dy#MHqWTr7$VGqRIBJbl_IHW#yXEaI< z!J@m){=oR|4b~mea24xs$g$!I-ygx0d%z5lb(4uciNVS9m3D2jZjWYps`w1M5N1rw z*<@F;0gKCQ>QzbGDup?nNBC}{Fg(*M%{F$kToLfKKGrgyf2dr3tM_CKSv^;AU-BmI zPl@i$u^)3tv@+#-T5a_M36jj?Yr* zxpl>|n6h(@$MpHZ_#KFHnLe2>o2k^CW$%~Ibo9Ju1W6hbqRqNrrMPE}x$QSjvvFsy zr{T2cV4!q8z*_r$SZ!klR-0bmPr+-7bZf&BW-FWB?A%r^Kh19W{FFOQ&0I83;Cm~Z zcS>Bh?``NUu76}vsa5dZG*5K!v<2%F!U}cS#D5d_s*&b#c`SsM>bqQ9yOyO_k`g`a zez&8wo%KFx&xqZaqsk7S`#yVaLQea{9^v^F%?4RdlWZ(L;}X_0&DFvRz8HH6 z&Dqj8rZspL@CMd+o2YEr9anm-Z2DLjn3XT~Zk}WMDp^TT-qw65-ght;k{M`5m_mlO zNo%Sjq$9*Wm21(Ylqoc04Txw;40m!?3oZ02HBXJqm{seMpc0zjO_||MMZj;lyf|*^ z^`^;Hnx=+vl*JXzpdtCcIhS(1H8xUp=#)-ce@{QtyMmjt?0Hg^P-TYiS&$>U3)+e` zp1Y$)M_c!K^ zfO2kGzYPB*mfVV|-U;71Da-)K)vPS$JQ$>eyfI{H zWfm`yowq^IG3HaTNQvxec(fhyv#hy%XQc=$v)8=w75uL&b7x$~NS%VW7B8`HQ@-MK zT7*rH0-aHbp7YHE=7*|jc+_SqC0ts{XSwP#K>F?|BsEkvc1*>WpVa zd{d+O#%A6YHp*wqQ%ktA3<0yF@BX+_)|XDpn@4NG68;Ik7TL36W_q8>cqKZvbEIZ* zlO?rdV>07OHR%v%ANt5n+L?|_9M1ZsPxGWsOEI^p>nXo;mu%k;*b!`HOV4VwpEC=! znedlLa`L8cY7KUb+<8Yk3(=HXF4Et|P#^hw`h9qXCzV*a2^P?EPOKBs#~<)as$2R* z8CBk}$lFBz9ow{@#XbS9tE;|8vM06U^OwusigNx?&KcXb@-~=%qoRMUx(16kPmzan z17Xkd(V$N<+t6ym*LUmHq8Ov$3}R>(>(0M+`GCC&aiB8@W5jP>btdBHfRDINS&z&h zEj}B?{`Nem)<1QW_*{&f_2XOKP3(#Ew9LA(s%A87!M&H9gW-v>U{BH9T2<%56U^2I zJoUDTQ(d%9y?;)M%F?*$K-(M-r|h0TX_w}}JpTpXl*Mj9M~t5!=l_A%WDUM6tJ(jT rW081Y<7(H}ZvNLlZU_& diff --git a/Documents/BKP/ZigZagLinearRegression/ZigZagColor.mq5 b/Documents/BKP/ZigZagLinearRegression/ZigZagColor.mq5 deleted file mode 100644 index ed3448af..00000000 --- a/Documents/BKP/ZigZagLinearRegression/ZigZagColor.mq5 +++ /dev/null @@ -1,288 +0,0 @@ -//+------------------------------------------------------------------+ -//| ZigzagColor.mq5 | -//| Copyright 2000-2025, MetaQuotes Ltd. | -//| https://www.mql5.com | -//+------------------------------------------------------------------+ -#property copyright "Copyright 2000-2025, MetaQuotes Ltd." -#property link "https://www.mql5.com" -//--- indicator settings -#property indicator_chart_window -#property indicator_buffers 5 -#property indicator_plots 1 -#property indicator_type1 DRAW_COLOR_ZIGZAG -#property indicator_width1 3 -#property indicator_color1 clrAqua, clrMagenta -//--- input parameters -input int InpDepth =12; // Depth -input int InpDeviation=5; // Deviation -input int InpBackstep =3; // Back Step -//--- indicator buffers -double ZigzagPeakBuffer[]; -double ZigzagBottomBuffer[]; -double HighMapBuffer[]; -double LowMapBuffer[]; -double ColorBuffer[]; - -int ExtRecalc=3; // recounting's depth - -enum EnSearchMode - { - Extremum=0, // searching for the first extremum - Peak=1, // searching for the next ZigZag peak - Bottom=-1 // searching for the next ZigZag bottom - }; -//+------------------------------------------------------------------+ -//| Custom indicator initialization function | -//+------------------------------------------------------------------+ -void OnInit() - { -//--- indicator buffers mapping - SetIndexBuffer(0,ZigzagPeakBuffer,INDICATOR_DATA); - SetIndexBuffer(1,ZigzagBottomBuffer,INDICATOR_DATA); - SetIndexBuffer(2,ColorBuffer,INDICATOR_COLOR_INDEX); - SetIndexBuffer(3,HighMapBuffer,INDICATOR_CALCULATIONS); - SetIndexBuffer(4,LowMapBuffer,INDICATOR_CALCULATIONS); -//--- set accuracy - IndicatorSetInteger(INDICATOR_DIGITS,_Digits); -//--- name for DataWindow and indicator subwindow label - string short_name=StringFormat("ZigZagColor(%d,%d,%d)",InpDepth,InpDeviation,InpBackstep); - IndicatorSetString(INDICATOR_SHORTNAME,short_name); - PlotIndexSetString(0,PLOT_LABEL,short_name); -//--- set an empty value - PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0); - } -//+------------------------------------------------------------------+ -//| ZigZag calculation | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[]) - { - if(rates_total<100) - return(0); -//--- - int i,start=0; - int extreme_counter=0,extreme_search=Extremum; - int shift,back=0,last_high_pos=0,last_low_pos=0; - double val=0,res=0; - double cur_low=0,cur_high=0,last_high=0,last_low=0; -//--- initializing - if(prev_calculated==0) - { - ArrayInitialize(ZigzagPeakBuffer,0.0); - ArrayInitialize(ZigzagBottomBuffer,0.0); - ArrayInitialize(HighMapBuffer,0.0); - ArrayInitialize(LowMapBuffer,0.0); - //--- start calculation from bar number InpDepth - start=InpDepth-1; - } -//--- ZigZag was already calculated before - if(prev_calculated>0) - { - i=rates_total-1; - //--- searching for the third extremum from the last uncompleted bar - while(extreme_counterrates_total -100) - { - res=(ZigzagPeakBuffer[i]+ZigzagBottomBuffer[i]); - //--- - if(res!=0) - extreme_counter++; - i--; - } - i++; - start=i; - //--- what type of exremum we search for - if(LowMapBuffer[i]!=0) - { - cur_low=LowMapBuffer[i]; - extreme_search=Peak; - } - else - { - cur_high=HighMapBuffer[i]; - extreme_search=Bottom; - } - //--- clear indicator values - for(i=start+1; i(InpDeviation*_Point)) - val=0.0; - else - { - for(back=InpBackstep; back>=1; back--) - { - res=LowMapBuffer[shift-back]; - //--- - if((res!=0) && (res>val)) - LowMapBuffer[shift-back]=0.0; - } - } - } - if(low[shift]==val) - LowMapBuffer[shift]=val; - else - LowMapBuffer[shift]=0.0; - //--- high - val=Highest(high,InpDepth,shift); - if(val==last_high) - val=0.0; - else - { - last_high=val; - if((val-high[shift])>(InpDeviation*_Point)) - val=0.0; - else - { - for(back=InpBackstep; back>=1; back--) - { - res=HighMapBuffer[shift-back]; - //--- - if((res!=0) && (reslast_high && - LowMapBuffer[shift]==0.0) - { - ZigzagPeakBuffer[last_high_pos]=0.0; - last_high_pos=shift; - last_high=HighMapBuffer[shift]; - ZigzagPeakBuffer[shift]=last_high; - ColorBuffer[shift]=0; - } - if(LowMapBuffer[shift]!=0.0 && HighMapBuffer[shift]==0.0) - { - last_low=LowMapBuffer[shift]; - last_low_pos=shift; - ZigzagBottomBuffer[shift]=last_low; - ColorBuffer[shift]=1; - extreme_search=Peak; - } - break; - default: - return(rates_total); - } - } - -//--- return value of prev_calculated for next call - return(rates_total); - } -//+------------------------------------------------------------------+ -//| Get highest value for range | -//+------------------------------------------------------------------+ -double Highest(const double&array[],int count,int start) - { - double res=array[start]; -//--- - for(int i=start-1; i>start-count && i>=0; i--) - if(resstart-count && i>=0; i--) - if(res>array[i]) - res=array[i]; -//--- - return(res); - } -//+------------------------------------------------------------------+ diff --git a/Documents/BKP/ZigZagLinearRegression/x-saherelm.xzg.mq5 b/Documents/BKP/ZigZagLinearRegression/x-saherelm.xzg.mq5 deleted file mode 100644 index 0492a503..00000000 --- a/Documents/BKP/ZigZagLinearRegression/x-saherelm.xzg.mq5 +++ /dev/null @@ -1,1111 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XZG -// Description: ZigZag Implementation ... -// -// -// 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 XZG Indicator" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -#define ShortName "XZG" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Definitions ... -enum ENUM_X_ZG_SEARCH_MODE -{ - X_ZG_SEARCH_EXTREMUM = 0, // searching for the first extremum - X_ZG_SEARCH_PEAK = 1, // searching for the next ZigZag peak - X_ZG_SEARCH_VALE = -1 // searching for the next ZigZag vale -}; - -// -// Inputs ... - -// -input group "Calculation"; -input int depth = 12; // Depth -input int deviation = 5; // Deviation -input int backStep = 3; // Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // Low Detect Mode - -// -// Presentation ... -input group "Presentation"; -input bool showPeaks = true; // Show Peaks -input bool showVales = true; // Show Vales -input bool showZigZag = true; // Show ZigZag -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Non Inputs ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 7 -#property indicator_plots 3 - -// -// ZigZag ... - -// -#define zigzagBufferIndex 0 -#define zigzagBufferPlotIndex 0 -double zigzagBuffer[]; - -// -#property indicator_label1 "XZG" -#property indicator_type1 DRAW_SECTION -#property indicator_color1 clrYellow -#property indicator_width1 2 - -// -// Peaks ... - -// -#define peakBufferIndex 1 -#define peakBufferPlotIndex 1 -double peakBuffer[]; - -// -#property indicator_label2 "PEAK" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 3 - -// -// Vales ... - -// -#define valeBufferIndex 2 -#define valeBufferPlotIndex 2 -double valeBuffer[]; - -// -#property indicator_label3 "VALE" -#property indicator_type3 DRAW_ARROW -#property indicator_color3 clrAqua -#property indicator_width3 3 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 2 - -// -#define highsBufferIndex mLastBufferIndex + 1 -double highsBuffer[]; - -// -#define highsTimeBufferIndex mLastBufferIndex + 2 -double highsTimeBuffer[]; - -// -#define lowsBufferIndex mLastBufferIndex + 3 -double lowsBuffer[]; - -// -#define lowsTimeBufferIndex mLastBufferIndex + 4 -double lowsTimeBuffer[]; - -// -// Variables, Properties and etc ... - -// -int mRecalc = 3; // Number of last extremes for recalculation - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -double zigzagUppers[]; -double zigzagLowers[]; -int zigzagLowersCount = 0; -int zigzagUppersCount = 0; - -// -double lastZigZagPeak = 0; -datetime lastZigZagPeakTime = NULL; - -// -double lastZigZagVale = 0; -datetime lastZigZagValeTime = NULL; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // 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 ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -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 -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Do ZigZag Calculations Before ArraySet As Series ... - int calculatedZigZags = CalculateZigZag( - 0, - prev_calculated, - rates_total, - open, - high, - close, - low, - tick_volume // - ); - if (calculatedZigZags != rates_total) - { - return prev_calculated; - } - - // - // Checking PrevCalculated ... - if (prev_calculated == rates_total) - { - return rates_total; - } - - // - // Calculating Limit ... - limit = prev_calculated == 0 - ? rates_total - 1 - : rates_total - prev_calculated; - if (limit <= 0) - { - limit = rates_total - 1; - } - - // - // Main Loop ... - for (int i = limit; i < rates_total - 1 && !IsStopped(); i++) - { - // - // Calculate Peaks and Vales ... - CalculatePeaksAndVales( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - // Inputs ... - depth > 0 && - deviation > 0 && - backStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // ZigZag ... - - // - ENUM_DRAW_TYPE zigzagDrawType = showZigZag ? DRAW_SECTION : DRAW_NONE; - - // - SetIndexBuffer(zigzagBufferIndex, zigzagBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_SHOW_DATA, showZigZag); - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_TYPE, zigzagDrawType); - - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(zigzagBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // PEAK ... - - // - ENUM_DRAW_TYPE peaksDrawType = showPeaks ? DRAW_ARROW : DRAW_NONE; - - // - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPeaks); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, peaksDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ENUM_DRAW_TYPE valesDrawType = showVales ? DRAW_ARROW : DRAW_NONE; - - // - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showVales); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, valesDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // Data Buffers ... - - // - // Highs ... - SetIndexBuffer(highsBufferIndex, highsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(highsTimeBufferIndex, highsTimeBuffer, INDICATOR_CALCULATIONS); - - // - // Lows ... - SetIndexBuffer(lowsBufferIndex, lowsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(lowsTimeBufferIndex, lowsTimeBuffer, INDICATOR_CALCULATIONS); - - // -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - * - * @return ( int ) - */ -int CalculateZigZag( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int result = 0; - - // - // Define Variables ... - int i = 0; - - // - int start = 0; - int extreme_counter = 0; - int extreme_search = X_ZG_SEARCH_EXTREMUM; - int shift = 0; - int back = 0; - int last_high_pos = 0; - int last_low_pos = 0; - - // - double val = 0; - double res = 0; - double curlow = 0; - double curhigh = 0; - double last_high = 0; - double last_low = 0; - - // - // Initializing ... - if (prevCalculated == 0) - { - // - ArrayInitialize(lowsBuffer, 0); - ArrayInitialize(highsBuffer, 0); - ArrayInitialize(zigzagBuffer, 0); - ArrayInitialize(lowsTimeBuffer, 0); - ArrayInitialize(highsTimeBuffer, 0); - - // - start = depth; - } - - // - // Preparing ZigZag Calculation High and Lows ... - - // - if (zigzagLowersCount != zigzagUppersCount || zigzagLowersCount != ratesTotal) - { - // - // Filling Upper ... - zigzagUppersCount = FillPrice( - zigzagUppersMode, - zigzagUppers, - open, - high, - close, - low // - ); - - // - // Filling Lower ... - zigzagLowersCount = FillPrice( - zigzagLowersMode, - zigzagLowers, - open, - high, - close, - low // - ); - } - - // - // Already Calculated Before ... - if (prevCalculated > 0) - { - // - i = ratesTotal - 1; - - // - // Searching for the third X_ZG_SEARCH_EXTREMUM from the last UnComplete Bar ... - while (extreme_counter < mRecalc && i > ratesTotal - 100) - { - // - res = zigzagBuffer[i]; - if (res != 0) - { - extreme_counter++; - } - - // - i--; - } - - // - i++; - start = i; - - // - // What type of X_ZG_SEARCH_EXTREMUM we Search for ... - if (lowsBuffer[i] != 0) - { - // - curlow = lowsBuffer[i]; - extreme_search = X_ZG_SEARCH_PEAK; - } - else - { - // - curhigh = highsBuffer[i]; - extreme_search = X_ZG_SEARCH_VALE; - } - - // - // Clear Values ... - for (i = start + 1; i < ratesTotal && !IsStopped(); i++) - { - // - lowsBuffer[i] = 0; - highsBuffer[i] = 0; - zigzagBuffer[i] = 0; - lowsTimeBuffer[i] = 0; - highsTimeBuffer[i] = 0; - } - } - - // - // Search for High and Low Extremes ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - // Low ... - val = zigzagLowers[Lowest(zigzagLowers, depth, shift)]; - if (val == last_low) - { - val = 0; - } - else - { - // - last_low = val; - - // - if ((zigzagLowers[shift] - val) > deviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= backStep; back++) - { - // - res = lowsBuffer[shift - back]; - if ((res != 0) && (res > val)) - { - // - lowsBuffer[shift - back] = 0; - lowsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagLowers[shift] == val) - { - // - lowsBuffer[shift] = val; - lowsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - // - lowsBuffer[shift] = 0; - lowsTimeBuffer[shift] = 0; - } - - // - // High ... - val = zigzagUppers[Highest(zigzagUppers, depth, shift)]; - if (val == last_high) - { - val = 0; - } - else - { - // - last_high = val; - - // - if ((val - zigzagUppers[shift]) > deviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= backStep; back++) - { - // - res = highsBuffer[shift - back]; - if ((res != 0) && (res < val)) - { - // - highsBuffer[shift - back] = 0; - highsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagUppers[shift] == val) - { - // - highsBuffer[shift] = val; - highsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - highsBuffer[shift] = 0; - highsTimeBuffer[shift] = 0; - } - } - - // - // Set Last Value ... - if (extreme_search == 0) // Undefined Values ... - { - // - last_low = 0; - last_high = 0; - } - else - { - // - last_low = curlow; - last_high = curhigh; - } - - // - // Final Selection of Extreme Points for ZigZag ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - res = 0; - - // - switch (extreme_search) - { - // - case X_ZG_SEARCH_EXTREMUM: - // - if (last_low == 0 && last_high == 0) - { - // - if (highsBuffer[shift] != 0) - { - // - last_high_pos = shift; - last_high = zigzagUppers[shift]; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - zigzagBuffer[shift] = last_high; - - // - res = 1; - } - - // - if (lowsBuffer[shift] != 0) - { - // - last_low_pos = shift; - last_low = zigzagLowers[shift]; - - // - extreme_search = X_ZG_SEARCH_PEAK; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - } - break; - - // - case X_ZG_SEARCH_PEAK: - // - if (lowsBuffer[shift] != 0 && lowsBuffer[shift] < last_low && highsBuffer[shift] == 0) - { - // - zigzagBuffer[last_low_pos] = 0; - - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - - // - if (highsBuffer[shift] != 0 && lowsBuffer[shift] == 0) - { - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - res = 1; - } - break; - - // - case X_ZG_SEARCH_VALE: - // - if (highsBuffer[shift] != 0 && highsBuffer[shift] > last_high && lowsBuffer[shift] == 0) - { - // - zigzagBuffer[last_high_pos] = 0; - - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - } - - // - if (lowsBuffer[shift] != 0 && highsBuffer[shift] == 0) - { - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - extreme_search = X_ZG_SEARCH_PEAK; - } - break; - } - } - - // - result = ratesTotal; - - // - return result; -} - -/** - * Calculate Peaks and Vales ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculatePeaksAndVales( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iZigZagValue = zigzagBuffer[barIndex]; - - // - // Peak ... - double iHighValue = highsBuffer[barIndex]; - double iHighTimeDouble = highsTimeBuffer[barIndex]; - datetime iHighTime = (datetime)((int)iHighTimeDouble); - if (iHighValue != 0 && iHighValue != EMPTY_VALUE && iZigZagValue == iHighValue) - { - // - peakBuffer[barIndex] = iHighValue; - - // - lastZigZagPeak = iHighValue; - lastZigZagPeakTime = iHighTime; - } - else - { - // - double iValue = emptyValue; - if ( - lastZigZagPeak != emptyValue && - lastZigZagPeak != EMPTY_VALUE && - IsSpecifiedValid(lastZigZagPeakTime)) - { - iValue = lastZigZagPeak; - } - - // - peakBuffer[barIndex] = iValue; - } - - // - // Vale ... - double iLowValue = lowsBuffer[barIndex]; - double iLowTimeDouble = lowsTimeBuffer[barIndex]; - datetime iLowTime = (datetime)((int)iLowTimeDouble); - if (iLowValue != 0 && iLowValue != EMPTY_VALUE && iZigZagValue == iLowValue) - { - // - valeBuffer[barIndex] = iLowValue; - - // - lastZigZagVale = iLowValue; - lastZigZagValeTime = iLowTime; - } - else - { - // - double iValue = emptyValue; - if ( - lastZigZagVale != emptyValue && - lastZigZagVale != EMPTY_VALUE && - IsSpecifiedValid(lastZigZagValeTime)) - { - iValue = lastZigZagVale; - } - - // - valeBuffer[barIndex] = iValue; - } -} - -// -// Get Specified Bar Time as Double ... -double GetZigZagBarTime(int barIndex) -{ - // - if (barIndex <= 0) - { - barIndex = 0; - } - - // - datetime time = iTime(_Symbol, _Period, barIndex); - - // - double result = (double)((int)time); - - // - return result; -} - -// -// Filling Required Prices Based on MODE ... -int FillPrice( - ENUM_X_PRICE mode, - double &dest[], - const double &open[], - const double &high[], - const double &close[], - const double &low[] // -) -{ - // - int result = 0; - - // - SpecifiedClean(dest); - - // - if (!IsXValid(mode)) - { - return result; - } - - // - switch (mode) - { - // - case X_PRICE_HIGH: - // - result = ArrayCopy( - dest, - high // - ); - break; - - // - case X_PRICE_LOW: - // - result = ArrayCopy( - dest, - low // - ); - break; - - // - case X_PRICE_OPEN: - // - result = ArrayCopy( - dest, - open // - ); - break; - - // - case X_PRICE_CLOSE: - // - result = ArrayCopy( - dest, - close // - ); - break; - - // - default: - // - result = ArrayCopy( - dest, - close // - ); - break; - } - - // - return result; -} - -// -// Search for the index of the highest bar ... -int Highest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double max = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] > max) - { - // - result = i; - max = mArray[i]; - } - } - - // - // Return index of the highest bar - return result; -} - -// -// Search for the index of the lowest bar ... -int Lowest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double min = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] < min) - { - // - result = i; - min = mArray[i]; - } - } - - // - // Return index of the lowest bar - return result; -} diff --git a/Documents/BKP/ZigZagLinearRegression/x-zigzag.analyser.ea.mq5 b/Documents/BKP/ZigZagLinearRegression/x-zigzag.analyser.ea.mq5 deleted file mode 100644 index c66d88eb..00000000 --- a/Documents/BKP/ZigZagLinearRegression/x-zigzag.analyser.ea.mq5 +++ /dev/null @@ -1,383 +0,0 @@ -//+------------------------------------------------------------------+ -//| ZigZag Analyzer.mq5| -//| Copyright 2025, MetaQuotes Ltd.| -//| https://www.mql5.com/en/users/lynnchris| -//+------------------------------------------------------------------+ -#property copyright "Copyright 2025, MetaQuotes Ltd." -#property link "https://www.mql5.com/en/users/lynnchris" -#property version "1.0" -#property strict - -// -#include "../Libraries/x-saherelm.common.lib.mq5" - -// Input parameters -input ENUM_TIMEFRAMES InpTimeFrame = PERIOD_CURRENT; // Timeframe to analyze -input int ZZ_Depth = 12; // ZigZag depth -input int ZZ_Deviation = 5; // ZigZag deviation -input int ZZ_Backstep = 3; // ZigZag backstep -input int LookBackBars = 500; // Bars to search for pivots -input int ExtendFutureBars = 100; // Bars to extend trendlines into the future - -// Global indicator handle for ZigZag -int zzHandle; - -// Arrays for ZigZag data and pivot storage -double zzBuffer[]; -bool pivotIsPeak[]; -double pivotPrices[]; -datetime pivotTimes[]; - -// Variable to detect new bars -datetime lastBarTime = 0; - -//+------------------------------------------------------------------+ -//| Initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - // - zzHandle = iCustom( - _Symbol, - InpTimeFrame, - "x-saherelm.xzg", - "", - ZZ_Depth, - ZZ_Deviation, - ZZ_Backstep, - X_PRICE_HIGH, - X_PRICE_LOW, - "", - false, - false, - true, - 159, - 159 // - ); - if (zzHandle == INVALID_HANDLE) - { - Print("Error creating ZigZag handle"); - return (INIT_FAILED); - } - return (INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| Deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - ObjectDelete(0, "Downtrend_HighLine"); - ObjectDelete(0, "Downtrend_LowLine"); - ObjectDelete(0, "Major_Resistance"); - ObjectDelete(0, "Major_Support"); - ObjectDelete(0, "Minor_Resistance"); - ObjectDelete(0, "Minor_Support"); - IndicatorRelease(zzHandle); -} - -//+------------------------------------------------------------------+ -//| Tick function | -//+------------------------------------------------------------------+ -void OnTick() -{ - datetime currentBarTime = iTime(_Symbol, InpTimeFrame, 0); - if (currentBarTime == lastBarTime) - return; - lastBarTime = currentBarTime; - - // Remove previous objects - ObjectDelete(0, "Downtrend_HighLine"); - ObjectDelete(0, "Downtrend_LowLine"); - ObjectDelete(0, "Major_Resistance"); - ObjectDelete(0, "Major_Support"); - ObjectDelete(0, "Minor_Resistance"); - ObjectDelete(0, "Minor_Support"); - - if (CopyBuffer(zzHandle, 0, 0, LookBackBars, zzBuffer) <= 0) - { - Print("Failed to copy ZigZag data"); - return; - } - ArraySetAsSeries(zzBuffer, true); - - DrawZigZagTrendlines(); - DrawSupportResistance(); -} - -//+------------------------------------------------------------------+ -//| Draw ZigZag-based Trendlines | -//+------------------------------------------------------------------+ -void DrawZigZagTrendlines() -{ - double highPrices[10], lowPrices[10]; - datetime highTimes[10], lowTimes[10]; - int highCount = 0, lowCount = 0; - - // Extract swing points from the ZigZag buffer - for (int i = 0; i < LookBackBars - 1; i++) - { - if (zzBuffer[i] != 0) - { - if (iHigh(_Symbol, InpTimeFrame, i) == zzBuffer[i] && highCount < 10) - { - highPrices[highCount] = zzBuffer[i]; - highTimes[highCount] = iTime(_Symbol, InpTimeFrame, i); - highCount++; - } - else if (iLow(_Symbol, InpTimeFrame, i) == zzBuffer[i] && lowCount < 10) - { - lowPrices[lowCount] = zzBuffer[i]; - lowTimes[lowCount] = iTime(_Symbol, InpTimeFrame, i); - lowCount++; - } - } - } - - // Exclude the most recent swing if possible - int usedHighCount = (highCount >= 4) ? highCount - 1 : highCount; - int usedLowCount = (lowCount >= 4) ? lowCount - 1 : lowCount; - - double mHigh = 0, bHigh = 0, mLow = 0, bLow = 0; - bool validHigh = false, validLow = false; - - // Regression for highs - if (usedHighCount >= 3) - { - double sumT = 0, sumP = 0, sumTP = 0, sumT2 = 0; - for (int i = 0; i < usedHighCount; i++) - { - double t = (double)highTimes[i]; - double p = highPrices[i]; - sumT += t; - sumP += p; - sumTP += t * p; - sumT2 += t * t; - } - int N = usedHighCount; - double denominator = N * sumT2 - sumT * sumT; - if (denominator != 0) - { - mHigh = (N * sumTP - sumT * sumP) / denominator; - bHigh = (sumP - mHigh * sumT) / N; - } - else - bHigh = sumP / N; - validHigh = true; - } - - // Regression for lows - if (usedLowCount >= 3) - { - double sumT = 0, sumP = 0, sumTP = 0, sumT2 = 0; - for (int i = 0; i < usedLowCount; i++) - { - double t = (double)lowTimes[i]; - double p = lowPrices[i]; - sumT += t; - sumP += p; - sumTP += t * p; - sumT2 += t * t; - } - int N = usedLowCount; - double denominator = N * sumT2 - sumT * sumT; - if (denominator != 0) - { - mLow = (N * sumTP - sumT * sumP) / denominator; - bLow = (sumP - mLow * sumT) / N; - } - else - bLow = sumP / N; - validLow = true; - } - - // Define time limits for trendlines - datetime pastTime = iTime(_Symbol, InpTimeFrame, LookBackBars - 1); - datetime futureTime = lastBarTime + ExtendFutureBars * PeriodSeconds(); - - // Draw trendlines if both regressions are valid - if (validHigh && validLow) - { - // When slopes have the same sign, use average slope - if (mHigh * mLow > 0) - { - double mParallel = (mHigh + mLow) / 2.0; - double bHighParallel = highPrices[0] - mParallel * (double)highTimes[0]; - double bLowParallel = lowPrices[0] - mParallel * (double)lowTimes[0]; - - datetime highStartTime = pastTime; - double highStartPrice = mParallel * (double)highStartTime + bHighParallel; - double highEndPrice = mParallel * (double)futureTime + bHighParallel; - if (!ObjectCreate(0, "Downtrend_HighLine", OBJ_TREND, 0, highStartTime, highStartPrice, futureTime, highEndPrice)) - Print("Failed to create High Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_COLOR, clrRed); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_RIGHT, true); - } - - datetime lowStartTime = pastTime; - double lowStartPrice = mParallel * (double)lowStartTime + bLowParallel; - double lowEndPrice = mParallel * (double)futureTime + bLowParallel; - if (!ObjectCreate(0, "Downtrend_LowLine", OBJ_TREND, 0, lowStartTime, lowStartPrice, futureTime, lowEndPrice)) - Print("Failed to create Low Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_COLOR, clrGreen); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_RIGHT, true); - } - } - else - { - datetime highStartTime = pastTime; - double highStartPrice = mHigh * (double)highStartTime + bHigh; - double highEndPrice = mHigh * (double)futureTime + bHigh; - if (!ObjectCreate(0, "Downtrend_HighLine", OBJ_TREND, 0, highStartTime, highStartPrice, futureTime, highEndPrice)) - Print("Failed to create High Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_COLOR, clrRed); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_RIGHT, true); - } - - datetime lowStartTime = pastTime; - double lowStartPrice = mLow * (double)lowStartTime + bLow; - double lowEndPrice = mLow * (double)futureTime + bLow; - if (!ObjectCreate(0, "Downtrend_LowLine", OBJ_TREND, 0, lowStartTime, lowStartPrice, futureTime, lowEndPrice)) - Print("Failed to create Low Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_COLOR, clrGreen); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_RIGHT, true); - } - } - } - else - { - if (validHigh) - { - datetime highStartTime = pastTime; - double highStartPrice = mHigh * (double)highStartTime + bHigh; - double highEndPrice = mHigh * (double)futureTime + bHigh; - if (!ObjectCreate(0, "Downtrend_HighLine", OBJ_TREND, 0, highStartTime, highStartPrice, futureTime, highEndPrice)) - Print("Failed to create High Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_COLOR, clrRed); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_HighLine", OBJPROP_RAY_RIGHT, true); - } - } - if (validLow) - { - datetime lowStartTime = pastTime; - double lowStartPrice = mLow * (double)lowStartTime + bLow; - double lowEndPrice = mLow * (double)futureTime + bLow; - if (!ObjectCreate(0, "Downtrend_LowLine", OBJ_TREND, 0, lowStartTime, lowStartPrice, futureTime, lowEndPrice)) - Print("Failed to create Low Trendline"); - else - { - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_COLOR, clrGreen); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_LEFT, true); - ObjectSetInteger(0, "Downtrend_LowLine", OBJPROP_RAY_RIGHT, true); - } - } - } -} - -//+------------------------------------------------------------------+ -//| Draw Support and Resistance Levels | -//+------------------------------------------------------------------+ -void DrawSupportResistance() -{ - double confirmedHighs[10], confirmedLows[10]; - int confHighCount = 0, confLowCount = 0; - - for (int i = 0; i < LookBackBars - 1; i++) - { - if (zzBuffer[i] != 0) - { - if (iHigh(_Symbol, InpTimeFrame, i) == zzBuffer[i] && confHighCount < 10) - { - confirmedHighs[confHighCount] = zzBuffer[i]; - confHighCount++; - } - else if (iLow(_Symbol, InpTimeFrame, i) == zzBuffer[i] && confLowCount < 10) - { - confirmedLows[confLowCount] = zzBuffer[i]; - confLowCount++; - } - } - } - - int usedHighCount = (confHighCount >= 4) ? confHighCount - 1 : confHighCount; - int usedLowCount = (confLowCount >= 4) ? confLowCount - 1 : confLowCount; - - double majorResistance = -1e9, majorSupport = 1e9; - double minorResistance = -1e9, minorSupport = 1e9; - double tempHigh = -1e9, tempLow = -1e9; - for (int i = 0; i < usedHighCount; i++) - { - if (confirmedHighs[i] > majorResistance) - { - tempHigh = majorResistance; - majorResistance = confirmedHighs[i]; - } - else if (confirmedHighs[i] > tempHigh) - { - tempHigh = confirmedHighs[i]; - } - } - if (tempHigh > -1e9) - minorResistance = tempHigh; - for (int i = 0; i < usedLowCount; i++) - { - if (confirmedLows[i] < majorSupport) - { - tempLow = majorSupport; - majorSupport = confirmedLows[i]; - } - else if (confirmedLows[i] < tempLow) - { - tempLow = confirmedLows[i]; - } - } - if (tempLow < 1e9) - minorSupport = tempLow; - - if (usedHighCount > 0) - { - if (!ObjectCreate(0, "Major_Resistance", OBJ_HLINE, 0, 0, majorResistance)) - Print("Failed to create Major Resistance"); - else - ObjectSetInteger(0, "Major_Resistance", OBJPROP_COLOR, clrMagenta); - - if (minorResistance > -1e9 && minorResistance < majorResistance) - { - if (!ObjectCreate(0, "Minor_Resistance", OBJ_HLINE, 0, 0, minorResistance)) - Print("Failed to create Minor Resistance"); - else - ObjectSetInteger(0, "Minor_Resistance", OBJPROP_COLOR, clrFuchsia); - } - } - if (usedLowCount > 0) - { - if (!ObjectCreate(0, "Major_Support", OBJ_HLINE, 0, 0, majorSupport)) - Print("Failed to create Major Support"); - else - ObjectSetInteger(0, "Major_Support", OBJPROP_COLOR, clrAqua); - - if (minorSupport < 1e9 && minorSupport > majorSupport) - { - if (!ObjectCreate(0, "Minor_Support", OBJ_HLINE, 0, 0, minorSupport)) - Print("Failed to create Minor Support"); - else - ObjectSetInteger(0, "Minor_Support", OBJPROP_COLOR, clrBlue); - } - } -} -//+------------------------------------------------------------------+ diff --git a/Documents/BKP/backtester.temp.mq5 b/Documents/BKP/backtester.temp.mq5 deleted file mode 100644 index e01c1c0e..00000000 --- a/Documents/BKP/backtester.temp.mq5 +++ /dev/null @@ -1,1484 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XTest MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XBackTester -// Description: a Backtest Tools Strategy Tester -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -//////////////////////////////////////////////////////x -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XBackTester" -#property strict - -// -#define ShortName "XBackTester" - -// -// Imports ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-chart.helper.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" - -// -// Import Chart Objects ... -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// -// Definitions ... - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Alert ... -// Here we Provider All Requirements for -// Configuring Alert Provider ... -input group "Alert"; -input bool eAEnableAlerts = true; // Enable Alerts -input bool eALogAlerts = true; // Log Alerts -input bool eAMailAlerts = false; // Mail Alerts -input bool eAPushAlerts = false; // Push Alerts -input bool eATerminalAlerts = false; // Terminal Alerts -// -// Define Local Variables ... - -// -string eaLogTag; // EA Log Prefix ... -XCAlert *eaAlert; // Alert Provider for Expert Adviser ... -XCTrade *eaTrader; // Trader of Expert Adviser ... -XCChartHelper *mChartHelper; // Chart Helper Class ... - -// -// Object Props ... - -// -string objSuffix; - -// -CButton btnBuy; -CButton btnSell; -CButton btnClose; -CButton btnCloseAll; - -// -CEdit lblPositionId; - -// -CButton *btnSelectedPosInfo; -CArrayObj selectedPosInfoArr; - -// -int btnCloseSizeX = 0; -int btnCloseSizeY = 0; -int btnCloseStartX = 0; -int btnCloseStartY = 0; -int lblPositionIdSizeX = 0; -int lblPositionIdSizeY = 0; -int lblPositionIdStartX = 0; -int lblPositionIdStartY = 0; - -// -ulong selectedPositionID = 0; - -// -// Position Arrays ... -CArrayObj posArray; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Timer ... - if (!InitTimer()) - { - return INIT_FAILED; - } - - // - // Initialize all Requirements ... - if (!InitEA()) - { - return INIT_FAILED; - } - - // - // Initialize all GUI Objects and Classes ... - if (!InitGUI()) - { - return INIT_FAILED; - } - - // - // Alert Initialization ... - string msg = "Initialized Successfully ..."; - eaAlert.SendAlert(msg); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Destroy Timer ... - DestroyTimer(); - - // - // Destroy all GUI Requirements ... - DestroyGUI(); - - // - // Alert De Initialization Succeeded ... - string msg = "De Initialized Successfully ..."; - eaAlert.SendAlert(msg); - - // - // Destroy all EA Requirements ... - DestroyEA(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - UpdateGUI(); -} - -// -// Handle On Trade Event ... -void OnTrade() -{ - // - eaTrader.HandleOnTrade(); -} - -// -// On Timer ... -void OnTimer() -{ - // - // TODO: Implement Time Based Functionalities ... -} - -// -// Chart Event Handler ... -void OnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // -) -{ -} - -// -// Custom Functions ... - -/** - * Validate all Inputs of Expert Adviser ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - eaSlippage > 0 && - eaMagicNumber > 0 - // - ); - if (!isCommonValid) - { - // - errMessage += "common configurations error;" + "\n"; - } - - // - result = - // - // Common ... - isCommonValid && - // - // Otere ... - true - // - ; - - // - if (!result) - { - // - // Since here Logger not Initiallized, we Use Raw Print Command ... - Print(ShortName + " Errors: \n", errMessage); - } - - // - return result; -} - -/** - * Initialize Timer ... - * - * @return ( bool ) - */ -bool InitTimer() -{ - // - bool result = false; - - // - // TODO: Initialize Timer if necessary ... - // result = EventSetTimer(1); - // result = EventSetMillisecondTimer(100); - result = true; - - // - return result; -} - -/** - * Destroy Timer ... - */ -void DestroyTimer() -{ - // - // TODO: Use This ... - // EventKillTimer(); -} - -/** - * Initialize all Requirements for Working Fine ... - * - * @return ( bool ) - */ -bool InitEA() -{ - // - bool result = false; - - // - // Locally Apply Changes on Prefix ... - eaLogTag = ShortName + ">" + eaLogSuffix; - - // - // Create Instance of Alert Class and Configure it ... - eaAlert = new XCAlert(); - eaAlert.SetPrefix(eaLogTag); - eaAlert.SetLogAlerts(eALogAlerts); - eaAlert.SetMailAlerts(eAMailAlerts); - eaAlert.SetPushAlerts(eAPushAlerts); - eaAlert.SetEnableAlerts(eAEnableAlerts); - eaAlert.SetTerminalAlerts(eATerminalAlerts); - - // - // Create Trader Instance and Configure it ... - eaTrader = new XCTrade( - eaSlippage, - eaMagicNumber // - ); - - // - // Attach Event Handlers ... - eaTrader.AddOnDealsChangedEventHandler(OnDealsChanged); - eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered); - eaTrader.AddOnOrdersChangedEventHandler(OnOrdersChanged); - eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); - eaTrader.AddOnModifyPositionEventHandler(OnPositionModified); - eaTrader.AddOnPositionsChangedEventHandler(OnPositionsChanged); - eaTrader.AddOnTradeStateChangedEventHandler(OnTradeStateChanged); - eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed); - eaTrader.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed); - - // - // TODO: Fix This ... - result = true; - - // - return result; -} - -/** - * Destroy all Initialized EA Requirements ... - */ -void DestroyEA() -{ - // - delete eaAlert; -} - -// -// GUI Events ... - -/** - * Initialize all GUI Requirements for EA ... - * - * @return ( bool ) - */ -bool InitGUI() -{ - // - bool result = false; - - // - int subWindow = 0; - ulong chartId = ChartID(); - objSuffix = ShortName + "_"; - - // - // Initial Chart Class Instance ... - mChartHelper = new XCChartHelper(chartId); - - // - int startX = 5; - int startY = 25; - - // - int defaultGap = 5; - int defaultWidth = 100; - int defaultHeight = 30; - - // - // Buy ... - int btnBuyStartX = startX; - int btnBuySizeX = startX + defaultWidth; - int btnBuyStartY = startY; - int btnBuySizeY = startY + defaultHeight; - string btnBuyName = objSuffix + "BTN_BUY"; - result = btnBuy.Create( - chartId, - btnBuyName, - subWindow, - btnBuyStartX, - btnBuyStartY, - btnBuySizeX, - btnBuySizeY // - ); - if (result) - { - // - // Apply Buy Button Style ... - - // - btnBuy.Text("Buy"); - btnBuy.Color(clrYellow); - btnBuy.ColorBackground(clrGreen); - } - - // - // Sell ... - int btnSellStartX = btnBuyStartX + btnBuySizeX; - int btnSellSizeX = btnSellStartX + defaultWidth; - int btnSellStartY = btnBuyStartY; - int btnSellSizeY = btnBuySizeY; - string btnSellName = objSuffix + "BTN_SELL"; - result = btnSell.Create( - chartId, - btnSellName, - subWindow, - btnSellStartX, - btnSellStartY, - btnSellSizeX, - btnSellSizeY // - ); - if (result) - { - // - // Apply Sell Button Style ... - - // - btnSell.Text("Sell"); - btnSell.Color(clrYellow); - btnSell.ColorBackground(clrDarkRed); - } - - // - // LABEL Position ID ... - lblPositionIdStartX = btnBuyStartX; - lblPositionIdSizeX = lblPositionIdStartX + defaultWidth; - lblPositionIdStartY = btnSellSizeY + defaultGap; - lblPositionIdSizeY = lblPositionIdStartY + defaultHeight; - string lblPositionIdName = objSuffix + "LBL_POS_ID"; - result = lblPositionId.Create( - chartId, - lblPositionIdName, - subWindow, - lblPositionIdStartX, - lblPositionIdStartY, - lblPositionIdSizeX, - lblPositionIdSizeY // - ); - if (result) - { - // - // Apply Label Position ID Style ... - lblPositionId.ReadOnly(true); - lblPositionId.Text("Pos ID: "); - lblPositionId.Color(clrYellow); - lblPositionId.ColorBackground(clrDarkGray); - } - - // - // Close ... - btnCloseStartX = startX; - btnCloseSizeX = btnCloseStartX + defaultWidth; - btnCloseStartY = lblPositionIdSizeY + defaultGap; - btnCloseSizeY = lblPositionIdSizeY + defaultHeight; - string btnCloseName = objSuffix + "BTN_CLOSE"; - result = btnClose.Create( - chartId, - btnCloseName, - subWindow, - btnCloseStartX, - btnCloseStartY, - btnCloseSizeX, - btnCloseSizeY // - ); - if (result) - { - // - // Apply Close Button Style ... - - // - btnClose.Text("Close"); - btnClose.Color(clrYellow); - btnClose.ColorBackground(clrDarkOrange); - } - - // - // Close All ... - int btnCloseAllStartX = btnCloseSizeX + defaultGap; - int btnCloseAllSizeX = btnCloseAllStartX + defaultWidth; - int btnCloseAllStartY = lblPositionIdSizeY + defaultGap; - int btnCloseAllSizeY = lblPositionIdSizeY + defaultHeight; - string btnCloseAllName = objSuffix + "BTN_CLOSE_ALL"; - result = btnCloseAll.Create( - chartId, - btnCloseAllName, - subWindow, - btnCloseAllStartX, - btnCloseAllStartY, - btnCloseAllSizeX, - btnCloseAllSizeY // - ); - if (result) - { - // - // Apply Close Button Style ... - - // - btnCloseAll.Text("Close All"); - btnCloseAll.Color(clrYellow); - btnCloseAll.ColorBackground(clrDarkRed); - } - - // - UpdateGUIState(); - - // - return result; -} - -/** - * Update GUI based on Each Ticks ... - */ -void UpdateGUI() -{ - // - UpdateGUIState(); - - // - // Buy Button Pressed ... - if (btnBuy.Pressed()) - { - // - HandleBuyTrade(); - btnBuy.Pressed(false); - } - - // - // Sell Button Pressed ... - if (btnSell.Pressed()) - { - // - HandleSellTrade(); - btnSell.Pressed(false); - } - - // - // Close Button Pressed ... - if (btnClose.Pressed()) - { - // - if (btnClose.IsEnabled()) - { - // - if (selectedPositionID > 0) - { - HandleCloseTrade(selectedPositionID); - } - } - - // - btnClose.Pressed(false); - } - - // - // Close All Button Pressed ... - if (btnCloseAll.Pressed()) - { - // - if (btnCloseAll.IsEnabled()) - { - HandleCloseTrade(0); - } - - // - btnCloseAll.Pressed(false); - } - - // - // Check Show Hide Selected Position Info ... - if (btnSelectedPosInfo != NULL) - { - // - if (btnSelectedPosInfo.Pressed()) - { - // - // Check Enable ... - if (btnSelectedPosInfo.IsEnabled()) - { - // - // Handle Toggle Show/Hide lblSelectedPositionInfo ... - CEdit *iLbl = NULL; - bool isVisible = false; - int count = selectedPosInfoArr.Total(); - if (IsValidSize(count)) - { - // - // Loop Through Labels ... - for (int i = 0; i < count; i++) - { - // - iLbl = (CEdit *)selectedPosInfoArr.At(i); - isVisible = iLbl.IsVisible(); - if (isVisible) - { - iLbl.Hide(); - } - else - { - iLbl.Show(); - } - } - - // - // Update Button Text ... - isVisible = iLbl.IsVisible(); - string btnText = isVisible - ? "Hide Info" - : "Show Info"; - btnSelectedPosInfo.Text(btnText); - } - - // - ZeroMemory(iLbl); - } - - // - btnSelectedPosInfo.Pressed(false); - } - } - - // - // Check Positions Buttons ... - int posCount = posArray.Total(); - bool has = IsValidSize(posCount); - if (has) - { - // - for (int i = 0; i < posCount; i++) - { - // - CButton *iBtn = (CButton *)posArray.At(i); - - // - if (iBtn.Pressed()) - { - // - if (iBtn.IsEnabled()) - { - // - ulong posID = ExtractPositionIDFromButtonName(iBtn.Name()); - if (posID > 0 && selectedPositionID != posID) - { - selectedPositionID = posID; - UpdateGUIState(); - } - } - - // - iBtn.Pressed(false); - } - - // - ZeroMemory(iBtn); - } - } -} - -/** - * Destroy all Initialized GUi Requirements ... - */ -void DestroyGUI() -{ - // - delete mChartHelper; - ZeroMemory(mChartHelper); - - // - delete btnSelectedPosInfo; - ZeroMemory(btnSelectedPosInfo); -} - -// -// Trade Event Handlers ... - -/** - * Handle StopLoss Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnStopLossTriggered(const XDeal &deal) -{ - // - UpdatePositionButtons(); -} - -/** - * Handle Take Profit Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnTakeProfitTriggered(const XDeal &deal) -{ - // - UpdatePositionButtons(); -} - -/** - * Handle Force Close a Position ... - * - * @param ticket: ULONG ... - * @param position: XPosition instance ... - * @param comment: String ... - */ -void OnPositionForceClosed( - const ulong ticket, - const XPosition &position, - const string comment // -) -{ - // - UpdatePositionButtons(); -} - -/** - * Handle Deals Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnDealsChanged(int count) -{ -} - -/** - * Handle Orders Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnOrdersChanged(int count) -{ -} - -/** - * Handle Positions Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnPositionsChanged(int count) -{ - // - // Update Position Buttons ... - UpdatePositionButtons(); -} - -/** - * Handle Position Modified ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionModified( - const ulong ticket, - const double profit, - const string comment // -) -{ -} - -/** - * Handle Position Partial Closed ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionPartialClosed( - const ulong ticket, - const double profit, - const string comment // -) -{ -} - -/** - * Handle Trade State Changed ... - * - * @param state: XOnTradeHandlerState instance ... - */ -void OnTradeStateChanged(const XOnTradeHandlerState &state) -{ -} - -// -// GUI Event Handlers and Helpers ... - -// -void HandleBuyTrade() -{ - HandleTrade(X_DIRECTION_BULLISH); -} - -// -void HandleSellTrade() -{ - HandleTrade(X_DIRECTION_BEARISH); -} - -// -void HandleTrade(ENUM_X_DIRECTION dir) -{ - // - if (!HasDirection(dir)) - { - return; - } - - // - string symbol = mChartHelper.Symbol(); - ENUM_TIMEFRAMES period = mChartHelper.Period(); - - // - bool isBullish = IsSpecifiedBullish(dir); - - // - double r2r = 1.5; - double volume = 0.01; - double riskInPoints = 100; - double point = GetPoints(symbol); - double entry = GetEntry(symbol, dir); - - // - double risk = riskInPoints * point; - double reward = risk * r2r; - - // - double sl = isBullish - ? entry - risk - : entry + risk; - double tp = isBullish - ? entry + reward - : entry - reward; - - // - string comment = ShortName + "_POS_" + ToXString(dir); - - // - if (isBullish) - { - // - eaTrader.Buy( - symbol, - period, - volume, - entry, - sl, - tp, - comment // - ); - } - else - { - // - eaTrader.Sell( - symbol, - period, - volume, - entry, - sl, - tp, - comment // - ); - } -} - -// -void HandleCloseTrade(ulong positionID) -{ - // - if (positionID == 0) - { - // - XPosition positions[]; - int count = eaTrader.GetPositions( - positions // - ); - bool has = IsValidSize(count); - if (has) - { - // - int closedCount = eaTrader.Close(positions); - has = IsValidSize(closedCount); - } - } - else - { - // - XPosition position; - bool has = eaTrader.GetPosition( - positionID, - position // - ); - if (has) - { - // - has = eaTrader.Close(positionID); - } - } -} - -// -ulong ExtractPositionIDFromButtonName(string name) -{ - // - ulong result = 0; - - // - string nameParts[]; - int namePartsCount = SplitContent(nameParts, name, "_"); - bool has = IsValidSize(namePartsCount); - if (has) - { - // - string lastPart = nameParts[namePartsCount - 1]; - StringReplace(lastPart, "_", ""); - result = (long)lastPart; - } - - // - ZeroMemory(nameParts); - - // - return result; -} - -// -void UpdatePositionButtons() -{ - // - // Retrieve Positions ... - XPosition positions[]; - int count = eaTrader.GetPositions( - positions // - ); - bool has = IsValidSize(count); - if (!has) - { - // - posArray.Clear(); - selectedPositionID = 0; - UpdateGUIState(); - return; - } - - // - posArray.Clear(); - - // - // Selected Position ID ... - bool isSelectdPositionIDExists = false; - if (has && selectedPositionID > 0) - { - // - for (int i = 0; i < count; i++) - { - // - if (!isSelectdPositionIDExists && - positions[i].ticket == selectedPositionID) - { - // - isSelectdPositionIDExists = true; - break; - } - } - } - if (!isSelectdPositionIDExists || - selectedPositionID == 0) - { - // - XPosition youngest; - int youngestIDX = GetXYoungest(youngest, positions); - bool hasYoungest = IsValidIndex(youngestIDX) && - youngest.IsValid(); - if (hasYoungest) - { - selectedPositionID = youngest.ticket; - } - - // - youngest.Clean(); - } - - // - int subWindow = 0; - ulong chartId = mChartHelper.ChartId(); - - // - int btnWidth = 25; - - // - int lastX = lblPositionIdSizeX + 5; - int lastSizeX = lastX + btnWidth; - - // - int lastY = lblPositionIdStartY; - int lastSizeY = lblPositionIdSizeY; - - // - for (int i = 0; i < count; i++) - { - // - XPosition iPos = positions[i]; - - // - string posTypeStr = IsLong(iPos.type) - ? "LONG" - : "SHORT"; - - // - int iPosBtnX = lastX; - int iPosBtnSizeX = iPosBtnX + btnWidth; - string iPosBtnName = objSuffix + "_" + posTypeStr + "_POS_SELECT_BTN_" + ToXString(iPos.ticket); - - // - CButton *iPosBtn = new CButton(); - has = iPosBtn.Create( - chartId, - iPosBtnName, - subWindow, - iPosBtnX, - lastY, - iPosBtnSizeX, - lastSizeY // - ); - if (has) - { - // - // Apply Styles ... - string iPosBtnText = ToXString(iPos.ticket); - - // - iPosBtn.Text(iPosBtnText); - iPosBtn.Color(clrWhite); - - // - color iPosBtnBG = IsLong(iPos.type) - ? clrGreen - : clrDarkRed; - iPosBtn.ColorBackground(iPosBtnBG); - - // - lastX = iPosBtnSizeX + 5; - - // - if (selectedPositionID == iPos.ticket) - { - iPosBtn.Disable(); - } - - // - posArray.Add(iPosBtn); - } - - // - iPos.Clean(); - } - - // - ZeroMemory(positions); - UpdateGUIState(); -} - -// -void UpdateGUIState() -{ - // - // Update States Of Position Select Buttons ... - int count = posArray.Total(); - bool has = IsValidSize(count) && selectedPositionID > 0; - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - CButton *iBtn = (CButton *)posArray.At(i); - - // - ulong posID = ExtractPositionIDFromButtonName(iBtn.Name()); - - // - // Select Position ... - XPosition iPos; - bool hasPosition = eaTrader.GetPosition( - posID, - iPos // - ); - string iTooltip = - !hasPosition - ? "" - : IsLong(iPos.type) - ? "Long" - : "Short"; - - // - if (posID == selectedPositionID) - { - // - iBtn.Disable(); - iBtn.ColorBackground(clrDarkGray); - } - else - { - // - iBtn.Enable(); - - // - color iBtnBG = IsLong(iPos.type) - ? clrGreen - : clrDarkRed; - - // - iBtn.ColorBackground(iBtnBG); - } - - // - ZeroMemory(iBtn); - } - } - - // - // Update State of Close All ... - if (has && count > 1) - { - // - btnCloseAll.Enable(); - btnCloseAll.ColorBackground(clrDarkRed); - } - else - { - // - btnCloseAll.Disable(); - btnCloseAll.ColorBackground(clrDarkGray); - } - - // - // Update Selected Position Info Button State ... - if (has) - { - // - // Reading Global Chart Info ... - int subWindow = 0; - int chartWidth = mChartHelper.Width(); - ulong chartId = mChartHelper.ChartId(); - - // - // Read Selected Position ... - XPosition selectedPosition; - bool hasPosition = eaTrader.GetPosition( - selectedPositionID, - selectedPosition // - ); - - // - // Read All Positions ... - double profits = 0; - XPosition positions[]; - string positionsInfo = ""; - int positionsCount = eaTrader.GetPositions(positions); - has = IsValidSize(positionsCount); - if (has) - { - // - for (int i = 0; i < positionsCount; i++) - { - profits += positions[i].profit; - } - - // - if (positionsCount > 1) - { - positionsInfo = "Positions Count: " + ToXString(positionsCount) + ", Profits: " + ToXString(profits); - } - } - - // - if (hasPosition) - { - // - // Preparing Position Info ... - string posTicket = "Ticket: " + ToXString(selectedPosition.ticket); - string posType = "Type: " + ToXString(selectedPosition.type); - string posSymbolPeriod = - "Symbol: " + selectedPosition.symbol + ", " + - "Period: " + ToXString(selectedPosition.period); - string posProfit = "Profit: " + ToXString(selectedPosition.profit); - string posRiskToRewardRatio = "RiskToReward: " + ToXString(selectedPosition.GetRiskRewardRatio()); - string accountInfo = - "Balance: " + ToXString(eaTrader.mAccount.GetBalance()) + ", " + - "Equity: " + ToXString(eaTrader.mAccount.GetEquity()); - - // - string posInfos[]; - - // - // Ticket ... - Add( - posTicket, - posInfos // - ); - - // - // Type ... - Add( - posType, - posInfos // - ); - - // - // Symbol Period ... - Add( - posSymbolPeriod, - posInfos // - ); - - // - // Profit ... - Add( - posProfit, - posInfos // - ); - - // - // Risk to Reward Ratio ... - Add( - posRiskToRewardRatio, - posInfos // - ); - - // - // Add Positions Info if Exists ... - if (IsSpecifiedValid(positionsInfo)) - { - // - Add( - positionsInfo, - posInfos // - ); - - // - // Clear Info Array ... - selectedPosInfoArr.Clear(); - } - - // - // Adding Account Info ... - Add( - accountInfo, - posInfos // - ); - - // - // Create Button If Not Exists ... - if (btnSelectedPosInfo == NULL) - { - // - btnSelectedPosInfo = new CButton(); - - // - string name = objSuffix + "BTN_TOOGLE_SPOS_INFO"; - - // - int btnStartX = btnCloseStartX; - int btnSizeX = btnStartX + 200 + 5; - - // - int btnStartY = btnCloseSizeY + 5; - int btnSizeY = btnStartY + 50; - - // - bool isCreated = btnSelectedPosInfo.Create( - chartId, - name, - subWindow, - btnStartX, - btnStartY, - btnSizeX, - btnSizeY // - ); - if (!isCreated) - { - // - delete btnSelectedPosInfo; - ZeroMemory(btnSelectedPosInfo); - } - else - { - // - // Apply Styles ... - btnSelectedPosInfo.Color(clrYellow); - btnSelectedPosInfo.ColorBackground(clrDarkBlue); - } - } - - // - // Check Btn Exists ... - has = btnSelectedPosInfo != NULL; - if (has) - { - // - int posInfoCount = ArraySize(posInfos); - int lblInfoCount = selectedPosInfoArr.Total(); - has = IsValidSize(lblInfoCount) && lblInfoCount == posInfoCount; - - // - // Create info Labels ... - if (!has) - { - // - selectedPosInfoArr.Clear(); - has = IsValidSize(posInfoCount); - if (has) - { - // - // Creat Info Control ... - - // - string name = objSuffix + "LBL_SPOS_INFO"; - - // - int lblHeight = 25; - int lblWidth = 450; - - // - int startX = chartWidth - lblWidth - 5; - int sizeX = startX + lblWidth; - - // - int startY = 5; - int sizeY = startY + lblHeight; - - // - // Loop through Position Info's Array to Create Label Controls ... - for (int i = 0; i < posInfoCount; i++) - { - // - string iText = posInfos[i]; - string iTextMD5 = ToMD5(iText); - - // - string iName = name + "_" + iTextMD5; - - // - int iX1 = startX; - int iX2 = sizeX; - - // - int iY1 = startY; - int iY2 = startY + lblHeight; - - // - CEdit *iLbl = new CEdit(); - bool isCreated = iLbl.Create( - chartId, - iName, - subWindow, - iX1, - iY1, - iX2, - iY2 // - ); - if (isCreated) - { - // - iLbl.Text(iText); - iLbl.Color(clrYellow); - iLbl.ColorBorder(clrDarkSlateGray); - iLbl.ColorBackground(clrDarkSlateGray); - - // - selectedPosInfoArr.Add(iLbl); - - // - startY = iY2; - } - } - } - } - - // - // Update Info Labels ... - lblInfoCount = selectedPosInfoArr.Total(); - has = IsValidSize(lblInfoCount); - if (has) - { - // - CEdit *iLbl = NULL; - - // - // Loop Through Infos ... - for (int i = 0; i < lblInfoCount; i++) - { - // - iLbl = (CEdit *)selectedPosInfoArr.At(i); - - // - iLbl.Text(posInfos[i]); - } - - // - bool isVisible = iLbl.IsVisible(); - string btnText = isVisible - ? "Hide Info" - : "Show Info"; - btnSelectedPosInfo.Text(btnText); - - // - ZeroMemory(iLbl); - } - } - - // - ZeroMemory(posInfos); - } - - // - SpecifiedClean(positions); - } - else - { - // - // Toggle Selected Position Btn ... - if (btnSelectedPosInfo != NULL) - { - // - btnSelectedPosInfo.Destroy(); - - // - delete btnSelectedPosInfo; - ZeroMemory(btnSelectedPosInfo); - } - - // - // Selected Position Lbls ... - selectedPosInfoArr.Clear(); - } - - // - // Update State of BtnClose and BtnClose All ... - if (selectedPositionID == 0) - { - // - btnClose.Disable(); - btnClose.ColorBackground(clrDarkGray); - } - else - { - // - btnClose.Enable(); - btnClose.ColorBackground(clrDarkOrange); - } -} - -// \ No newline at end of file diff --git a/Documents/BKP/signaller.xfima.drawing.tmp.mq5 b/Documents/BKP/signaller.xfima.drawing.tmp.mq5 deleted file mode 100644 index d63e9a02..00000000 --- a/Documents/BKP/signaller.xfima.drawing.tmp.mq5 +++ /dev/null @@ -1,208 +0,0 @@ - -// -// Draw Market Analysis ... -// has = iStructure.pvAnalysis.IsValid(); -// if (has) -// { -// // -// XBoxZone iBox; -// XCBoxObject *iBoxObj; - -// -// poiDrawer.RemoveDraws(); - -// // -// has = iStructure.pvAnalysis.HasSupportBox(iBox); -// if (has) -// { -// // -// iBox.to = iBar.time; -// poiDrawer.DrawBox( -// iBox, -// iBoxObj, -// true, -// iBox.type // -// ); -// } - -// // -// ZeroMemory(iBoxObj); -// has = iStructure.pvAnalysis.HasResistanceBox(iBox); -// if (has) -// { -// // -// iBox.to = iBar.time; -// poiDrawer.DrawBox( -// iBox, -// iBoxObj, -// true, -// iBox.type // -// ); -// } -// } - -// // -// // Draw Zones ... -// has = HasChild(iStructure.supports); -// if (has) { -// // -// CArrayObj *iSupportObjs; -// poiDrawer.DrawBoxes( -// iStructure.supports, -// iSupportObjs, -// true // -// ); -// } - -// // -// has = HasChild(iStructure.resistances); -// if (has) { -// // -// CArrayObj *iResistanceObjs; -// poiDrawer.DrawBoxes( -// iStructure.resistances, -// iResistanceObjs, -// true // -// ); -// } - -// -// Detecte Fibo Section Changes ... - -// // -// has = fimaHelper.IsFiboSectionChanged(iDir, iBar.Index()); -// has = has && -// IsXBullish(iDir) && -// fimaHelper.IsValeOverLast(iBar.Index()); - -// // -// has = fimaHelper.IsFiboSectionChanged(iDir, iBar.Index()); -// has = has && -// IsXBearish(iDir) && -// fimaHelper.IsPeakUnderLast(iBar.Index()); - -// // -// has = fimaHelper.HasFiboPush(iDir, iBar.Index(), 5); - -// // -// XBoxZone fimaZones[]; -// int fimaZonesCount = fimaHelper.DetectXFIMAZones( -// fimaZones, -// iBar.Index(), -// true, // Only Valid Zones ... -// 50, // Number of Zones ... -// 4, // Shadow Multiplier ... -// 1, // Strength ... -// 7, // Validation Length ... -// 500 // Loopback .. -// ); - -// -// XPivot fimaPivots[]; -// int fimaPivotsCount = fimaHelper.DetecteXFIMAPivots( -// fimaPivots, -// iBar.Index(), -// 50, // Number of Pivots ... -// 7, // Validation Length ... -// 500 // Loopback ... -// ); - -// // -// has = IsValidSize(fimaZonesCount); -// if (has) -// { -// // -// // Draw Detected Zones ... -// for (int i = 0; i < fimaZonesCount; i++) -// { -// // -// XCBoxObject *iObj; -// has = poiDrawer.DrawBox( -// fimaZones[i], -// iObj, -// true, // Ignore At ... -// fimaZones[i].type // Specified Name ... -// ); -// if (has) -// { -// zoneObjects.Add(iObj); -// } -// } -// } - -// // -// has = IsValidSize(fimaPivotsCount); -// if (has) -// { -// // -// // Draw Detected Pivots ... -// for (int i = 0; i < fimaPivotsCount; i++) -// { -// // -// XCBarArrowObject *iObj; -// has = poiDrawer.DrawPivot( -// fimaPivots[i], -// iObj); -// if (has) -// { -// pivotObjects.Add(iObj); -// } -// } -// } - -// -// Detect DecisionBars ... -// XOHCL decisionBars[]; -// int decisionBarsCount = 0; -// ENUM_X_DIRECTION decisionBarDirs[]; -// decisionBarsCount = fimaHelper.DetectXFIMAPOIBars( -// decisionBars, -// decisionBarDirs, -// iBar.Index(), -// X_DIRECTION_ALL, // For Dir ... -// 300 // Required Number of Bars ... -// ); -// decisionBarsCount = fimaHelper.DetectXFIMAReversalPOIBars( -// decisionBars, -// decisionBarDirs, -// iBar.Index(), -// true, // Force Touch Boundary ... -// X_DIRECTION_ALL, // For Dir ... -// 300 // Required Number of Bars ... -// ); -// decisionBarsCount = fimaHelper.DetectXFIMAContinuationalPOIBars( -// decisionBars, -// decisionBarDirs, -// iBar.Index(), -// true, -// X_DIRECTION_ALL, // For Dir ... -// 300 // Required Number of Bars ... -// ); - -// // -// has = IsValidSize(decisionBarsCount); -// if (has) -// { -// // -// for (int i = 0; i < decisionBarsCount; i++) -// { -// // -// XCBarArrowObject *iObj; -// has = poiDrawer.DrawBarArrow( -// decisionBars[i], -// iObj, -// IsXBullish(decisionBarDirs[i]) ? X_PRICE_LOW : X_PRICE_HIGH, -// 159, -// IsXBullish(decisionBarDirs[i]) ? clrAqua : clrMagenta, -// 5, -// IsXBullish(decisionBarDirs[i]) ? ANCHOR_TOP : ANCHOR_BOTTOM, -// "XOHCL_" + ToXString(TimeToSeconds(decisionBars[i].time)), -// true, // Ignore Bar Tag ... -// 5 // Threshold ... -// ); -// if (has) -// { -// barObjects.Add(iObj); -// } -// } -// } diff --git a/Documents/BKP/support and resistances.bkp.mq5 b/Documents/BKP/support and resistances.bkp.mq5 deleted file mode 100644 index 764d816f..00000000 --- a/Documents/BKP/support and resistances.bkp.mq5 +++ /dev/null @@ -1,76 +0,0 @@ - if (result) - { - // - XOHCL tmpBar; - int tmpIDX = -1; - bool has = false; - double upper = 0; - double lower = 0; - int length = zone.GetAge(); - - // - // Support ... - tmpIDX = bar.FindLowestIndex(length, MODE_LOW); - if (IsValidIndex(tmpIDX)) - { - // - if (tmpBar.Init(symbol, period, tmpIDX)) - { - // - lower = iLow(symbol, period, tmpIDX); - upper = bar.FindLowest(length, MODE_CLOSE); - if (upper <= lower) - { - upper = tmpBar.GetDown(); - } - - // - has = support.Init( - symbol, - period, - upper, - lower, - tmpBar.time, - bar.time, - X_DIRECTION_BULLISH, - ToXString(X_BAR_PATTERN_SUPPORT) // - ); - - // - tmpBar.Clean(); - } - } - - // - // Resistance ... - tmpIDX = bar.FindHighestIndex(length, MODE_HIGH); - if (IsValidIndex(tmpIDX)) - { - // - if (tmpBar.Init(symbol, period, tmpIDX)) - { - // - upper = iHigh(symbol, period, tmpIDX); - lower = bar.FindHighest(length, MODE_CLOSE); - if (upper <= lower) - { - upper = tmpBar.GetUp(); - } - - // - has = resistance.Init( - symbol, - period, - upper, - lower, - tmpBar.time, - bar.time, - X_DIRECTION_BEARISH, - ToXString(X_BAR_PATTERN_RESISTANCE) // - ); - - // - tmpBar.Clean(); - } - } - } diff --git a/Documents/BKP/test-xpv.ind.mq5 b/Documents/BKP/test-xpv.ind.mq5 deleted file mode 100644 index 24cd2f7a..00000000 --- a/Documents/BKP/test-xpv.ind.mq5 +++ /dev/null @@ -1,765 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XFIMAPV -// Description: Integrates All Requirements inside -// this indicator for analyse Markets Based on OM1 ... -// -// -// 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 XFIMA Indicator" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -// Definitions ... - -// -#define ShortName "XFIMA" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -// Calculation ... -input group "Calculation"; -input int pvValidationLength = 7; // Peaks and Vales Validation Length -input int pvValidationCount = 2; // Recent Peak or Vale must under/over latests -input ENUM_X_PRICE peakPriceType = X_PRICE_HIGH; // Peak Calculated Price -input ENUM_X_PRICE valePriceType = X_PRICE_LOW; // Vale Calculated Price - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show Peaks and Vales -input bool showHL = true; // Show Highs and Lows -input int startCalculationForLastBars = 1500; // Calculate Last n Bars -input int peakArrowCode = 159; // Peaks Arrow Code -input int highArrowCode = 159; // Highs Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code -input int lowArrowCode = 159; // Lows Arrow Code - -// -// Non Inputs ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 6 -#property indicator_plots 4 - -// -// Plot Buffers ... - -// -// PEAKS ... - -// -#define peakBufferIndex 0 -double peakBuffer[]; - -// -#define peakBufferPlotIndex 0 -#property indicator_label1 "PEAK" -#property indicator_type1 DRAW_ARROW -#property indicator_color1 clrMagenta -#property indicator_width1 3 - -// -// VALES ... - -// -#define valeBufferIndex 1 -double valeBuffer[]; - -// -#define valeBufferPlotIndex 1 -#property indicator_label2 "VALE" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrAqua -#property indicator_width2 3 - -// -// HIGHS ... - -// -#define highBufferIndex 2 -double highBuffer[]; - -// -#define highBufferPlotIndex 2 -#property indicator_label3 "HIGH" -#property indicator_type3 DRAW_ARROW -#property indicator_color3 clrOrangeRed -#property indicator_width3 3 - -// -// LOWS ... - -// -#define lowBufferIndex 3 -double lowBuffer[]; - -// -#define lowBufferPlotIndex 3 -#property indicator_label4 "LOW" -#property indicator_type4 DRAW_ARROW -#property indicator_color4 clrYellow -#property indicator_width4 3 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 3 - -// -#define highRawBufferIndex mLastBufferIndex + 1 -double highRawBuffer[]; - -// -#define lowRawBufferIndex mLastBufferIndex + 2 -double lowRawBuffer[]; - -// -// Variables ... - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // 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 ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - has = InitRequirements(); - if (!has) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -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 - - // - // De Initialize all Handlers and etc ... -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - 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); - - // - // Validate Calculated Bars ... - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - IsXValid(peakPriceType) && - IsXValid(valePriceType) && - NotEmptyZero(pvValidationLength) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(result, pvValidationLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // PV ... - - // - ENUM_DRAW_TYPE pvDrawType = showPV ? DRAW_ARROW : DRAW_NONE; - - // - // PEAK ... - - // - ArraySetAsSeries(peakBuffer, true); - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ArraySetAsSeries(valeBuffer, true); - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // HL ... - - // - ENUM_DRAW_TYPE hlDrawType = showHL ? DRAW_ARROW : DRAW_NONE; - - // - // HIGH ... - - // - ArraySetAsSeries(highBuffer, true); - SetIndexBuffer(highBufferIndex, highBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(highBufferPlotIndex, PLOT_SHOW_DATA, showHL); - PlotIndexSetInteger(highBufferPlotIndex, PLOT_DRAW_TYPE, hlDrawType); - - // - PlotIndexSetDouble(highBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(highBufferPlotIndex, PLOT_ARROW, highArrowCode); - - // - // LOW ... - - // - ArraySetAsSeries(lowBuffer, true); - SetIndexBuffer(lowBufferIndex, lowBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lowBufferPlotIndex, PLOT_SHOW_DATA, showHL); - PlotIndexSetInteger(lowBufferPlotIndex, PLOT_DRAW_TYPE, hlDrawType); - - // - PlotIndexSetDouble(lowBufferPlotIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(lowBufferPlotIndex, PLOT_ARROW, lowArrowCode); - - // - // Data Buffers ... - - // - ArraySetAsSeries(lowRawBuffer, true); - SetIndexBuffer(lowRawBufferIndex, lowRawBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(highRawBuffer, true); - SetIndexBuffer(highRawBufferIndex, highRawBuffer, INDICATOR_CALCULATIONS); -} - -/** - * Initial all Indicator Requirements ... - * - * @return ( false ) - * - */ -bool InitRequirements() -{ - // - bool result = true; - - // - // Handlers ... - - // - return result; -} - -/** - * Calculate Custom Buffers ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Calculate Bars Limit and First Bar Index ... - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - if (barsLimit == 0) - { - // - barsLimit = ratesTotal; - firstBarIndex = barsLimit - 1; - } - else - { - firstBarIndex = startCalculationForLastBars; - } - - // - // bool canCalculate = true; - bool canCalculate = - barIndex <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(barIndex); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - // TODO: Fill Buffers as Empty ... - lowBuffer[barIndex] = emptyValue; - highBuffer[barIndex] = emptyValue; - peakBuffer[barIndex] = emptyValue; - valeBuffer[barIndex] = emptyValue; - highRawBuffer[barIndex] = emptyValue; - lowRawBuffer[barIndex] = emptyValue; -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Common Requirements ... - - // - FillBuffersZero(barIndex); - - // - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - - // - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Calculate Highs and Lows ... - XOHCL iBar; - bool has = iBar.Init( - _Symbol, - _Period, - barIndex // - ); - if (!has) - { - return; - } - - // - int lowestIDX = -1; - double iRawLow = iBar.FindLowest( - lowestIDX, - pvValidationLength, - valePriceType // - ); - - // - int highestIDX = -1; - double iRawHigh = iBar.FindHighest( - highestIDX, - pvValidationLength, - peakPriceType // - ); - - // - lowRawBuffer[barIndex] = iRawLow; - highRawBuffer[barIndex] = iRawHigh; - - // - lowBuffer[barIndex] = iRawLow; - highBuffer[barIndex] = iRawHigh; - - // - if (barIndex < firstBarIndex - (pvValidationLength + 1)) - { - // - double tmp[]; - ArrayCopy( - tmp, - lowRawBuffer, - 0, - barIndex, - pvValidationLength // - ); - double minLow = GetMin(tmp); - bool isLow = iRawLow < minLow; - lowBuffer[barIndex] = - isLow - ? iRawLow - : lowBuffer[lastBarIndex]; - - // - XClean(tmp); - ArrayCopy( - tmp, - highRawBuffer, - 0, - barIndex, - pvValidationLength // - ); - double maxHigh = GetMax(tmp); - bool isHigh = iRawHigh > maxHigh; - highBuffer[barIndex] = - isHigh - ? iRawHigh - : highBuffer[lastBarIndex]; - - // - // Cleanup Resources ... - XClean(tmp); - } - - // // - // double iLow = emptyValue; - // // IsLow(iLow, barIndex); - // double iPLow = isFirstBar - // ? iLow - // : lowRawBuffer[lastBarIndex]; - - // // - // double iHigh = emptyValue; - // IsHigh(iHigh, barIndex); - // double iPHigh = isFirstBar - // ? iHigh - // : highRawBuffer[lastBarIndex]; - - // // - // // Clculate Values ... - - // // - // lowRawBuffer[barIndex] = iLow; - // highRawBuffer[barIndex] = iHigh; - - // // - // lowBuffer[barIndex] = NotEmptyZero(iLow) - // ? iLow - // : iPLow; - // highBuffer[barIndex] = NotEmptyZero(iHigh) - // ? iHigh - // : iPHigh; - - // // - // double iP2Low = - // barIndex < maxBarIndex - 2 - // ? lowBuffer[barIndex + 2] - // : emptyValue; - // double iP2High = - // barIndex < maxBarIndex - 2 - // ? highBuffer[barIndex + 2] - // : emptyValue; - - // // - // double mLowValues[]; - // double iVale = emptyValue; - // if (NotEmptyZero(iPLow)) - // { - // Add(iPLow, mLowValues); - // } - // if (NotEmptyZero(iP2Low)) - // { - // Add(iP2Low, mLowValues); - // } - // bool isVale = iLow <= GetMin(mLowValues); - // iVale = isVale - // ? iLow - // : isFirstBar - // ? emptyValue - // : valeBuffer[lastBarIndex]; - // valeBuffer[barIndex] = iVale; - - // // - // double mHighValues[]; - // double iPeak = emptyValue; - // if (NotEmptyZero(iPHigh)) - // { - // Add(iPHigh, mHighValues); - // } - // if (NotEmptyZero(iP2High)) - // { - // Add(iP2High, mHighValues); - // } - // bool isPeak = iHigh >= GetMax(mHighValues); - // iPeak = isPeak - // ? iHigh - // : isFirstBar - // ? emptyValue - // : peakBuffer[lastBarIndex]; - // peakBuffer[barIndex] = iPeak; - - // // - // bool has = - // NotEmptyZero(iLow) || - // NotEmptyZero(iPLow) || - // NotEmptyZero(iHigh) || - // NotEmptyZero(iPHigh); - // if (has) - // { - // } -} - -// \ No newline at end of file diff --git a/Documents/BKP/test.fima.conditions.mq5 b/Documents/BKP/test.fima.conditions.mq5 deleted file mode 100644 index 0e983ce1..00000000 --- a/Documents/BKP/test.fima.conditions.mq5 +++ /dev/null @@ -1,295 +0,0 @@ - -// // -// isBullish = -// // -// // Vales Same ... -// sameVales >= 7 && -// // -// // PBar Patterns ... -// isBarPatternsPassed && -// isPBarCloseOverFast && -// // -// // Validate PullBack based on HK Bond ... -// isPullbackBullish && -// pBar.close > pHKBondLower; - -// -// poiDrawer.DrawPatternAnalysis( -// pBarAnalysis, -// structureDrawConfig.barAnalysisDrawConfig // -// ); - -// // -// if (IsValidSize(zonesCount)) -// { -// // -// poiDrawer.DrawZones( -// zones, -// structureDrawConfig.drawConfig // -// ); -// } - -// // -// if (IsValidSize(affectedZonesCount)) -// { -// // -// poiDrawer.DrawZones( -// affectedZones, -// structureDrawConfig.drawConfig // -// ); -// } - -// -// poiDrawer.DrawZones( -// affectedZonesBullish, -// structureDrawConfig.drawConfig // -// ); - -// // -// poiDrawer.DrawZones( -// affectedZonesBearish, -// structureDrawConfig.drawConfig // -// ); - -// // -// // Update POI Zones ... -// ENUM_X_DETECTOR_ZONE_ACTION zoneActions[]; -// poiDetector.UpdateZones( -// iBar, -// zoneActions // -// // Validation Length ... -// // Required Zones ... -// // Loopback ... -// ); - -// -// Retrieve Conditions ... -// conditions.Clean(); -// has = fimaHelper.GetConditions( -// conditions, -// barIndex, -// 10 // Loopback ... -// ); -// if (!has) -// { -// // -// iBar.Clean(); -// conditions.Clean(); - -// // -// return; -// } - -// -// structure.Clean(); -// poiDetector.AnalyseMarket( -// structure, -// structureConfig, -// barIndex // -// ); -// poiDrawer.drawnObjects.Clear(); -// poiDrawer.DrawMarketStructure( -// structure, -// structureDrawConfig // -// ); - -/** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ -bool StrategyXHasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // -) -{ - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL pBar; - XOHCL p2Bar; - bool isBullish = false; - bool isBearish = false; - XOHCL continuationalBar; - XBoxZone continuationalZones[]; - - // - // Read PBar ... - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading pBar Patterns ... - XPatternAnalysis pBarAnalysis; - poiDetector.AnalyseBarPatterns( - pBar, - pBarAnalysis, - structureConfig.barsAnalysisConfig // - ); - - // - // Check Continuational Pullback ... - bool isContinuationPullBack = poiDetector.IsContinuationPullbackPattern( - pBar, - zone, - continuationalZones, - dir, - continuationalBar, - 3, // Continuational Length ... - true, // Force Continuational Loopback Has Zones ... - true, // Force Continuational Loopback Has Patterns ... - 2, // Pullback Length ... - false // Force Pullback Break ... - ); - - // - // Do ... - - // - isBullish = - // - IsXBullish(dir) && - isContinuationPullBack && - continuationalBar.GetUp() < pBar.GetDown() && - true - // isPBarHasBullishPatterns - // - ; - - // - isBearish = - // - IsXBearish(dir) && - isContinuationPullBack && - continuationalBar.GetDown() > pBar.GetUp() && - true - // isPBarHasBearishPatterns - // - ; - - // - // Validate ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - // zone.to = bar.time; - // poiDrawer.DrawZone(zone, structureDrawConfig.drawConfig); - - // - // Draw Continuational Zones ... - UpdateToTime(continuationalZones, bar.time); - poiDrawer.DrawZones(continuationalZones, structureDrawConfig.drawConfig); - - // - zone.Clean(); - - // - int idx = -1; - if (isBullish) - { - idx = GetHighestBelow(bar.GetDown(), continuationalZones); - } - else - { - idx = GetLowestAbove(bar.GetUp(), continuationalZones); - } - result = IsValidIndex(idx); - if (result) - { - zone = continuationalZones[idx]; - } - - // - if (zone.IsValid()) - { - // - XPOIDrawConfig iConfig = structureDrawConfig.drawConfig; - iConfig.bullishColor = clrYellow; - iConfig.bearishColor = clrYellow; - poiDrawer.DrawZones(continuationalZones, iConfig); - } - - // - // Manage Stops ... - if (result) - { - } - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - p2Bar.Clean(); - continuationalBar.Clean(); - XClean(continuationalZones); - - // - return result; -} diff --git a/Documents/BKP/test.fima.ind.mq5 b/Documents/BKP/test.fima.ind.mq5 deleted file mode 100644 index 0f1cd20a..00000000 --- a/Documents/BKP/test.fima.ind.mq5 +++ /dev/null @@ -1,2523 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XFIMA -// Description: Integrates All Requirements inside -// this indicator for analyse Markets Based on OM1 ... -// -// -// 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 XFIMA Indicator" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -// Definitions ... - -// -// Definitions ... -enum ENUM_X_ZG_SEARCH_MODE -{ - X_ZG_SEARCH_EXTREMUM = 0, // searching for the first extremum - X_ZG_SEARCH_PEAK = 1, // searching for the next ZigZag peak - X_ZG_SEARCH_VALE = -1 // searching for the next ZigZag vale -}; - -// -#define ShortName "XFIMA" - -// -// Imports ... -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Calculation"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// PV ... -input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method - -// -// Others ... -input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level -input double sarStep = 0.02; // SAR Step -input double sarMax = 0.2; // SAR Maximum -input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To -input int maFastLength = 7; // Fast MA Length -input int maSlowLength = 21; // Slow MA Length -input int maBandLength = 21; // MA Bond Length -input int zigzagDepth = 12; // ZigZag Depth -input int zigzagDeviation = 5; // ZigZag Deviation -input int zigzagBackStep = 3; // ZigZag Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode -input bool hkIgnoreShadows = true; // HK Remove noises -input int hkSmoothingLength = 21; // HK Smoothing Length -input ENUM_X_MA_METHOD hkSmoothingMode = X_MA_MODE_EMA; // HK Smoothing Method - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show PV -input bool showHK = true; // Show HK -input bool showSAR = true; // Show Sar -input bool showHKBond = true; // Show HK Bond -input bool showMAFast = true; // Show MA Fast -input bool showMASlow = true; // Show MA Slow -input bool showMABand = true; // Show MA Bond -input bool showZigZag = true; // Show ZigZag -input bool showFiboZone = true; // Show Fibo Zone - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -input int sarArrowCode = 159; // Parabolic Sar Arrow Code -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Non Inputs ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 40 -#property indicator_plots 14 - -// -// Plot Buffers ... - -// -// Fast MA ... - -// -#define maFastBufferIndex 0 -#define maFastBufferPlotIndex 0 -double maFastBuffer[]; - -// -#define maFastColorBufferIndex 1 -double maFastColorBuffer[]; - -// -#property indicator_label1 "FastMA" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrLime, clrLime, clrLime // clrYellow, clrOrangeRed, clrGray -#property indicator_width1 3 - -// -// Slow MA ... - -// -#define maSlowBufferIndex 2 -#define maSlowBufferPlotIndex 1 -double maSlowBuffer[]; - -// -#define maSlowColorBufferIndex 3 -double maSlowColorBuffer[]; - -// -#property indicator_label2 "SlowMA" -#property indicator_type2 DRAW_COLOR_LINE -#property indicator_color2 CLR_NONE, clrRed, clrRed, clrRed // clrLime, clrRed, clrGray -#property indicator_width2 3 - -// -// SAR ... - -// -#define sarBufferIndex 4 -#define sarBufferPlotIndex 2 -double sarBuffer[]; - -// -#define sarColorBufferIndex 5 -double sarColorBuffer[]; - -// -#property indicator_label3 "SAR" -#property indicator_type3 DRAW_COLOR_ARROW -#property indicator_color3 CLR_NONE, clrLime, clrRed, clrGray -#property indicator_width3 2 - -// -// PEAKS ... - -// -#define peakBufferIndex 6 -#define peakBufferPlotIndex 3 -double peakBuffer[]; - -// -#property indicator_label4 "PEAK" -#property indicator_type4 DRAW_ARROW -#property indicator_color4 clrMagenta -#property indicator_width4 3 - -// -// VALES ... - -// -#define valeBufferIndex 7 -#define valeBufferPlotIndex 4 -double valeBuffer[]; - -// -#property indicator_label5 "VALE" -#property indicator_type5 DRAW_ARROW -#property indicator_color5 clrAqua -#property indicator_width5 3 - -// -// FIBO Upper ... - -// -#define fiboUpperBufferIndex 8 -#define fiboUpperBufferPlotIndex 5 -double fiboUpperBuffer[]; - -// -#property indicator_label6 "FIBUP" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrAqua -#property indicator_width6 2 - -// -// FIBO Middle ... - -// -#define fiboMiddleBufferIndex 9 -#define fiboMiddleBufferPlotIndex 6 -double fiboMiddleBuffer[]; - -// -#property indicator_label7 "FIBMID" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrBrown -#property indicator_width7 2 - -// -// FIBO Lower ... - -// -#define fiboLowerBufferIndex 10 -#define fiboLowerBufferPlotIndex 7 -double fiboLowerBuffer[]; - -// -#property indicator_label8 "FIBLO" -#property indicator_type8 DRAW_LINE -#property indicator_color8 clrMagenta -#property indicator_width8 2 - -// -// ZigZag ... - -// -#define zigzagBufferIndex 11 -#define zigzagBufferPlotIndex 8 -double zigzagBuffer[]; - -// -#property indicator_label9 "XZG" -#property indicator_type9 DRAW_SECTION -#property indicator_color9 clrYellow -#property indicator_width9 2 - -// -// MA Upper Boundary ... - -// -#define maUpperBufferIndex 12 -#define maUpperBufferPlotIndex 9 -double maUpperBuffer[]; - -// -#property indicator_label10 "UpperMA" -#property indicator_type10 DRAW_LINE -#property indicator_color10 clrAqua -#property indicator_width10 3 - -// -// MA Lower Boundary ... - -// -#define maLowerBufferIndex 13 -#define maLowerBufferPlotIndex 10 -double maLowerBuffer[]; - -// -#property indicator_label11 "LowerMA" -#property indicator_type11 DRAW_LINE -#property indicator_color11 clrMagenta -#property indicator_width11 3 - -// -// XHK ... - -// -#define hkOpenBufferIndex 14 -double hkOpenBuffer[]; - -// -#define hkHighBufferIndex 15 -double hkHighBuffer[]; - -// -#define hkLowBufferIndex 16 -double hkLowBuffer[]; - -// -#define hkCloseBufferIndex 17 -double hkCloseBuffer[]; - -// -#define hkColorBufferIndex 18 -double hkColorBuffer[]; - -// -#define hkBufferPlotIndex 11 -#property indicator_label12 "XHK Open;XHK High;XHK Low;XHK Close" -#property indicator_type12 DRAW_COLOR_CANDLES -#property indicator_color12 CLR_NONE, clrAqua, clrMagenta, clrGray - -// -#define hkBondUpperBufferIndex 19 -double hkBondUpperBuffer[]; - -// -#define hkBondUpperBufferPlotIndex 12 -#property indicator_label13 "UpperHK" -#property indicator_type13 DRAW_LINE -#property indicator_color13 clrAqua -#property indicator_width13 3 - -// -#define hkBondLowerBufferIndex 20 -double hkBondLowerBuffer[]; - -// -#define hkBondLowerBufferPlotIndex 13 -#property indicator_label14 "LowerHK" -#property indicator_type14 DRAW_LINE -#property indicator_color14 clrMagenta -#property indicator_width14 3 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 20 - -// -// MA ... - -// -#define maFastStateBufferIndex mLastBufferIndex + 1 -double maFastStateBuffer[]; - -// -#define maSlowStateBufferIndex mLastBufferIndex + 2 -double maSlowStateBuffer[]; - -// -// SAR ... - -// -#define sarStateBufferIndex mLastBufferIndex + 3 -double sarStateBuffer[]; - -// -// CYCLES ... - -// -// SC ... - -// -#define sHHBufferIndex mLastBufferIndex + 4 -double sHHBuffer[]; - -// -#define sLLBufferIndex mLastBufferIndex + 5 -double sLLBuffer[]; - -// -// MC ... - -// -#define mHHBufferIndex mLastBufferIndex + 6 -double mHHBuffer[]; - -// -#define mLLBufferIndex mLastBufferIndex + 7 -double mLLBuffer[]; - -// -// LC ... - -// -#define lHHBufferIndex mLastBufferIndex + 8 -double lHHBuffer[]; - -// -#define lLLBufferIndex mLastBufferIndex + 9 -double lLLBuffer[]; - -// -// HC ... - -// -#define hHHBufferIndex mLastBufferIndex + 10 -double hHHBuffer[]; - -// -#define hLLBufferIndex mLastBufferIndex + 11 -double hLLBuffer[]; - -// -// ZigZag ... - -// -#define highsBufferIndex mLastBufferIndex + 12 -double highsBuffer[]; - -// -#define highsTimeBufferIndex mLastBufferIndex + 13 -double highsTimeBuffer[]; - -// -#define lowsBufferIndex mLastBufferIndex + 14 -double lowsBuffer[]; - -// -#define lowsTimeBufferIndex mLastBufferIndex + 15 -double lowsTimeBuffer[]; - -// -// XHK Data ... - -// -#define hkRawHighBufferIndex mLastBufferIndex + 16 -double hkRawHighBuffer[]; - -// -#define hkRawOpenBufferIndex mLastBufferIndex + 17 -double hkRawOpenBuffer[]; - -// -#define hkRawLowBufferIndex mLastBufferIndex + 18 -double hkRawLowBuffer[]; - -// -#define hkRawCloseBufferIndex mLastBufferIndex + 19 -double hkRawCloseBuffer[]; - -// -// Variables, Properties and etc ... - -// -// XMarketCycle sc; -int mSCLength = 0; -ENUM_TIMEFRAMES mSCPeriod = NULL; - -// -// XMarketCycle mc; -int mMCLength = 0; -ENUM_TIMEFRAMES mMCPeriod = NULL; - -// -// XMarketCycle lc; -int mLCLength = 0; -ENUM_TIMEFRAMES mLCPeriod = NULL; - -// -// XMarketCycle hc; -int mHCLength = 0; -ENUM_TIMEFRAMES mHCPeriod = NULL; - -// -int sarHandler = INVALID_HANDLE; -int maFastHandler = INVALID_HANDLE; -int maSlowHandler = INVALID_HANDLE; -int maUpperHandler = INVALID_HANDLE; -int maLowerHandler = INVALID_HANDLE; - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -// Requirements ... -CArrayObj mObjects; -XCPOIDrawer *mDrawer; - -// -double zigzagUppers[]; -double zigzagLowers[]; -int zigzagLowersCount = 0; -int zigzagUppersCount = 0; -int zigzagRecalc = 3; // Number of last extremes for recalculation - -// -double lastZigZagPeak = 0; -datetime lastZigZagPeakTime = NULL; - -// -double lastZigZagVale = 0; -datetime lastZigZagValeTime = NULL; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - has = InitCycles(); - if (!has) - { - return INIT_FAILED; - } - - // - // 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 ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - has = InitRequirements(); - if (!has) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -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 mDrawer; - ZeroMemory(mDrawer); - - // - mObjects.Clear(); - - // - // De Initialize all Handlers and etc ... - IndicatorRelease(sarHandler); - IndicatorRelease(maFastHandler); - IndicatorRelease(maSlowHandler); - IndicatorRelease(maUpperHandler); - IndicatorRelease(maLowerHandler); -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Do ZigZag Calculations Before ArraySet As Series ... - int calculatedZigZags = CalculateZigZag( - 0, - prev_calculated, - rates_total, - open, - high, - close, - low, - tick_volume // - ); - if (calculatedZigZags != rates_total) - { - return prev_calculated; - } - - // - // 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); - - // - // Validate Calculated Bars ... - - // - // MA ... - int maFastCalculatedBars = BarsCalculated(maFastHandler); - int maSlowCalculatedBars = BarsCalculated(maSlowHandler); - int maUpperCalculatedBars = BarsCalculated(maUpperHandler); - int maLowerCalculatedBars = BarsCalculated(maLowerHandler); - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // MA ... - maFastCalculatedBars >= maxLength && - maSlowCalculatedBars >= maxLength && - maUpperCalculatedBars >= maxLength && - maLowerCalculatedBars >= maxLength && - // - // SAR ... - sarCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // MA ... - int copiedMAFasts = CopyBuffer(maFastHandler, MAIN_LINE, 0, limit, maFastBuffer); - int copiedMASlows = CopyBuffer(maSlowHandler, MAIN_LINE, 0, limit, maSlowBuffer); - int copiedMAUppers = CopyBuffer(maUpperHandler, MAIN_LINE, 0, limit, maUpperBuffer); - int copiedMALowers = CopyBuffer(maLowerHandler, MAIN_LINE, 0, limit, maLowerBuffer); - - // - // SAR ... - int copiedSARs = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // MA ... - copiedMAFasts >= limit && - copiedMASlows >= limit && - copiedMAUppers >= limit && - copiedMALowers >= limit && - // - // SAR ... - copiedSARs >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maBandLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(mSCLength, mMCLength); - result = MathMax(result, mLCLength); - result = MathMax(result, mHCLength); - result = MathMax(result, maFastLength); - result = MathMax(result, maSlowLength); - result = MathMax(result, maBandLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Fast MA ... - - // - ArraySetAsSeries(maFastBuffer, true); - SetIndexBuffer(maFastBufferIndex, maFastBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maFastBufferPlotIndex, PLOT_SHOW_DATA, showMAFast); - PlotIndexSetDouble(maFastBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(maFastColorBuffer, true); - SetIndexBuffer(maFastColorBufferIndex, maFastColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(maFastStateBuffer, true); - SetIndexBuffer(maFastStateBufferIndex, maFastStateBuffer, INDICATOR_CALCULATIONS); - - // - // Slow MA ... - - // - ArraySetAsSeries(maSlowBuffer, true); - SetIndexBuffer(maSlowBufferIndex, maSlowBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maSlowBufferPlotIndex, PLOT_SHOW_DATA, showMASlow); - PlotIndexSetDouble(maSlowBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(maSlowColorBuffer, true); - SetIndexBuffer(maSlowColorBufferIndex, maSlowColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(maSlowStateBuffer, true); - SetIndexBuffer(maSlowStateBufferIndex, maSlowStateBuffer, INDICATOR_CALCULATIONS); - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSAR); - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - // PEAK / VALE ... - - // - ENUM_DRAW_TYPE pvDrawType = showPV ? DRAW_ARROW : DRAW_NONE; - - // - // PEAK ... - - // - ArraySetAsSeries(peakBuffer, true); - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ArraySetAsSeries(valeBuffer, true); - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // FIBO Zone ... - - // - ENUM_DRAW_TYPE fiboZoneDrawType = showFiboZone ? DRAW_LINE : DRAW_NONE; - - // - // Upper ... - ArraySetAsSeries(fiboUpperBuffer, true); - SetIndexBuffer(fiboUpperBufferIndex, fiboUpperBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboUpperBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboUpperBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboUpperBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // Middle ... - ArraySetAsSeries(fiboMiddleBuffer, true); - SetIndexBuffer(fiboMiddleBufferIndex, fiboMiddleBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboMiddleBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboMiddleBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboMiddleBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // Lower ... - ArraySetAsSeries(fiboLowerBuffer, true); - SetIndexBuffer(fiboLowerBufferIndex, fiboLowerBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboLowerBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboLowerBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboLowerBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // ZigZag ... - - // - ENUM_DRAW_TYPE zigzagDrawType = showZigZag ? DRAW_SECTION : DRAW_NONE; - - // - SetIndexBuffer(zigzagBufferIndex, zigzagBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_SHOW_DATA, showZigZag); - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_TYPE, zigzagDrawType); - - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(zigzagBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // MA Bond ... - - // - ENUM_DRAW_TYPE maBandDrawType = showMABand ? DRAW_LINE : DRAW_NONE; - - // - // MA Upper Bond ... - - // - ArraySetAsSeries(maUpperBuffer, true); - SetIndexBuffer(maUpperBufferIndex, maUpperBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_SHOW_DATA, showMABand); - PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_DRAW_TYPE, maBandDrawType); - - PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(maUpperBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // MA Lower Bond ... - - // - ArraySetAsSeries(maLowerBuffer, true); - SetIndexBuffer(maLowerBufferIndex, maLowerBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_SHOW_DATA, showMABand); - PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_DRAW_TYPE, maBandDrawType); - - PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(maLowerBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // XHK ... - - // - // XHK Color ... - ArraySetAsSeries(hkColorBuffer, true); - SetIndexBuffer(hkColorBufferIndex, hkColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(hkBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(hkBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(hkOpenBuffer, true); - SetIndexBuffer(hkOpenBufferIndex, hkOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(hkHighBuffer, true); - SetIndexBuffer(hkHighBufferIndex, hkHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(hkLowBuffer, true); - SetIndexBuffer(hkLowBufferIndex, hkLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(hkCloseBuffer, true); - SetIndexBuffer(hkCloseBufferIndex, hkCloseBuffer, INDICATOR_DATA); - - // - // XHK Bond ... - - // - // Upper ... - ArraySetAsSeries(hkBondUpperBuffer, true); - SetIndexBuffer(hkBondUpperBufferIndex, hkBondUpperBuffer, INDICATOR_DATA); - - // - // Lower ... - ArraySetAsSeries(hkBondLowerBuffer, true); - SetIndexBuffer(hkBondLowerBufferIndex, hkBondLowerBuffer, INDICATOR_DATA); - - // - // Data Buffers ... - - // - // CYCLES ... - - // - // SC ... - - // - ArraySetAsSeries(sHHBuffer, true); - SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(sLLBuffer, true); - SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_DATA); - - // - // MC ... - - // - ArraySetAsSeries(mHHBuffer, true); - SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(mLLBuffer, true); - SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_DATA); - - // - // LC ... - - // - ArraySetAsSeries(lHHBuffer, true); - SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(lLLBuffer, true); - SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_DATA); - - // - // HC ... - - // - ArraySetAsSeries(hHHBuffer, true); - SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(hLLBuffer, true); - SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_DATA); - - // - // Highs ... - SetIndexBuffer(highsBufferIndex, highsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(highsTimeBufferIndex, highsTimeBuffer, INDICATOR_CALCULATIONS); - - // - // Lows ... - SetIndexBuffer(lowsBufferIndex, lowsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(lowsTimeBufferIndex, lowsTimeBuffer, INDICATOR_CALCULATIONS); - - // - // XHK Data ... - - // - ArraySetAsSeries(hkRawHighBuffer, true); - SetIndexBuffer(hkRawHighBufferIndex, hkRawHighBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(hkRawOpenBuffer, true); - SetIndexBuffer(hkRawOpenBufferIndex, hkRawOpenBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(hkRawLowBuffer, true); - SetIndexBuffer(hkRawLowBufferIndex, hkRawLowBuffer, INDICATOR_DATA); - - // - ArraySetAsSeries(hkRawCloseBuffer, true); - SetIndexBuffer(hkRawCloseBufferIndex, hkRawCloseBuffer, INDICATOR_DATA); - - // -} - -/** - * Initial Market Cycles ... - * - * @return ( bool ) - */ -bool InitCycles() -{ - // - bool result = false; - - // - int cPeriodSeconds = PeriodSeconds(_Period); - - // - // Find Cycle Period ... - if (scMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mSCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_SHORT, - _Period // - ); - } - else - { - mSCPeriod = scPeriod; - } - - // - if (IsValid(mSCPeriod)) - { - mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (mcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mMCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_MEDIUM, - _Period // - ); - } - else - { - mMCPeriod = mcPeriod; - } - - // - if (IsValid(mMCPeriod)) - { - mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (lcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mLCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_LONG, - _Period // - ); - } - else - { - mLCPeriod = lcPeriod; - } - - // - if (IsValid(mLCPeriod)) - { - mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (hcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mHCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mHCPeriod = hcPeriod; - } - - // - if (IsValid(mHCPeriod)) - { - mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; - } - - // - result = mSCLength > 0 && - mMCLength > mSCLength && - mLCLength > mMCLength && - mHCLength > mLCLength; - - // - return result; -} - -/** - * Initial all Indicator Requirements ... - * - * @return ( false ) - * - */ -bool InitRequirements() -{ - // - bool result = false; - - // - // Handlers ... - - // - // Fast MA ... - maFastHandler = iMA( - _Symbol, - _Period, - maFastLength, - 0, - maMethod, - maAppliedTo // - ); - result = maFastHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // Slow MA ... - maSlowHandler = iMA( - _Symbol, - _Period, - maSlowLength, - 0, - maMethod, - maAppliedTo // - ); - result = maSlowHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // MA Bond Upper ... - maUpperHandler = iMA( - _Symbol, - _Period, - maBandLength, - 0, - maMethod, - PRICE_HIGH // - ); - result = maUpperHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // MA Bond Lower ... - maLowerHandler = iMA( - _Symbol, - _Period, - maBandLength, - 0, - maMethod, - PRICE_LOW // - ); - result = maLowerHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - result = sarHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - mDrawer = new XCPOIDrawer(); - - // - return result; -} - -/** - * Calculate Custom Buffers ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Calculate Bars Limit and First Bar Index ... - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - if (barsLimit == 0) - { - // - barsLimit = ratesTotal; - firstBarIndex = barsLimit - 1; - } - else - { - firstBarIndex = startCalculationForLastBars; - } - - // - // bool canCalculate = true; - bool canCalculate = - barIndex <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(barIndex); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - // TODO: Fill Buffers as Empty ... -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Common Requirements ... - - // - // CYCLES Ranges ... - CalculateCycleRanges( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // PV ... - CalculatePV( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // XHK ... - CalculateHKBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Fast MA ... - double iFastMa = maFastBuffer[barIndex]; - double maFastState = close[barIndex] > iFastMa - ? bullishState - : close[barIndex] < iFastMa - ? bearishState - : neuturalState; - double maFastColor = close[barIndex] > iFastMa - ? bullishColorIDX - : close[barIndex] < iFastMa - ? bearishColorIDX - : neuturalColorIDX; - maFastStateBuffer[barIndex] = maFastState; - maFastColorBuffer[barIndex] = showMAFast - ? maFastColor - : hideColorIDX; - - // - // Slow MA ... - double iSlowMa = maSlowBuffer[barIndex]; - double maSlowState = close[barIndex] > iSlowMa - ? bullishState - : close[barIndex] < iSlowMa - ? bearishState - : neuturalState; - double maSlowColor = close[barIndex] > iSlowMa - ? bullishColorIDX - : close[barIndex] < iSlowMa - ? bearishColorIDX - : neuturalColorIDX; - maSlowStateBuffer[barIndex] = maSlowState; - maSlowColorBuffer[barIndex] = showMASlow - ? maSlowColor - : hideColorIDX; - - // - // SAR ... - double iSar = sarBuffer[barIndex]; - double sarState = low[barIndex] > iSar - ? bullishState - : high[barIndex] < iSar - ? bearishState - : neuturalState; - double sarColor = low[barIndex] > iSar - ? bullishColorIDX - : high[barIndex] < iSar - ? bearishColorIDX - : neuturalColorIDX; - sarStateBuffer[barIndex] = sarState; - sarColorBuffer[barIndex] = showSAR - ? sarColor - : hideColorIDX; - - // - // FIBO Zone ... - - // - double iPeak = peakBuffer[barIndex]; - double iVale = valeBuffer[barIndex]; - - // - double iFiboUp = GetFibonacciLevel( - iPeak, - iVale, - fiboUpperZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - double iFiboMid = GetFibonacciLevel( - iPeak, - iVale, - fiboMiddleZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - double iFiboLo = GetFibonacciLevel( - iPeak, - iVale, - fiboLowerZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - fiboUpperBuffer[barIndex] = iFiboUp; - fiboMiddleBuffer[barIndex] = iFiboMid; - fiboLowerBuffer[barIndex] = iFiboLo; -} - -// -void CalculatePV( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iSHH = sHHBuffer[barIndex]; - double iSLL = sLLBuffer[barIndex]; - - // - double iMHH = mHHBuffer[barIndex]; - double iMLL = mLLBuffer[barIndex]; - - // - double iLHH = lHHBuffer[barIndex]; - double iLLL = lLLBuffer[barIndex]; - - // - double iHHH = hHHBuffer[barIndex]; - double iHLL = hLLBuffer[barIndex]; - - // - // Calculate VALE ... - bool isVale = iSLL == iMLL && - iMLL == iLLL && - iLLL == iHLL; - double iPVale = - isFirstBar - ? emptyValue - : valeBuffer[lastBarIndex]; - double iVale = - isVale - ? iSLL - : iPVale; - valeBuffer[barIndex] = iVale; - - // - // Calculate PEAK ... - bool isPeak = iSHH == iMHH && - iMHH == iLHH && - iLHH == iHHH; - double iPPeak = - isFirstBar - ? emptyValue - : peakBuffer[lastBarIndex]; - double iPeak = - isPeak - ? iSHH - : iPPeak; - peakBuffer[barIndex] = iPeak; -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - * - * @return ( int ) - */ -int CalculateZigZag( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int result = 0; - - // - // Define Variables ... - int i = 0; - - // - int start = 0; - int extreme_counter = 0; - int extreme_search = X_ZG_SEARCH_EXTREMUM; - int shift = 0; - int back = 0; - int last_high_pos = 0; - int last_low_pos = 0; - - // - double val = 0; - double res = 0; - double curlow = 0; - double curhigh = 0; - double last_high = 0; - double last_low = 0; - - // - // Initializing ... - if (prevCalculated == 0) - { - // - ArrayInitialize(lowsBuffer, 0); - ArrayInitialize(highsBuffer, 0); - ArrayInitialize(zigzagBuffer, 0); - ArrayInitialize(lowsTimeBuffer, 0); - ArrayInitialize(highsTimeBuffer, 0); - - // - start = zigzagDepth; - } - - // - // Preparing ZigZag Calculation High and Lows ... - - // - if (zigzagLowersCount != zigzagUppersCount || zigzagLowersCount != ratesTotal) - { - // - // Filling Upper ... - zigzagUppersCount = FillPrice( - zigzagUppersMode, - zigzagUppers, - open, - high, - close, - low // - ); - - // - // Filling Lower ... - zigzagLowersCount = FillPrice( - zigzagLowersMode, - zigzagLowers, - open, - high, - close, - low // - ); - } - - // - // Already Calculated Before ... - if (prevCalculated > 0) - { - // - i = ratesTotal - 1; - - // - // Searching for the third X_ZG_SEARCH_EXTREMUM from the last UnComplete Bar ... - while (extreme_counter < zigzagRecalc && i > ratesTotal - 100) - { - // - res = zigzagBuffer[i]; - if (res != 0) - { - extreme_counter++; - } - - // - i--; - } - - // - i++; - start = i; - - // - // What type of X_ZG_SEARCH_EXTREMUM we Search for ... - if (lowsBuffer[i] != 0) - { - // - curlow = lowsBuffer[i]; - extreme_search = X_ZG_SEARCH_PEAK; - } - else - { - // - curhigh = highsBuffer[i]; - extreme_search = X_ZG_SEARCH_VALE; - } - - // - // Clear Values ... - for (i = start + 1; i < ratesTotal && !IsStopped(); i++) - { - // - lowsBuffer[i] = 0; - highsBuffer[i] = 0; - zigzagBuffer[i] = 0; - lowsTimeBuffer[i] = 0; - highsTimeBuffer[i] = 0; - } - } - - // - // Search for High and Low Extremes ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - // Low ... - val = zigzagLowers[Lowest(zigzagLowers, zigzagDepth, shift)]; - if (val == last_low) - { - val = 0; - } - else - { - // - last_low = val; - - // - if ((zigzagLowers[shift] - val) > zigzagDeviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= zigzagBackStep; back++) - { - // - res = lowsBuffer[shift - back]; - if ((res != 0) && (res > val)) - { - // - lowsBuffer[shift - back] = 0; - lowsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagLowers[shift] == val) - { - // - lowsBuffer[shift] = val; - lowsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - // - lowsBuffer[shift] = 0; - lowsTimeBuffer[shift] = 0; - } - - // - // High ... - val = zigzagUppers[Highest(zigzagUppers, zigzagDepth, shift)]; - if (val == last_high) - { - val = 0; - } - else - { - // - last_high = val; - - // - if ((val - zigzagUppers[shift]) > zigzagDeviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= zigzagBackStep; back++) - { - // - res = highsBuffer[shift - back]; - if ((res != 0) && (res < val)) - { - // - highsBuffer[shift - back] = 0; - highsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagUppers[shift] == val) - { - // - highsBuffer[shift] = val; - highsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - highsBuffer[shift] = 0; - highsTimeBuffer[shift] = 0; - } - } - - // - // Set Last Value ... - if (extreme_search == 0) // Undefined Values ... - { - // - last_low = 0; - last_high = 0; - } - else - { - // - last_low = curlow; - last_high = curhigh; - } - - // - // Final Selection of Extreme Points for ZigZag ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - res = 0; - - // - switch (extreme_search) - { - // - case X_ZG_SEARCH_EXTREMUM: - // - if (last_low == 0 && last_high == 0) - { - // - if (highsBuffer[shift] != 0) - { - // - last_high_pos = shift; - last_high = zigzagUppers[shift]; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - zigzagBuffer[shift] = last_high; - - // - res = 1; - } - - // - if (lowsBuffer[shift] != 0) - { - // - last_low_pos = shift; - last_low = zigzagLowers[shift]; - - // - extreme_search = X_ZG_SEARCH_PEAK; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - } - break; - - // - case X_ZG_SEARCH_PEAK: - // - if (lowsBuffer[shift] != 0 && lowsBuffer[shift] < last_low && highsBuffer[shift] == 0) - { - // - zigzagBuffer[last_low_pos] = 0; - - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - - // - if (highsBuffer[shift] != 0 && lowsBuffer[shift] == 0) - { - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - res = 1; - } - break; - - // - case X_ZG_SEARCH_VALE: - // - if (highsBuffer[shift] != 0 && highsBuffer[shift] > last_high && lowsBuffer[shift] == 0) - { - // - zigzagBuffer[last_high_pos] = 0; - - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - } - - // - if (lowsBuffer[shift] != 0 && highsBuffer[shift] == 0) - { - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - extreme_search = X_ZG_SEARCH_PEAK; - } - break; - } - } - - // - result = ratesTotal; - - // - return result; -} - -// -void CalculateHKBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double lastHKOpen = - isFirstBar - ? emptyValue - : hkOpenBuffer[lastBarIndex]; - double lastHKClose = - isFirstBar - ? emptyValue - : hkCloseBuffer[lastBarIndex]; - - // - double iHKOpenValue = (lastHKOpen + lastHKClose) / 2; - double iHKCloseValue = (open[barIndex] + high[barIndex] + close[barIndex] + low[barIndex]) / 4; - double iHKHighValue = MathMax(high[barIndex], MathMax(iHKOpenValue, iHKCloseValue)); - double iHKLowValue = MathMin(low[barIndex], MathMin(iHKOpenValue, iHKCloseValue)); - - // - bool isBullish = iHKOpenValue < iHKCloseValue; - bool isBearish = iHKOpenValue > iHKCloseValue; - - // - if (hkIgnoreShadows) - { - // - iHKHighValue = isBullish - ? iHKCloseValue - : iHKOpenValue; - - // - iHKLowValue = isBullish - ? iHKOpenValue - : iHKCloseValue; - } - - // - // XHK Buffers ... - hkOpenBuffer[barIndex] = iHKOpenValue; - hkHighBuffer[barIndex] = iHKHighValue; - hkLowBuffer[barIndex] = iHKLowValue; - hkCloseBuffer[barIndex] = iHKCloseValue; - - // - // XHK Raw Bufferss ... - hkRawOpenBuffer[barIndex] = iHKOpenValue; - hkRawHighBuffer[barIndex] = iHKHighValue; - hkRawLowBuffer[barIndex] = iHKLowValue; - hkRawCloseBuffer[barIndex] = iHKCloseValue; - - // - // Smoothing ... - if (IsXValid(hkSmoothingMode) && hkSmoothingLength > 0) - { - // - // XHK Signal ... - - // - // High ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawHighBuffer, - hkHighBuffer, - hkSmoothingMode // - ); - - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawOpenBuffer, - hkOpenBuffer, - hkSmoothingMode // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawLowBuffer, - hkLowBuffer, - hkSmoothingMode // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawCloseBuffer, - hkCloseBuffer, - hkSmoothingMode // - ); - } - - // - hkBondUpperBuffer[barIndex] = hkHighBuffer[barIndex]; - hkBondLowerBuffer[barIndex] = hkLowBuffer[barIndex]; - - // - // Calculate HK Color ... - double iHKColorValue = - isBullish - ? bullishColorIDX - : isBearish - ? bearishColorIDX - : neuturalColorIDX; - hkColorBuffer[barIndex] = - showHK - ? iHKColorValue - : hideColorIDX; -} - -// -void CalculateCycleRanges( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // SHORT ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_SHORT, - sHHBuffer, - sLLBuffer // - ); - - // - // MEDIUM ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_MEDIUM, - mHHBuffer, - mLLBuffer // - ); - - // - // LONG ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_LONG, - lHHBuffer, - lLLBuffer // - ); - - // - // HIND ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_HIND, - hHHBuffer, - hLLBuffer // - ); -} - -/** - * Calculate Specified Market Cycle Info ... - * - * @param barIndex: Integer, Bar Index ... - * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... - * @param hhBuffer: Highest High Buffer Reference ... - * @param llBuffer: Lowest Low Buffer Reference ... - */ -void CalculateCycle( - int barIndex, - ENUM_X_MARKET_CYCLES cycle, - double &hhBuffer[], - double &llBuffer[] // -) -{ - // - XOHCL bar; - bool isBarInited = bar.Init( - _Symbol, - _Period, - barIndex - // - ); - if (!isBarInited) - { - return; - } - - // - int mLength = 0; - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - mLength = mSCLength; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - mLength = mMCLength; - break; - - // - case X_MARKET_CYCLE_LONG: - mLength = mLCLength; - break; - - // - case X_MARKET_CYCLE_HIND: - mLength = mHCLength; - break; - } - - // - if (mLength == 0) - { - return; - } - - // - // Find Highest High ... - double hhValue = bar.FindHighest( - mLength, - upperMode // - ); - hhBuffer[barIndex] = hhValue; - - // - // Find Lowest Low ... - double llValue = bar.FindLowest( - mLength, - lowerMode // - ); - llBuffer[barIndex] = llValue; - - // - bar.Clean(); -} - -// -// -// - -// -// Get Specified Bar Time as Double ... -double GetZigZagBarTime(int barIndex) -{ - // - if (barIndex <= 0) - { - barIndex = 0; - } - - // - datetime time = iTime(_Symbol, _Period, barIndex); - - // - double result = (double)((int)time); - - // - return result; -} - -// -// Filling Required Prices Based on MODE ... -int FillPrice( - ENUM_X_PRICE mode, - double &dest[], - const double &open[], - const double &high[], - const double &close[], - const double &low[] // -) -{ - // - int result = 0; - - // - SpecifiedClean(dest); - - // - if (!IsXValid(mode)) - { - return result; - } - - // - switch (mode) - { - // - case X_PRICE_HIGH: - // - result = ArrayCopy( - dest, - high // - ); - break; - - // - case X_PRICE_LOW: - // - result = ArrayCopy( - dest, - low // - ); - break; - - // - case X_PRICE_OPEN: - // - result = ArrayCopy( - dest, - open // - ); - break; - - // - case X_PRICE_CLOSE: - // - result = ArrayCopy( - dest, - close // - ); - break; - - // - default: - // - result = ArrayCopy( - dest, - close // - ); - break; - } - - // - return result; -} - -// -// Search for the index of the highest bar ... -int Highest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double max = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] > max) - { - // - result = i; - max = mArray[i]; - } - } - - // - // Return index of the highest bar - return result; -} - -// -// Search for the index of the lowest bar ... -int Lowest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double min = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] < min) - { - // - result = i; - min = mArray[i]; - } - } - - // - // Return index of the lowest bar - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/tmp-trade_symbol.info.mq5 b/Documents/BKP/tmp-trade_symbol.info.mq5 deleted file mode 100644 index ebc5440b..00000000 --- a/Documents/BKP/tmp-trade_symbol.info.mq5 +++ /dev/null @@ -1,977 +0,0 @@ -` - // - // an Structure for Holds an Specified Symbols - // Positions Info ... - struct XTradeSymbolInfo -{ - // - // Properties ... - - // - string symbol; // Trading Symbol - - // - int longs; // All Long Trades - int shorts; // All Short Trades - - // - int trades; // All Trades - - // - int losses; // All Loosing Trades - int profits; // All Winning Trades - - // - datetime managedStart; // Managed Start Time - - // - int managedSLs; // Managed SL(s) - int managedTPs; // Managed TP(s) - int managedTrades; // Managed Trades - - // - double managedBalance; // Managed Start Balance - double managedProfits; // Managed Profit(s) - - // - // Constructor ... - XTradeSymbolInfo() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - - // - longs = 0; - shorts = 0; - - // - trades = 0; - - // - losses = 0; - profits = 0; - - // - managedStart = NULL; - - // - managedSLs = 0; - managedTPs = 0; - managedTrades = 0; - - // - managedBalance = 0; - managedProfits = 0; - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsSpecifiedValid(symbol); - - // - return result; - } - - // - bool IsSameAs(XTradeSymbolInfo &item) - { - // - bool result = false; - - // - result = IsValid() && - item.IsValid() && - symbol == item.symbol; - - // - return result; - } - - // - string GetRestrictionDescription( - ENUM_XTRADE_RESTRICTION_PERIOD period // - ) - { - // - string result = NULL; - - // - if (!IsValid() || - !HasRestrictions(period)) - { - return result; - } - - // - result += - "-------------------" + "\n" + - "Restrictions: " + "\n" + - "-------------------" + "\n" + - "Symbol: " + ToXString(symbol) + "\n" + - "Period: " + ToXString(period) + "\n" + - "Start: " + ToFormatString(managedStart) + "\n" + - "Balance: " + ToXString(managedBalance) + "\n" + - "-------------------" + "\n" + - "Trades: " + ToXString(managedTrades) + "\n" + - "SL: " + ToXString(managedSLs) + "\n" + - "TP: " + ToXString(managedTPs) + "\n" + - "Profit: " + ToXString(managedProfits) + "\n" + - ""; - - // - return result; - } -}; - -// -void SetForceCloseTradesAt( - string _forceCloseAt // -) -{ - forceCloseAt = _forceCloseAt; -} - -// -void SetTradeSession( - string symbol, - string start, - string end, - string name = NULL // -) -{ - // - // Validate Args ... - bool has = IsValid(end) && - IsValid(start) && - IsValid(symbol); - if (!has) - { - return; - } - - // - // Create Session ... - - // - XTradeSession session; - - // - session.end = end; - session.name = name; - session.start = start; - - // - int sessionIDX = -1; - has = FindSymbolSession( - sessionIDX, - symbol // - ); - - // - if (!has) - { - // - // Add New Symbol Session ... - - // - XSymbolSessions iSymbolSession; - iSymbolSession.symbol = symbol; - - // - AddTradingSession( - session, - iSymbolSession // - ); - - // - AddRef( - iSymbolSession, - sessions // - ); - - // - iSymbolSession.Clean(); - } - else - { - // - // Update Trading Sessions of Exists Symbol Session ... - AddTradingSession( - session, - sessions[sessionIDX] // - ); - } - - // - // Cleanup Resources ... - session.Clean(); -} - -// -void SetTradeRestrictions( - ENUM_XTRADE_RESTRICTION_PERIOD _period, - int _maxAllowedTPs, - int _maxAllowedSLs, - int _maxAllowedTrades // -) -{ - // - // Normalizing Args ... - _maxAllowedTPs = NormalizeInt(_maxAllowedTPs, 0); - _maxAllowedSLs = NormalizeInt(_maxAllowedSLs, 0); - _maxAllowedTrades = NormalizeInt(_maxAllowedTrades, 0); - - // - restrictionsPeriod = _period; - maxAllowedTPs = _maxAllowedTPs; - maxAllowedSLs = _maxAllowedSLs; - maxAllowedTrades = _maxAllowedTrades; -} -// -// Symbol Info ... - -// -bool FindSymbolIndex( - int &index, - XTradeSymbolInfo &item // -) -{ - // - bool result = false; - - // - index = -1; - - // - result = item.IsValid(); - if (!result) - { - return result; - } - - // - result = HasChild(symbols); - if (!result) - { - return result; - } - - // - index = FindIndex( - item, - symbols // - ); - - // - result = IsValidIndex(index); - - // - return result; -} - -// -bool FindSymbolIndex( - int &index, - string symbol // -) -{ - // - bool result = false; - - // - index = -1; - - // - result = IsValid(symbol) && - HasChild(symbols); - if (!result) - { - return result; - } - - // - int count = ArraySize(symbols); - for (int i = 0; i < count; i++) - { - // - result = symbols[i].symbol == symbol; - if (result) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; -} - -// -void AddOrUpdateSymbolInfo(XTradeSymbolInfo &item) -{ - // - bool has = item.IsValid(); - if (!has) - { - return; - } - - // - int index = -1; - bool isExists = FindSymbolIndex( - index, - item // - ); - if (!isExists) - { - // - AddRef( - item, - symbols // - ); - } - else - { - // - symbols[index].longs += item.longs; - symbols[index].shorts += item.shorts; - symbols[index].trades += item.trades; - symbols[index].losses += item.losses; - symbols[index].profits += item.profits; - symbols[index].managedSLs += item.managedSLs; - symbols[index].managedTPs += item.managedTPs; - symbols[index].managedTrades += item.managedTrades; - symbols[index].managedProfits += item.managedProfits; - - // - // Handle Remove on Managed SL based On Managed TP ... - if (item.managedTPs > 0) - { - // - symbols[index].managedSLs -= item.managedTPs; - if (symbols[index].managedSLs < 0) - { - symbols[index].managedSLs = 0; - } - } - - // - // Handle Remove on Managed TP based On Managed SL ... - if (item.managedSLs > 0) - { - // - symbols[index].managedTPs -= item.managedSLs; - if (symbols[index].managedTPs < 0) - { - symbols[index].managedTPs = 0; - } - } - } -} - -// -void ResetSymbolsRestrictions() -{ - // - bool has = HasChild(symbols); - if (has) - { - // - string prefix = "Protector: "; - - // - datetime start = TimeCurrent(); - double balance = trader.mAccount.GetBalance(); - bool hasRestrictions = HasRestrictions(restrictionsPeriod); - if (!hasRestrictions) - { - // - balance = 0; - start = NULL; - } - - // - int count = ArraySize(symbols); - for (int i = 0; i < count; i++) - { - // - XTradeSymbolInfo iInfo = symbols[i]; - if (reportRestrictions) - { - // - string message = iInfo.GetRestrictionDescription(restrictionsPeriod); - alert.SendAlert(message); - } - SaveRestrictions(iInfo); - - // - symbols[i].managedSLs = 0; - symbols[i].managedTPs = 0; - symbols[i].managedTrades = 0; - symbols[i].managedProfits = 0; - symbols[i].managedStart = start; - symbols[i].managedBalance = balance; - - // - iInfo.Clean(); - } - - // - string message = prefix + "Reset Symbols Restrictions"; - HandleReportProtector(message); - } -} - -// -void HandleRestrictions() -{ - // - bool isNewDay = timeTracker.IsNewDay(); - bool isNewHour = timeTracker.IsNewHour(); - bool isNewWeek = timeTracker.IsNewWeek(); - bool isNewMonth = timeTracker.IsNewMonth(); - - // - // Reset Force Closed Flag on new Day Starts ... - if (isNewDay) - { - isForceCloseAtTime = false; - } - - // - bool canResetRestrictions = - ( - // - // Hourly ... - (isNewHour && - restrictionsPeriod == XTRADE_RESTRICATION_HOURLY) - // - || - // - // Daily ... - (isNewDay && - restrictionsPeriod == XTRADE_RESTRICATION_DAILY) - // - || - // - // Weekly ... - (isNewWeek && - restrictionsPeriod == XTRADE_RESTRICATION_WEEKLY) - // - || - // - // Monthly ... - (isNewMonth && - restrictionsPeriod == XTRADE_RESTRICATION_MONTHLY) - // - ) - // - ; - if (canResetRestrictions) - { - ResetSymbolsRestrictions(); - } -} - -// -bool SaveRestrictions(XTradeSymbolInfo &info) -{ - // - bool result = false; - - // - if (!mSaveRestrictions) - { - return result; - } - - // - result = info.IsValid(); - if (!result) - { - return result; - } - - // - string filePath = GetRestrictionsFilePath(info.symbol); - result = IsValid(filePath); - if (!result) - { - return result; - } - - // - string content = info.GetRestrictionDescription(restrictionsPeriod); - - // - result = collector.Append( - filePath, - content // - ); - - // - return result; -} - -// -// Symbol Session ... - -// -bool FindSymbolSession( - int &index, - string symbol // -) -{ - // - bool result = false; - - // - index = -1; - - // - result = IsValid(symbol) && - HasChild(sessions); - if (!result) - { - return result; - } - - // - int count = ArraySize(sessions); - for (int i = 0; i < count; i++) - { - // - result = sessions[i].symbol == symbol; - if (result) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; -} - -// -void AddTradingSession( - XTradeSession &session, - XSymbolSessions &symbolSession // -) -{ - // - bool has = session.IsValid() && - symbolSession.IsValid(); - if (!has) - { - return; - } - - // - // Check Session Exists in Symbol Session ... - bool isExists = false; - if (HasChild(symbolSession.sessions)) - { - // - int count = ArraySize(symbolSession.sessions); - for (int i = 0; i < count; i++) - { - // - isExists = symbolSession.sessions[i].end == session.end && - symbolSession.sessions[i].start == session.start; - if (isExists) - { - break; - } - } - } - - // - if (!isExists) - { - // - AddRef( - session, - symbolSession.sessions // - ); - } -} - -/** - * Check Signal Execution Conditions ... - * - * @param signal: XSignal instance reference ... - * @param executionResult: ENUM_X_SIGNAL_EXECUTION_RESULT member reference ... - * - * @return ( bool ) - */ -bool CheckSignal( - XSignal &signal, - ENUM_X_SIGNAL_EXECUTION_RESULT &executionResult // -) -{ - // - bool result = false; - - // - // Cleanup ... - executionResult = X_SIGNAL_EXECUTION_UNKNOWN; - - // - // Validate Signal ... - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - // Reporting Signal ... - if (reportSignals) - { - // - string message = signal.GetMessage("Provided"); - alert.SendAlert(message); - } - - // - SaveSignal(signal); - - // - // Check Trade Permission ... - if (!allowTrade) - { - // - result = false; - executionResult = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; - - // - return result; - } - - // - bool isLong = IsLong(signal.type); - bool isShort = IsShort(signal.type); - - // - bool isLongAndAllowed = - isLong && - allowLongs; - - // - bool isShortAndAllowed = - isShort && - allowShorts; - - // - result = isLongAndAllowed || - isShortAndAllowed; - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; - - // - return result; - } - - // - // Check Symbol Info Exists or not ... - int symbolInfoIDX = -1; - bool isSymbolInfoExists = FindSymbolIndex( - symbolInfoIDX, - signal.symbol // - ); - - // - // Check Symbol Session Exists or not ... - int symbolSessionIDX = -1; - bool isSymbolSessionExists = FindSymbolSession( - symbolSessionIDX, - signal.symbol // - ); - - // - // Chack Trade Session Validating ... - if (isSymbolSessionExists) - { - // - result = sessions[symbolSessionIDX].CanTrade(); - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED; - - // - return result; - } - } - - // - // Check Trade Permissions Based on SL(s) Count ... - bool hasRestrictions = restrictionsPeriod != XTRADE_RESTRICATION_NONE; - if (hasRestrictions) - { - // - // Only Can Check Restrictions when - // Symbol Info Exists ... - if (isSymbolInfoExists) - { - // - bool isTPAllowed = maxAllowedTPs == 0 - ? true - : symbols[symbolInfoIDX].managedTPs < maxAllowedTPs; - bool isSLAllowed = maxAllowedSLs == 0 - ? true - : symbols[symbolInfoIDX].managedSLs < maxAllowedSLs; - bool isTradeAllowed = maxAllowedTrades == 0 - ? true - : symbols[symbolInfoIDX].managedTrades < maxAllowedTrades; - - // - result = isTPAllowed && - isSLAllowed && - isTradeAllowed; - } - - // - // Report Error ... - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_MAX_REACHED; - - // - return result; - } - } - - // - return result; -} - -/** - * Execute Specified Signal ... - * - * @param signal: XSignal instance reference ... - * @param conditions: XCATBEAStrategyConditions instance reference ... - * - * @return ( bool ) - */ -bool Execute(XSignal &signal) -{ - // - bool result = false; - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - int idx = -1; - bool isExists = HasTrade( - idx, - signal // - ); - result = !isExists; - if (!result) - { - return result; - } - - // - ENUM_X_SIGNAL_EXECUTION_RESULT executionResult; - - // - // Checking Signal For Execution ... - result = CheckSignal( - signal, - executionResult // - ); - if (result) - { - // - result = trader.ExecuteSignal( - signal, - executionResult // - ); - } - - // - // Alert Signal Execution ... - if (reportTrades) - { - // - string executionMessage = ToString(executionResult); - - // - string message = NULL; - if (result) - { - message = signal.GetMessage("Executed"); - } - else - { - message = signal.GetMessage("Failed due (" + executionMessage + ")"); - } - - // - alert.SendAlert(message); - } - - // - if (result) - { - // - // Create Symbol Info Struct ... - XTradeSymbolInfo iSymbolInfo; - - // - iSymbolInfo.trades = 1; - iSymbolInfo.managedTrades = 1; - iSymbolInfo.symbol = signal.symbol; - - // - bool isLong = IsLong(signal.type); - if (isLong) - { - iSymbolInfo.longs = 1; - } - else - { - iSymbolInfo.shorts = 1; - } - - // - // Fill Balance for Restrications ... - bool hasRestrictions = HasRestrictions(restrictionsPeriod); - if (hasRestrictions) - { - // - // Read Balance ... - double balance = trader.mAccount.GetBalance(); - iSymbolInfo.managedBalance = balance; - iSymbolInfo.managedStart = TimeCurrent(); - } - - // - AddOrUpdateSymbolInfo(iSymbolInfo); - - // - // Create Trade Struct ... - XTradeInfo iTrade; - - // - ulong positionID = trader.GetLastOpenPositionTicket(); - double commission = trader.GetPositionCommission(positionID); - - // - iTrade.signal = signal; - iTrade.positionID = positionID; - iTrade.commission = commission; - iTrade.signaledAt = signal.time; - iTrade.executedAt = TimeCurrent(); - iTrade.conditions = signal.conditions; - - // - AddRef( - iTrade, - trades // - ); - } - - // - return result; -} - - /** - * Check Specified Symbol is Active for - * Analysing or Open Trades ... - */ - bool IsActiveSession(string symbol) - { - // - bool result = false; - - // - // Validate Args ... - result = IsValid(symbol); - if (!result) - { - return result; - } - - // - // TODO: Complete this ... - - // // - // // Check Symbol Session Exists or not ... - // int symbolSessionIDX = -1; - // bool isSymbolSessionExists = FindSymbolSession( - // symbolSessionIDX, - // symbol // - // ); - - // // - // // Chack Trade Session Validating ... - // if (isSymbolSessionExists) - // { - // result = sessions[symbolSessionIDX].CanTrade(); - // } - - // - return result; - } - -// -string forceCloseAt; -bool isForceCloseAtTime; - -// -int maxAllowedTPs; -int maxAllowedSLs; -int maxAllowedTrades; -ENUM_XTRADE_RESTRICTION_PERIOD restrictionsPeriod; - -XTradeSymbolInfo symbols[]; -XSymbolSessions sessions[]; - -// -forceCloseAt = NULL; -isForceCloseAtTime = false; - -// -maxAllowedTPs = 0; -maxAllowedSLs = 0; -maxAllowedTrades = 0; -restrictionsPeriod = XTRADE_RESTRICATION_NONE; diff --git a/Documents/BKP/tmp.backtester.codes.mq5 b/Documents/BKP/tmp.backtester.codes.mq5 deleted file mode 100644 index 55c7c9a6..00000000 --- a/Documents/BKP/tmp.backtester.codes.mq5 +++ /dev/null @@ -1,1389 +0,0 @@ - -void UpdateMainPanel() -{ - // - // Validate ... - if (mChartHelper == NULL || - mainPanel == NULL) - { - return; - } - - // - bool has = false; - - // - // Update Main Panel Position ... - XObjPosition mainPanelPosition; - CalculateMainPanelPosition(mainPanelPosition); - if (mainPanelPosition.IsValidForRectangle()) - { - // - has = mainPanel.ShiftPoint(1, mainPanelPosition.fromTime, mainPanelPosition.fromPrice); - if (has) - { - has = mainPanel.ShiftPoint(2, mainPanelPosition.toTime, mainPanelPosition.toPrice); - } - } -} - -/** - * Calculate Main Window Position ... - * - * @param position: XObjPosition - */ -void CalculateMainPanelPosition(XObjPosition &position) -{ - // - position.Clean(); - - // - // Reading Chart Helper Requirements ... - - // - string mChartSymbol = mChartHelper.Symbol(); - double mPoint = GetPoints(mChartSymbol); - - // - ENUM_TIMEFRAMES mChartPeriod = mChartHelper.Period(); - int mChartPeriodSeconds = PeriodSeconds(mChartPeriod); - - // - double mChartMinPrice = mChartHelper.PriceMin(); - double mChartMaxPrice = mChartHelper.PriceMax(); - int mChartVisibleBarsCount = mChartHelper.VisibleBars(); - int mChartFirstBarIndex = mChartHelper.FirstVisibleBar(); - - // - datetime mChartFirstBarTime = GetBarTime( - mChartSymbol, - mChartPeriod, - mChartFirstBarIndex // - ); - - // - position.fromTime = mChartFirstBarTime + (mChartPeriodSeconds); - position.fromPrice = mChartMaxPrice - (10 * mPoint); - - // - position.toTime = position.fromTime + (40 * mChartPeriodSeconds); - position.toPrice = position.fromPrice - (20 * mPoint); - - // - Print(" "); - - // - Print("From Time: ", position.fromTime); - Print("To Time: ", position.toTime); - - // - Print(" "); - - // - Print("From Price: ", position.fromPrice); - Print("To Price: ", position.toPrice); -} - -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XTest MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XBackTester -// Description: a Backtest Tools Strategy Tester -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -//////////////////////////////////////////////////////x -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XBackTester" -#property strict - -// -#define ShortName "XBackTester" - -// -// Imports ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-chart.helper.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" - -// -// Import Chart Objects ... -#include -#include -#include -#include -#include -#include -#include - -// -// Definitions ... -struct XObjPosition -{ - // - // Props ... - datetime fromTime; - double fromPrice; - datetime toTime; - double toPrice; - - // - // Constructor ... - XObjPosition() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - toPrice = 0; - fromPrice = 0; - - // - toTime = NULL; - fromTime = NULL; - } - - // - // Validate XWindowPosition for Rectangle ... - bool IsValidForRectangle() - { - // - bool result = - // - toPrice > 0 && - fromPrice > 0 && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime) && - fromTime < toTime - // - ; - - // - return result; - } -}; - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Alert ... -// Here we Provider All Requirements for -// Configuring Alert Provider ... -input group "Alert"; -input bool eAEnableAlerts = true; // Enable Alerts -input bool eALogAlerts = true; // Log Alerts -input bool eAMailAlerts = false; // Mail Alerts -input bool eAPushAlerts = false; // Push Alerts -input bool eATerminalAlerts = false; // Terminal Alerts -// -// Define Local Variables ... - -// -string eaLogTag; // EA Log Prefix ... -XCAlert *eaAlert; // Alert Provider for Expert Adviser ... -XCTrade *eaTrader; // Trader of Expert Adviser ... - -// -// Chart Objects and Properties ... -XCChartHelper *mChartHelper; - -// -// Chart Object Class ... - -// -string objSuffix; - -// -// Main Panel ... -string mainPanelName; -CChartObjectRectLabel *mainPanel; // Main Panel ... -string buyButtonName; -CChartObjectButton *buyButton; // Buy Button ... -string sellButtonName; -CChartObjectButton *sellButton; // Sell Button ... - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Timer ... - if (!InitTimer()) - { - return INIT_FAILED; - } - - // - // Initialize all Requirements ... - if (!InitEA()) - { - return INIT_FAILED; - } - - // - // Initialize all GUI Objects and Classes ... - if (!InitGUI()) - { - return INIT_FAILED; - } - - // - // Alert Initialization ... - string msg = "Initialized Successfully ..."; - eaAlert.SendAlert(msg); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Destroy Timer ... - DestroyTimer(); - - // - // Destroy all GUI Requirements ... - DestroyGUI(); - - // - // Alert De Initialization Succeeded ... - string msg = "De Initialized Successfully ..."; - eaAlert.SendAlert(msg); - - // - // Destroy all EA Requirements ... - DestroyEA(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - UpdateGUI(); -} - -// -// Handle On Trade Event ... -void OnTrade() -{ - eaTrader.HandleOnTrade(); -} - -// -// On Timer ... -void OnTimer() -{ - // - // TODO: Implement Time Based Functionalities ... -} - -// -// Chart Event Handler ... -void OnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // -) -{ - // - // Apply Chart Event on Main Window ... - if (id == CHARTEVENT_OBJECT_CLICK) - { - // - if (mainPanel != NULL && sparam == mainPanelName) - { - // - Print("Main Panel Clicked ..."); - } - } -} - -// -// Custom Functions ... - -/** - * Validate all Inputs of Expert Adviser ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - eaSlippage > 0 && - eaMagicNumber > 0 - // - ); - if (!isCommonValid) - { - // - errMessage += "common configurations error;" + "\n"; - } - - // - result = - // - // Common ... - isCommonValid && - // - // Otere ... - true - // - ; - - // - if (!result) - { - // - // Since here Logger not Initiallized, we Use Raw Print Command ... - Print(ShortName + " Errors: \n", errMessage); - } - - // - return result; -} - -/** - * Initialize Timer ... - * - * @return ( bool ) - */ -bool InitTimer() -{ - // - bool result = false; - - // - // TODO: Initialize Timer if necessary ... - // result = EventSetTimer(1); - // result = EventSetMillisecondTimer(100); - result = true; - - // - return result; -} - -/** - * Destroy Timer ... - */ -void DestroyTimer() -{ - // - // TODO: Use This ... - // EventKillTimer(); -} - -/** - * Initialize all Requirements for Working Fine ... - * - * @return ( bool ) - */ -bool InitEA() -{ - // - bool result = false; - - // - // Locally Apply Changes on Prefix ... - eaLogTag = ShortName + ">" + eaLogSuffix; - - // - // Create Instance of Alert Class and Configure it ... - eaAlert = new XCAlert(); - eaAlert.SetPrefix(eaLogTag); - eaAlert.SetLogAlerts(eALogAlerts); - eaAlert.SetMailAlerts(eAMailAlerts); - eaAlert.SetPushAlerts(eAPushAlerts); - eaAlert.SetEnableAlerts(eAEnableAlerts); - eaAlert.SetTerminalAlerts(eATerminalAlerts); - - // - // Create Trader Instance and Configure it ... - eaTrader = new XCTrade( - eaSlippage, - eaMagicNumber // - ); - - // - // TODO: Fix This ... - result = true; - - // - return result; -} - -/** - * Destroy all Initialized EA Requirements ... - */ -void DestroyEA() -{ - // - delete eaAlert; -} - -// -// GUI Events ... - -/** - * Initialize all GUI Requirements for EA ... - * - * @return ( bool ) - */ -bool InitGUI() -{ - // - bool result = false; - - // - int subWindow = 0; - ulong chartId = ChartID(); - objSuffix = ShortName + "_"; - - // - // Initial Chart Class Instance ... - mChartHelper = new XCChartHelper(chartId); - - // - // Create Main Panel ... - result = CreateMainPanel(); - - // - - // - return result; -} - -/** - * Update GUI based on Each Ticks ... - */ -void UpdateGUI() -{ - // - // UpdateMainPanel(); -} - -/** - * Destroy all Initialized GUi Requirements ... - */ -void DestroyGUI() -{ - // - delete mChartHelper; - ZeroMemory(mChartHelper); - - // - delete mainPanel; - ZeroMemory(mainPanel); -} - -// -// Custom Helper Functions ... - -bool CreateMainPanel() -{ - // - bool result = false; - - // - if (mChartHelper == NULL) - { - return result; - } - - // - int subWindow = 0; - - // - mainPanelName = objSuffix + "Main_Panel"; - mainPanel = new CChartObjectRectLabel(); - result = mainPanel.Create( - mChartHelper.ChartId(), - mainPanelName, - subWindow, - 10, - 25, - 400, - 200 // - ); - if (!result) - { - return result; - } - - // - // Styling Main Panel ... - mainPanel.BackColor(clrDarkGray); - mainPanel.Tooltip(mainPanelName); - - // - // Create Buttons ... - buyButtonName = objSuffix + "BTN_BUY"; - buyButton = new CChartObjectButton(); - result = buyButton.Create( - mChartHelper.ChartId(), - buyButtonName, - subWindow, - 10, - 25, - 200, - 100 // - ); - if (!result) - { - return result; - } - - // - // Apply Style of Buy Button ... - - if (result) - { - } - - // - return result; -} - -////////////////////////////////////////////////// - -// -// class XCEdit : public CEdit { -// // -// public: -// // -// string mValue; - -// // -// bool OnSetText() { -// // -// Print("Object Edit End ..."); -// return true; -// } -// }; - -// CEdit edtPositionId; - -// // -// // EDIT Position ID ... -// int edtPositionIdStartX = btnSellStartX; -// int edtPositionIdSizeX = edtPositionIdStartX + 100; -// int edtPositionIdStartY = btnSellSizeY + 5; -// int edtPositionIdSizeY = edtPositionIdStartY + 50; -// string edtPositionIdName = objSuffix + "EDT_POS_ID"; -// result = edtPositionId.Create( -// chartId, -// edtPositionIdName, -// subWindow, -// edtPositionIdStartX, -// edtPositionIdStartY, -// edtPositionIdSizeX, -// edtPositionIdSizeY // -// ); -// if (result) -// { -// // -// // Apply Edit Position ID Style ... -// edtPositionId.Text(ToXString(selectedPositionID)); -// edtPositionId.TextAlign(ALIGN_LEFT); -// } - -////////////////////////////////////////////////////////////////// - -// -CButton btnPauseReplay; -bool isVisualTesterPaused = false; - -// -// Initial Btn Pause Play ... -int subWindow = 0; -int defaultGap = 5; -int defaultWidth = 100; -int defaultHeight = 30; -ulong chartId = eaExpert.eaChartHelper.ChartId(); - -// -int btnPauseReplayX1 = defaultGap; -int btnPauseReplayX2 = btnPauseReplayX1 + defaultWidth; -int btnPauseReplayY1 = eaExpert.eaChartHelper.Height() - defaultHeight - defaultGap; -int btnPauseReplayY2 = btnPauseReplayY1 + defaultHeight; - -// -string btnPauseReplayName = ShortName + "BTN_PAUSE_REPLAY"; - -// -isInited = btnPauseReplay.Create( - chartId, - btnPauseReplayName, - subWindow, - btnPauseReplayX1, - btnPauseReplayY1, - btnPauseReplayX2, - btnPauseReplayY2 // -); -if (isInited) -{ - // - // Apply Style ... - string btnPauseReplayText = - isVisualTesterPaused - ? "Play" - : "Pause"; - btnPauseReplay.Text(btnPauseReplayText); - btnPauseReplay.Color(clrAzure); - btnPauseReplay.ColorBackground(clrBlack); -} - -// -// -// Update btn Pause Replay ... -string btnPauseReplayText = - isVisualTesterPaused - ? "Play" - : "Pause"; -btnPauseReplay.Text(btnPauseReplayText); -if (IsRunningeOnTestVisualMode()) -{ - // - btnPauseReplay.Show(); - btnPauseReplay.Enable(); -} -else -{ - // - btnPauseReplay.Hide(); - btnPauseReplay.Enable(); -} -if (btnPauseReplay.Pressed()) -{ - // - if (btnPauseReplay.IsEnabled()) - { - // - HandlePauseStrategyTester(); - - // - btnPauseReplayText = - isVisualTesterPaused - ? "Play" - : "Pause"; - btnPauseReplay.Text(btnPauseReplayText); - } - - // - btnPauseReplay.Pressed(false); -} - -void HandlePauseStrategyTester() -{ - // - isVisualTesterPaused = !isVisualTesterPaused; - - // - // DebugBreak(); - - keybd_event(VK_SPACE, 0, 0, 0); - keybd_event(VK_SPACE, 0, KEYEVENTF_KEYUP, 0); -} - -/////////////////////////// -/// XFIMA ... -/////////////////////////// - -// -// ZIGZAG Pattern ... -// if (detectZIGZAGPatterns) -// { -// // -// // Detect Market Analysis ... -// XZigZagAnalysis zAnalysis; -// has = fima2Signaller.fimaPOIDetector.AnalyseMarketUsingZigZag( -// cBar, -// cBar.period, -// fima2Signaller.fimaHelper, -// zAnalysis, -// 15 // -// ); -// if (has) -// { -// // -// Print(ShortName + zAnalysis.GetMessage()); - -// // -// XCZigZagAnalysisObject *iObj; -// has = fima2Signaller.fimaPOIDrawer.DrawZigZagMarketAnalysisByPV( -// iObj, -// zAnalysis // -// ); -// if (has) -// { -// draws.Add(iObj); -// } -// } -// } - -// -// Reading Pivots ... -double iLows[]; -double iHighs[]; -double lowTo = 0; -double highTo = 0; -double lowFrom = 0; -double highFrom = 0; -datetime lowToTime = NULL; -datetime highToTime = NULL; -datetime lowFromTime = NULL; -datetime highFromTime = NULL; -double lowsSlope = EMPTY_VALUE; -double highsSlope = EMPTY_VALUE; -double lowsIntercept = EMPTY_VALUE; -double highsIntercept = EMPTY_VALUE; - -// -int iLoopbackLength = 50; -for (int i = 0; i < iLoopbackLength; i++) -{ - // - double iLowPrice = iLow(_Symbol, _Period, i); - double iHighPrice = iHigh(_Symbol, _Period, i); - - // - Add( - iLowPrice, - iLows // - ); - Add( - iHighPrice, - iHighs // - ); -} -has = CalculateLinearRegression( - lowsSlope, - lowsIntercept, - iLows, - 0, - 0 // -); -if (has) -{ - // - lowToTime = GetBarTime( - _Symbol, - _Period, - 0 // - ); - lowTo = CalculateValueBySlopeIntercept( - lowsSlope, - lowsIntercept, - 0 // - ); - - // - lowFromTime = GetBarTime( - _Symbol, - _Period, - iLoopbackLength // - ); - lowFrom = CalculateValueBySlopeIntercept( - lowsSlope, - lowsIntercept, - iLoopbackLength // - ); -} - -// -has = CalculateLinearRegression( - highsSlope, - highsIntercept, - iHighs, - 0, - 0 // -); -if (has) -{ - // - highToTime = GetBarTime( - _Symbol, - _Period, - 0 // - ); - highTo = CalculateValueBySlopeIntercept( - highsSlope, - highsIntercept, - 0 // - ); - - // - highFromTime = GetBarTime( - _Symbol, - _Period, - iLoopbackLength // - ); - highFrom = CalculateValueBySlopeIntercept( - highsSlope, - highsIntercept, - iLoopbackLength // - ); -} - -// -// Try to Draw ... - -// -// Low ... -CChartObjectTrend *iLowTrend; -has = fima2Signaller.fimaPOIDrawer.DrawTrendLine( - lowFrom, - lowFromTime, - lowTo, - lowToTime, - iLowTrend, - "LOW_TREMD", - true // Ray Right ... -); -if (has) -{ - draws.Add(iLowTrend); -} - -// -// High ... -CChartObjectTrend *iHighTrend; -has = fima2Signaller.fimaPOIDrawer.DrawTrendLine( - highFrom, - highFromTime, - highTo, - highToTime, - iHighTrend, - "HIGH_TREMD", - true // Ray Right ... -); -if (has) -{ - draws.Add(iHighTrend); -} - -//////////////////////////////////////////////////////// - -// -// if (HasDirection(marketStructure.signalKeyBarPatternDir)) -// { -// Print("Detected ..."); -// } -// if (marketStructure.ob.IsValid() && marketStructure.fvg.IsValid()) -// { -// Print("Detected ..."); -// } -// if (marketStructure.support.IsValid() || marketStructure.resistance.IsValid()) -// { -// // -// XOHCL pBar; -// XOHCL p2Bar; -// bool has = cBar.GetPreviousBar(pBar); -// has = has && -// pBar.GetPreviousBar(p2Bar); -// if (!has) -// { -// // -// pBar.Clean(); -// p2Bar.Clean(); -// return; -// } - -// // -// // Check For PrevZoneExistanse ... -// has = marketStructure.prevZone.IsValid(); -// if (has) { -// // -// // Draw Prev Zone ... -// XCBoxObject *iPrevZoneObj; -// marketStructure.prevZone.to = pBar.time; -// has = fima2Signaller.poiDrawer.DrawBox( -// marketStructure.prevZone, -// iPrevZoneObj // -// ); -// if (has) -// { -// // -// XPOIStyle style; -// fima2Signaller.poiDrawer.GetBoxStyle( -// style, -// marketStructure.prevZone.dir // -// ); -// style.clr = clrYellow; -// fima2Signaller.poiDrawer.ApplyBoxStyle( -// iPrevZoneObj, -// style // -// ); - -// // -// style.Clean(); -// eaDraws.Add(iPrevZoneObj); -// } -// } - -// // -// if (has) -// { -// Print("Detected ..."); -// } - -// // -// // Cleanup Resources ... -// pBar.Clean(); -// p2Bar.Clean(); -// } - -////////////////////////////////////////////////////////// - -// -XOHCL pBar; -bool has = cBar.GetPreviousBar(pBar); -if (marketStructure.isPTest) -{ - // - // Check For PrevZoneExistanse ... - has = marketStructure.pTestedZone.IsValid(); - if (has) - { - // - // Draw Prev Zone ... - XCBoxObject *iPrevZoneObj; - marketStructure.pTestedZone.to = pBar.time; - has = fima2Signaller.poiDrawer.DrawBox( - marketStructure.pTestedZone, - iPrevZoneObj // - ); - if (has) - { - // - XPOIStyle style; - fima2Signaller.poiDrawer.GetBoxStyle( - style, - marketStructure.pTestedZone.dir // - ); - style.clr = clrYellow; - fima2Signaller.poiDrawer.ApplyBoxStyle( - iPrevZoneObj, - style // - ); - - // - style.Clean(); - eaDraws.Add(iPrevZoneObj); - } - } - - // - Print("Previous Tested ..."); -} -pBar.Clean(); - -///////////////////////////////////////////////////////////// - -// -// Previous Bar must Has Support or Resistance ... - -// -// Check Supports ... -idx = GetYoungestBefore( - pForBar.time, - supports // -); -has = - pForBar.IsValid() && - IsValidIndex(idx); -if (has) -{ - pSupport = supports[idx]; -} - -// -// Check Resistances ... -idx = GetYoungestBefore( - pForBar.time, - resistances // -); -has = - pForBar.IsValid() && - IsValidIndex(idx); -if (has) -{ - pResistance = resistances[idx]; -} - -// -bool isPSupportTouched = - pSupport.IsValid() && - pForBar.low < pSupport.upper; - -// -bool isPResistanceTouched = - pResistance.IsValid() && - pForBar.high > pResistance.lower; - -// -has = - isPSupportTouched || - isPResistanceTouched; -structure.isPTest = has; -if (has) -{ - // - if (isPSupportTouched) - { - // - // Validate Previously Tested Zone Price ... - structure.pTestedZone = pSupport; - } - else if (isPResistanceTouched) - { - // - // Validate Previously Tested Zone Price ... - structure.pTestedZone = pResistance; - } - - // -} - -///////////////////////////////////////////////////////////// - -// // -// // Here We Apply Custom Detecting ... -// detectorConfig.OffDetectors(); -// detectorConfig.detectSupport = true; -// detectorConfig.detectResistance= true; -// detectorConfig.detectSignalKeyBarPattern = true; - -// // -// // Initial Bar for Analysis ... -// // at Signal Time ... -// XOHCL signalBar; -// bool isInited = signalBar.Init( -// signal.symbol, -// signal.period, -// signal.time // -// ); - -// // -// // Analyse Market ... -// fima1Signaller.poiDetector.AnalyseMarket( -// signalBar, -// marketStructure, -// detectorConfig // -// ); -// CArrayObj *iObjects; -// int drawnsCount = fima2Signaller.poiDrawer.DrawMarketStructure( -// marketStructure, -// marketStructureDrawerConfig, -// iObjects // -// ); -// if (IsValidSize(drawnsCount)) -// { -// // -// AddObjects( -// iObjects, -// eaDraws // -// ); -// } - -///////////////////////////////////////////////////////////// - -// -// On Tick Handler ... -void OnTick() -{ - // - eaIsNewBar = eaBarTracker.IsNewBar(); - bool canProcess = eaProcessAllTicks - ? true - : eaIsNewBar; - // - eaExpert.HandleOnTick(); - - // - if (!canProcess) - { - return; - } - - // - fima1Signaller.OnTick(); - fima2Signaller.OnTick(); - - // - // Initial Bar for Analysis ... - XOHCL cBar; - bool isInited = cBar.Init( - _Symbol, - _Period, - 0 // - ); - - // - // Here We Apply Custom Detecting ... - detectorConfig.OffDetectors(); - detectorConfig.detectSupport = true; - detectorConfig.detectResistance = true; - detectorConfig.detectSignalKeyBarPattern = false; - detectorConfig.supportAndResistanceValidationLength = 21; - - // - // Analyse Market ... - fima2Signaller.poiDetector.AnalyseMarket( - cBar, - marketStructure, - detectorConfig // - ); - CArrayObj *iObjects; - int drawnsCount = fima2Signaller.poiDrawer.DrawMarketStructure( - marketStructure, - marketStructureDrawerConfig, - iObjects // - ); - if (IsValidSize(drawnsCount)) - { - // - AddObjects( - iObjects, - eaDraws // - ); - } - - // - // TODO: Remove this ... - XOHCL pBar; - bool has = cBar.GetPreviousBar(pBar); - if (marketStructure.fakeBreakedZone.IsValid()) - { - // - // Check For PrevZoneExistanse ... - has = marketStructure.fakeBreakedZone.IsValid(); - if (has) - { - // - // Draw Prev Zone ... - XCBoxObject *iPrevZoneObj; - marketStructure.fakeBreakedZone.to = pBar.time; - has = fima2Signaller.poiDrawer.DrawBox( - marketStructure.fakeBreakedZone, - iPrevZoneObj // - ); - if (has) - { - // - XPOIStyle style; - fima2Signaller.poiDrawer.GetBoxStyle( - style, - marketStructure.fakeBreakedZone.dir // - ); - style.clr = clrYellow; - fima2Signaller.poiDrawer.ApplyBoxStyle( - iPrevZoneObj, - style // - ); - - // - style.Clean(); - eaDraws.Add(iPrevZoneObj); - } - } - - // - Print("Fake Breaked Detection ..."); - } - if (HasChild(marketStructure.recentlyTestedZones)) - { - // - int idx = GetYoungest(marketStructure.recentlyTestedZones); - bool has = IsValidIndex(idx); - if (has) - { - // - has = IsTested( - pBar, - marketStructure.recentlyTestedZones[idx] // - ); - } - - // - if (has) - { - Print("PrevZone Exists ..."); - } - } - pBar.Clean(); - - // - cBar.Clean(); -} - -// -void AnalyseMarket(int barIndex = 0) -{ - // - bool has = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - string symbol = fima1Signaller.symbol; - ENUM_TIMEFRAMES period = fima1Signaller.period; - - // - // Retrieve Signal Bar ... - XOHCL bar; - has = bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // TODO: Remove this and add in OnInit() Method ... - - // - // Configuring Detector ... - - - // - detectorConfig.detectSwingTrend = true; - - // - detectorConfig.detectPinned = true; - detectorConfig.detectMomentum = true; - detectorConfig.detectEngulfed = true; - detectorConfig.detectTrueGaped = true; - - // - detectorConfig.detectStarPattern = true; - detectorConfig.detectFlagPattern = true; - detectorConfig.detectRisingPattern = true; - detectorConfig.detectPiercingPattern = true; - detectorConfig.detectSignalKeyBarPattern = true; - - // - detectorConfig.analyseFIMAPVPivots = true; - detectorConfig.analyseFIMAZigZagPivots = true; - - // - // Configure Drawer ... - - // - marketStructureDrawerConfig.drawOB = false; - marketStructureDrawerConfig.drawFVG = false; - - // - marketStructureDrawerConfig.drawPinned = false; - marketStructureDrawerConfig.drawEngulfed = true; - marketStructureDrawerConfig.drawTrueGaped = false; - marketStructureDrawerConfig.drawMomentum = false; - marketStructureDrawerConfig.drawFlagPattern = false; - marketStructureDrawerConfig.drawStarPattern = false; - marketStructureDrawerConfig.drawRisingPattern = false; - marketStructureDrawerConfig.drawPiercingPattern = false; - marketStructureDrawerConfig.drawSignalKeyBarPattern = true; - - // - // Recents ... - marketStructureDrawerConfig.drawRecentPatterns = false; - marketStructureDrawerConfig.drawFakeBreakedZone = false; - marketStructureDrawerConfig.drawRecentlyTestedZones = false; - marketStructureDrawerConfig.drawRecentlyBreakedZones = false; - - // - // XPV ... - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysis = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisZones = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisTrends = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisPivots = true; - - // - // XSAR ... - marketStructureDrawerConfig.drawFIMASARPivotsAnalysis = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisZones = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisTrends = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisPivots = false; - - // - // XZigZag ... - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysis = true; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisZones = true; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisTrends = false; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisPivots = false; - - // - // Analyse Market on Signalling Bar ... - fima1Signaller.poiDetector.AnalyseMarket( - bar, - marketStructure, - detectorConfig // - ); - - // - bar.Clean(); -} diff --git a/Documents/BKP/tmp.codes.mq5 b/Documents/BKP/tmp.codes.mq5 deleted file mode 100644 index 21a5c942..00000000 --- a/Documents/BKP/tmp.codes.mq5 +++ /dev/null @@ -1,7167 +0,0 @@ -// -int minRequiredRange = 20; -if (barIndex > maxBarIndex - minRequiredRange - 4) -{ - return; -} - -// -double iP2SCLL = sLLBuffer[barIndex + 2]; -double iP2SCHH = sHHBuffer[barIndex + 2]; - -// -double iP3SCLL = sLLBuffer[barIndex + 3]; -double iP3SCHH = sHHBuffer[barIndex + 3]; - -// -double iP4SCLL = sLLBuffer[barIndex + 4]; -double iP4SCHH = sHHBuffer[barIndex + 4]; - -// -double iP2MCLL = mLLBuffer[barIndex + 2]; -double iP2MCHH = mHHBuffer[barIndex + 2]; - -// -double iP3MCLL = mLLBuffer[barIndex + 3]; -double iP3MCHH = mHHBuffer[barIndex + 3]; - -// -double iP4MCLL = mLLBuffer[barIndex + 4]; -double iP4MCHH = mHHBuffer[barIndex + 4]; - -// -double iP2LCLL = lLLBuffer[barIndex + 2]; -double iP2LCHH = lHHBuffer[barIndex + 2]; - -// -double iP3LCLL = lLLBuffer[barIndex + 3]; -double iP3LCHH = lHHBuffer[barIndex + 3]; - -// -double iP4LCLL = lLLBuffer[barIndex + 4]; -double iP4LCHH = lHHBuffer[barIndex + 4]; - -// -double iP2HCLL = hLLBuffer[barIndex + 2]; -double iP2HCHH = hHHBuffer[barIndex + 2]; - -// -double iP3HCLL = hLLBuffer[barIndex + 3]; -double iP3HCHH = hHHBuffer[barIndex + 3]; - -// -double iP4HCLL = hLLBuffer[barIndex + 4]; -double iP4HCHH = hHHBuffer[barIndex + 4]; - -// -// Cycle States ... - -// -// Create Conditions ... - -// -bool isSCMaOverMCMa = iSCMa > iMCMa; -bool isPSCMaOverMCMa = iPSCMa > iPMCMa; - -// -bool isSCMaUnderMCMa = iSCMa < iMCMa; -bool isPSCMaUnderMCMa = iPSCMa < iPMCMa; - -// -bool isSCMaCrossedOverMCMa = - isSCMaOverMCMa && - !isPSCMaOverMCMa; - -// -bool isSCMaCrossedUnderMCMa = - isSCMaUnderMCMa && - !isPSCMaUnderMCMa; - -// -bool isLCMaOverHCMa = iLCMa > iHCMa; -bool isPLCMaOverHCMa = iPLCMa > iPHCMa; - -// -bool isLCMaUnderHCMa = iLCMa < iHCMa; -bool isPLCMaUnderHCMa = iPLCMa < iPHCMa; - -// -bool isLCMaCrossedOverHCMa = - isLCMaOverHCMa && - !isPLCMaOverHCMa; - -// -bool isLCMaCrossedUnderHCMa = - isLCMaUnderHCMa && - !isPLCMaUnderHCMa; - -// -// SC State ... - -// -bool isSCMaBullish = - iSCMaState == bullishState; -bool isPSCMaBullish = - iPSCMaState == bullishState; - -// -bool isSCMaBearish = - iSCMaState == bearishState; -bool isPSCMaBearish = - iPSCMaState == bearishState; - -// -bool isSCMaSwitchedToBullish = - isSCMaBullish && - !isPSCMaBullish; - -// -bool isSCMaSwitchedToBearish = - isSCMaBearish && - !isPSCMaBearish; - -// -bool isSCLLOverMCLL = - iSCLL > iMCLL; -bool isPSCLLOverMCLL = - iPSCLL > iPMCLL; -bool isP2SCLLOverMCLL = - iP2SCLL > iP2MCLL; -bool isP3SCLLOverMCLL = - iP3SCLL > iP3MCLL; -bool isP4SCLLOverMCLL = - iP4SCLL > iP4MCLL; - -// -bool isSCHHUnderMCHH = - iSCHH < iMCHH; -bool isPSCHHUnderMCHH = - iPSCHH < iPMCHH; -bool isP2SCHHUnderMCHH = - iP2SCHH < iP2MCHH; -bool isP3SCHHUnderMCHH = - iP3SCHH < iP3MCHH; -bool isP4SCHHUnderMCHH = - iP4SCHH < iP4MCHH; - -// -bool isSCLLCrossedOverMCLL = - isSCLLOverMCLL && - !isPSCLLOverMCLL; -bool isPSCLLCrossedOverMCLL = - isPSCLLOverMCLL && - !isP2SCLLOverMCLL; -bool isP2SCLLCrossedOverMCLL = - isP2SCLLOverMCLL && - !isP3SCLLOverMCLL; -bool isP3SCLLCrossedOverMCLL = - isP3SCLLOverMCLL && - !isP4SCLLOverMCLL; - -// -bool isSCHHCrossedUnderMCHH = - isSCHHUnderMCHH && - !isPSCHHUnderMCHH; -bool isPSCHHCrossedUnderMCHH = - isPSCHHUnderMCHH && - !isP2SCHHUnderMCHH; -bool isP2SCHHCrossedUnderMCHH = - isP2SCHHUnderMCHH && - !isP3SCHHUnderMCHH; -bool isP3SCHHCrossedUnderMCHH = - isP3SCHHUnderMCHH && - !isP4SCHHUnderMCHH; - -// -// MC State ... - -// -bool isMCMaBullish = - iMCMaState == bullishState; -bool isPMCMaBullish = - iPMCMaState == bullishState; - -// -bool isMCMaBearish = - iMCMaState == bearishState; -bool isPMCMaBearish = - iPMCMaState == bearishState; - -// -bool isMCMaSwitchedToBullish = - isMCMaBullish && - !isPMCMaBullish; - -// -bool isMCMaSwitchedToBearish = - isMCMaBearish && - !isPMCMaBearish; - -// -bool isMCLLOverLCLL = - iMCLL > iLCLL; -bool isPMCLLOverLCLL = - iPMCLL > iPLCLL; -bool isP2MCLLOverLCLL = - iP2MCLL > iP2LCLL; -bool isP3MCLLOverLCLL = - iP3MCLL > iP3LCLL; -bool isP4MCLLOverLCLL = - iP4MCLL > iP4LCLL; - -// -bool isMCHHUnderLCHH = - iMCHH < iLCHH; -bool isPMCHHUnderLCHH = - iPMCHH < iPLCHH; -bool isP2MCHHUnderLCHH = - iP2MCHH < iP2LCHH; -bool isP3MCHHUnderLCHH = - iP3MCHH < iP3LCHH; -bool isP4MCHHUnderLCHH = - iP4MCHH < iP4LCHH; - -// -bool isMCLLCrossedOverLCLL = - isMCLLOverLCLL && - !isPMCLLOverLCLL; -bool isPMCLLCrossedOverLCLL = - isPMCLLOverLCLL && - !isP2MCLLOverLCLL; -bool isP2MCLLCrossedOverLCLL = - isP2MCLLOverLCLL && - !isP3MCLLOverLCLL; -bool isP3MCLLCrossedOverLCLL = - isP3MCLLOverLCLL && - !isP4MCLLOverLCLL; - -// -bool isMCHHCrossedUnderLCHH = - isMCHHUnderLCHH && - !isPMCHHUnderLCHH; -bool isPMCHHCrossedUnderLCHH = - isPMCHHUnderLCHH && - !isP2MCHHUnderLCHH; -bool isP2MCHHCrossedUnderLCHH = - isP2MCHHUnderLCHH && - !isP3MCHHUnderLCHH; -bool isP3MCHHCrossedUnderLCHH = - isP3MCHHUnderLCHH && - !isP4MCHHUnderLCHH; - -// -// LC State ... - -// -bool isLCMaBullish = - iLCMaState == bullishState; -bool isPLCMaBullish = - iPLCMaState == bullishState; - -// -bool isLCMaBearish = - iLCMaState == bearishState; -bool isPLCMaBearish = - iPLCMaState == bearishState; - -// -bool isLCMaSwitchedToBullish = - isLCMaBullish && - !isPLCMaBullish; - -// -bool isLCMaSwitchedToBearish = - isLCMaBearish && - !isPLCMaBearish; - -// -bool isLCLLOverHCLL = - iLCLL > iHCLL; -bool isPLCLLOverHCLL = - iPLCLL > iPHCLL; -bool isP2LCLLOverHCLL = - iP2LCLL > iP2HCLL; -bool isP3LCLLOverHCLL = - iP3LCLL > iP3HCLL; -bool isP4LCLLOverHCLL = - iP4LCLL > iP4HCLL; - -// -bool isLCHHUnderHCHH = - iLCHH < iHCHH; -bool isPLCHHUnderHCHH = - iPLCHH < iPHCHH; -bool isP2LCHHUnderHCHH = - iP2LCHH < iP2HCHH; -bool isP3LCHHUnderHCHH = - iP3LCHH < iP3HCHH; -bool isP4LCHHUnderHCHH = - iP4LCHH < iP4HCHH; - -// -bool isLCLLCrossedOverHCLL = - isLCLLOverHCLL && - !isPLCLLOverHCLL; -bool isPLCLLCrossedOverHCLL = - isPLCLLOverHCLL && - !isP2LCLLOverHCLL; -bool isP2LCLLCrossedOverHCLL = - isP2LCLLOverHCLL && - !isP3LCLLOverHCLL; -bool isP3LCLLCrossedOverHCLL = - isP3LCLLOverHCLL && - !isP4LCLLOverHCLL; - -// -bool isLCHHCrossedUnderHCHH = - isLCHHUnderHCHH && - !isPLCHHUnderHCHH; -bool isPLCHHCrossedUnderHCHH = - isPLCHHUnderHCHH && - !isP2LCHHUnderHCHH; -bool isP2LCHHCrossedUnderHCHH = - isP2LCHHUnderHCHH && - !isP3LCHHUnderHCHH; -bool isP3LCHHCrossedUnderHCHH = - isP3LCHHUnderHCHH && - !isP4LCHHUnderHCHH; - -// -// HC State ... - -// -bool isHCMaBullish = - iHCMaState == bullishState; -bool isPHCMaBullish = - iPHCMaState == bullishState; - -// -bool isHCMaBearish = - iHCMaState == bearishState; -bool isPHCMaBearish = - iPHCMaState == bearishState; - -// -bool isHCMaSwitchedToBullish = - isHCMaBullish && - !isPHCMaBullish; - -// -bool isHCMaSwitchedToBearish = - isHCMaBearish && - !isPHCMaBearish; - -/////////////////////////////////////////////////////////////////////////////// - -// -// HK Signal Bar ... - -// -double iHKSOpen = hkSBarOpenBuffer[barIndex]; -double iHKSClose = hkSBarCloseBuffer[barIndex]; - -// -double iHKSMax = MathMax(iHKSOpen, iHKSClose); -double iHKSMin = MathMin(iHKSOpen, iHKSClose); - -// -bool isHKSBullish = hkSBarOpenBuffer[barIndex] < hkSBarCloseBuffer[barIndex]; -bool isPHKSBullish = hkSBarOpenBuffer[barIndex + 1] < hkSBarCloseBuffer[barIndex + 1]; - -// -bool isHKSBearish = hkSBarOpenBuffer[barIndex] > hkSBarCloseBuffer[barIndex]; -bool isPHKSBearish = hkSBarOpenBuffer[barIndex + 1] > hkSBarCloseBuffer[barIndex + 1]; - -// -bool isHKSSwitchedToBullish = - isHKSBullish && - !isPHKSBullish; - -// -bool isHKSSwitchedToBearish = - isHKSBearish && - !isPHKSBearish; - -// -// TREND ... - -// -double iTrend = trendBuffer[barIndex]; -bool isTrendBullish = trendStateBuffer[barIndex] > 0; -bool isTrendBearish = trendStateBuffer[barIndex] < 0; -bool isTrendSwitchedToBullish = - trendStateBuffer[barIndex] > 0 && - trendStateBuffer[barIndex + 1] <= 0; -bool isTrendSwitchedToBearish = - trendStateBuffer[barIndex] < 0 && - trendStateBuffer[barIndex + 1] >= 0; - -// -// RSI ... - -// -bool isRSIOverOB = rsiBuffer[barIndex] > rsiOBLevel; -bool isPRSIOverOB = rsiBuffer[barIndex + 1] > rsiOBLevel; - -// -bool isRSIUnderOB = rsiBuffer[barIndex] < rsiOBLevel; -bool isPRSIUnderOB = rsiBuffer[barIndex + 1] < rsiOBLevel; - -// -bool isRSICrossedOverOB = - isRSIOverOB && - !isPRSIOverOB; - -// -bool isRSICrossedUnderOB = - isRSIUnderOB && - !isPRSIUnderOB; - -// -bool isRSIOverOS = rsiBuffer[barIndex] > rsiOSLevel; -bool isPRSIOverOS = rsiBuffer[barIndex + 1] > rsiOSLevel; - -// -bool isRSIUnderOS = rsiBuffer[barIndex] < rsiOSLevel; -bool isPRSIUnderOS = rsiBuffer[barIndex + 1] < rsiOSLevel; - -// -bool isRSICrossedOverOS = - isRSIOverOS && - !isPRSIOverOS; - -// -bool isRSICrossedUnderOS = - isRSIUnderOS && - !isPRSIUnderOS; - -// -// ADX ... - -// -bool isADXOverThreshold = adxBuffer[barIndex] > adxThreshold; -bool isPADXOverThreshold = adxBuffer[barIndex + 1] > adxThreshold; - -// -bool isADXUnderThreshold = adxBuffer[barIndex] < adxThreshold; -bool isPADXUnderThreshold = adxBuffer[barIndex + 1] < adxThreshold; - -// -bool isADXCrossedOverThreshold = - isADXOverThreshold && - !isPADXOverThreshold; - -// -bool isADXCrossedUnderThreshold = - isADXUnderThreshold && - !isPADXUnderThreshold; - -// -bool isADXBullish = adxpBuffer[barIndex] > adxnBuffer[barIndex]; -bool isPADXBullish = adxpBuffer[barIndex + 1] > adxnBuffer[barIndex + 1]; - -// -bool isADXBearish = adxpBuffer[barIndex] < adxnBuffer[barIndex]; -bool isPADXBearish = adxpBuffer[barIndex + 1] < adxnBuffer[barIndex + 1]; - -// -bool isADXSwitchedToBullish = - isADXBullish && - !isPADXBullish; - -// -bool isADXSwitchedToBearish = - isADXBearish && - !isPADXBearish; - -// -bool isADXFullySwitchedToBullish = - isADXSwitchedToBullish && - isADXCrossedOverThreshold; - -// -bool isADXFullySwitchedToBearish = - isADXSwitchedToBearish && - isADXCrossedUnderThreshold; - -// -bool isTriggerBarOverHKS = - iBar.low > iHKSMax; -bool isTriggerBarUnderHKS = - iBar.high < iHKSMin; - -// -// KI ... - -// -bool isKIBullish = kiStateBuffer[barIndex] > 0; -bool isPKIBullish = kiStateBuffer[barIndex + 1] > 0; - -// -bool isKIBearish = kiStateBuffer[barIndex] < 0; -bool isPKIBearish = kiStateBuffer[barIndex = 1] < 0; - -// // -// bool isKIOverHKS = -// kiBuffer[barIndex] > iHKSMax; - -// // -// bool isKIUnderHKS = -// kiBuffer[barIndex] < iHKSMin; - -// -bool isKISwitchedToBullish = - isKIBullish && - !isPKIBullish; - -// -bool isKISwitchedToBearish = - isKIBearish && - !isPKIBearish; - -// -// Detecting Signal ... - -// -// Bullish ... -isBullish = - // - false - // Conditions Validation ... - // isKIOverHKS && - // isHKSBullish && - // isKISwitchedToBullish - // && - // - // Bar Validation ... - // iBar.IsBullish() && - // iBar.close > kiBuffer[barIndex] - // - ; - -// -// Bearish ... -isBearish = - // - false - // Conditions Validation ... - // isKIUnderHKS && - // isHKSBearish && - // isKISwitchedToBearish - // && - // - // Bar Validation ... - // iBar.IsBearish() && - // iBar.close < kiBuffer[barIndex] - // - ; - -//////////////////////////////////////////////////////////////////// - -// -int mSameKICount = 0; -int mSameKIBullishCount = 0; -int mSameKIBearishCount = 0; - -// -int mSamePeakCount = 0; -int mSameValeCount = 0; - -// -double mSamePeaksGoldenMin = 0; -double mSamePeaksGoldenMax = 0; - -// -double mSameValesGoldenMin = 0; -double mSameValesGoldenMax = 0; - -// -int mSamePeakGoldenCount = 0; -int mSameValeGoldenCount = 0; - -// -bool mDrawLiquidities = false; -bool mDrawRangeBreakes = false; - -// -bool mDetectLiquidities = true; -bool mDetectRangeBreakes = true; - -// -XBoxZone mBullishLiquidities[]; -XBoxZone mBearishLiquidities[]; -XBoxZone mBullishRangeBreakes[]; -XBoxZone mBearishRangeBreakes[]; - -// -// POI(s) Handlers ... -// - -/** - * Detect POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DetectPOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Some Requirements ... - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Handle Minimum Required Bars ... - bool isPassedRequiredBars = barIndex < maxBarIndex - 3; - if (!isPassedRequiredBars) - { - return; - } - - // - // Recieve Bar ... - XOHCL iBar; - XOHCL iPBar; - bool has = iBar.Init( - _Symbol, - _Period, - barIndex - // - ); - has = - has && - iBar.GetPreviousBar(iPBar); - if (!has) - { - return; - } - - // - bool isBullish = false; - bool isBearish = false; - int maxAllowedPOIs = 50; - - // - ENUM_X_DIRECTION iDir; - - // - // Detecting Liquidity ... - if (mDetectLiquidities) - { - // - bool isLiquidity = - mBarAnalyser - .IsRejected( - iBar, - iDir, - true, - true // - ); - bool isBullishLiquiditySweeped = - isLiquidity && - IsBullish(iDir); - bool isBearishLiquiditySweeped = - isLiquidity && - IsBearish(iDir); - if (isLiquidity) - { - // - XBoxZone iLiq; - - // - iLiq.dir = iDir; - iLiq.type = "XLIQ"; - iLiq.upper = - isBullishLiquiditySweeped - ? iBar.GetDown() - : iBar.high; - iLiq.lower = - isBullishLiquiditySweeped - ? iBar.low - : iBar.GetUp(); - iLiq.at = iBar.time; - iLiq.from = iBar.time; - iLiq.symbol = _Symbol; - iLiq.period = _Period; - iLiq.to = ((datetime)((int)iBar.time + (PeriodSeconds(_Period)))); - - // - if (iLiq.IsValid()) - { - // - if (isBullishLiquiditySweeped) - { - // - has = AddBoxIfNotExists( - iLiq, - mBullishLiquidities // - ); - if (has) - { - // - SortBoxes( - mBullishLiquidities, - maxAllowedPOIs // - ); - } - } - else - { - // - has = AddBoxIfNotExists( - iLiq, - mBearishLiquidities // - ); - if (has) - { - // - SortBoxes( - mBearishLiquidities, - maxAllowedPOIs // - ); - } - } - } - - // - iLiq.Clean(); - } - } - - // - // Detecting Bullish and Bearish Breakes ... - - // - bool isPeakSame = peakBuffer[barIndex] == peakBuffer[barIndex + 1]; - bool isPPeakSame = peakBuffer[barIndex + 1] == peakBuffer[barIndex + 2]; - - // - bool isPeakOverLast = peakBuffer[barIndex] > peakBuffer[barIndex + 1]; - bool isPPeakOverLast = peakBuffer[barIndex + 1] > peakBuffer[barIndex + 2]; - - // - bool isPeakUnderLast = peakBuffer[barIndex] < peakBuffer[barIndex + 1]; - bool isPPeakUnderLast = peakBuffer[barIndex + 1] < peakBuffer[barIndex + 2]; - - // - bool isSamePeakOverLast = - isPPeakSame && - isPeakOverLast; - bool isSamePeakUnderLast = - isPPeakSame && - isPeakUnderLast; - - // - bool isValeSame = valeBuffer[barIndex] == valeBuffer[barIndex + 1]; - bool isPValeSame = valeBuffer[barIndex + 1] == valeBuffer[barIndex + 2]; - - // - bool isValeOverLast = valeBuffer[barIndex] > valeBuffer[barIndex + 1]; - bool isPValeOverLast = valeBuffer[barIndex + 1] > valeBuffer[barIndex + 2]; - - // - bool isValeUnderLast = valeBuffer[barIndex] < valeBuffer[barIndex + 1]; - bool isPValeUnderLast = valeBuffer[barIndex + 1] < valeBuffer[barIndex + 2]; - - // - bool isSameValeOverLast = - isPValeSame && - isValeOverLast; - bool isSameValeUnderLast = - isPValeSame && - isValeUnderLast; - - // - // Detecting Range Breakes ... - if (mDetectRangeBreakes) - { - // - isBullish = isSamePeakOverLast - // || isSameValeOverLast - ; - isBearish = - isSameValeUnderLast - // || isSamePeakUnderLast - ; - - // - bool basedOnPeak = - isSamePeakOverLast - // || isSamePeakUnderLast - ; - - // - bool basedOnVale = - isSameValeUnderLast - // isSameValeOverLast || - ; - - // - has = isBullish || - isBearish; - - // - if (has) - { - // - XBoxZone iRNGBreak; - - // - iDir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - iRNGBreak.dir = iDir; - iRNGBreak.at = iBar.time; - iRNGBreak.type = "XRNGB"; - iRNGBreak.to = iBar.time; - iRNGBreak.symbol = _Symbol; - iRNGBreak.period = _Period; - - // - int fromIDX = - iBar.Index() + - (basedOnPeak - ? mSamePeakCount - : basedOnVale - ? mSameValeCount - : 0); - datetime from = GetBarTime( - _Symbol, - _Period, - fromIDX // - ); - iRNGBreak.from = from; - - // - double upper = - isBullish - ? basedOnPeak - ? peakBuffer[barIndex] - : basedOnVale - ? mSameValeGoldenCount - : 0 - : isBearish - ? basedOnPeak - ? peakBuffer[barIndex] - : basedOnVale - ? mSameValeGoldenCount - : 0 - : 0; - - // - double lower = - isBullish - ? basedOnPeak - ? mSamePeakGoldenCount - : basedOnVale - ? valeBuffer[barIndex] - : 0 - : isBearish - ? basedOnPeak - ? mSamePeakGoldenCount - : basedOnVale - ? valeBuffer[barIndex] - : 0 - : 0; - - // - iRNGBreak.upper = upper; - iRNGBreak.lower = lower; - - // - // Adding POI ... - has = iRNGBreak.IsValid(); - if (has) - { - // - if (isBullish) - { - // - has = AddBoxIfNotExists( - iRNGBreak, - mBullishRangeBreakes // - ); - if (has) - { - // - SortBoxes( - mBullishRangeBreakes, - maxAllowedPOIs // - ); - } - } - else if (isBearish) - { - // - has = AddBoxIfNotExists( - iRNGBreak, - mBearishRangeBreakes // - ); - if (has) - { - // - SortBoxes( - mBearishRangeBreakes, - maxAllowedPOIs // - ); - } - } - } - } - } - - // - if (isPeakSame) - { - // - mSamePeakGoldenCount = - mSamePeakGoldenCount == 0 - ? iBar.GetUp() - : MathMax(mSamePeakGoldenCount, iBar.GetUp()); - mSamePeakCount++; - } - else - { - // - mSamePeakCount = 0; - mSamePeakGoldenCount = 0; - } - - // - if (isValeSame) - { - // - mSameValeGoldenCount = - mSameValeGoldenCount == 0 - ? iBar.GetDown() - : MathMin(mSameValeGoldenCount, iBar.GetDown()); - mSameValeCount++; - } - else - { - // - mSameValeCount = 0; - mSameValeGoldenCount = 0; - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - iPBar.Clean(); -} - -/** - * Validate Detected POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void ValidatePOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int count = 0; - bool has = false; - int barsLength = 3; - datetime to = GetBarTime( - _Symbol, - _Period, - barIndex // - ); - - // - // Liquidities ... - - // - // Bullish Liquidities ... - count = ArraySize(mBullishLiquidities); - has = IsValidSize(count); - if (has) - { - // - ValidateBoxes( - mBullishLiquidities, - barIndex, - barsLength // - ); - } - - // - // Bearish Liquidities ... - count = ArraySize(mBearishLiquidities); - has = IsValidSize(count); - if (has) - { - // - ValidateBoxes( - mBearishLiquidities, - barIndex, - barsLength // - ); - } - - // - // Range Breaks ... - - // - // Bullish ... - count = ArraySize(mBullishRangeBreakes); - has = IsValidSize(count); - if (has) - { - // - ValidateBoxes( - mBullishRangeBreakes, - barIndex, - barsLength // - ); - } - - // - // Bearish ... - count = ArraySize(mBearishRangeBreakes); - has = IsValidSize(count); - if (has) - { - // - ValidateBoxes( - mBearishRangeBreakes, - barIndex, - barsLength // - ); - } - - // -} - -/** - * Draw Detected POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DrawPOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int count = 0; - XBoxZone iBox; - bool has = false; - datetime to = GetBarTime( - _Symbol, - _Period, - barIndex // - ); - - // - // Liquidities ... - if (mDrawLiquidities) - { - // - count = ArraySize(mBullishLiquidities); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - iBox = mBullishLiquidities[i]; - iBox.to = to; - - // - XCBoxObject *iObj; - has = mDrawer.DrawBox( - iBox, - iObj // - ); - if (has) - { - mObjects.Add(iObj); - } - - // - iBox.Clean(); - } - } - - // - count = ArraySize(mBearishLiquidities); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - iBox = mBearishLiquidities[i]; - iBox.to = to; - - // - XCBoxObject *iObj; - has = mDrawer.DrawBox( - iBox, - iObj // - ); - if (has) - { - mObjects.Add(iObj); - } - - // - iBox.Clean(); - } - } - } - - // - // Range Breaks ... - if (mDrawRangeBreakes) - { - // - // Bullish ... - count = ArraySize(mBullishRangeBreakes); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - iBox = mBullishRangeBreakes[i]; - iBox.to = to; - - // - XCBoxObject *iObj; - has = mDrawer.DrawBox( - iBox, - iObj // - ); - if (has) - { - // - XPOIStyle iStyle; - iStyle.width = 1; - iStyle.clr = clrAqua; - iStyle.style = STYLE_DOT; - - // - mDrawer.ApplyStyle( - iObj, - iStyle // - ); - - // - mObjects.Add(iObj); - } - - // - iBox.Clean(); - } - } - - // - // Bearish ... - count = ArraySize(mBearishRangeBreakes); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - iBox = mBearishRangeBreakes[i]; - iBox.to = to; - - // - XCBoxObject *iObj; - has = mDrawer.DrawBox( - iBox, - iObj // - ); - if (has) - { - // - XPOIStyle iStyle; - iStyle.width = 1; - iStyle.clr = clrMagenta; - iStyle.style = STYLE_DOT; - - // - mDrawer.ApplyStyle( - iObj, - iStyle // - ); - - // - mObjects.Add(iObj); - } - - // - iBox.Clean(); - } - } - } - - // -} - -/** - * Process Custom Analysing Senarios ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DoProcess( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Some Requirements ... - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Recieve Bar ... - XOHCL iBar; - XOHCL iPBar; - bool has = iBar.Init( - _Symbol, - _Period, - barIndex - // - ); - has = - has && - iBar.GetPreviousBar(iPBar); - if (!has) - { - return; - } - - // - // Do Process ... - - // - // Detecting Trigger Bar ... - - // - bool hasSignal = false; - bool isBullish = false; - bool isBearish = false; - string namePrefix = NULL; - int triggerBarPushers = 0; - ENUM_X_DIRECTION triggerDir; - - // - // Detecting Trigger Bars ... - - // - bool isCond1Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - true, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond1BullishTrigger = - isCond1Trigger && - IsBullish(triggerDir); - bool isCond1BearishTrigger = - isCond1Trigger && - IsBearish(triggerDir); - if (isCond1Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond1"; - } - - // - bool isCond2Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - true, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond2BullishTrigger = - isCond2Trigger && - IsBullish(triggerDir); - bool isCond2BearishTrigger = - isCond2Trigger && - IsBearish(triggerDir); - if (isCond2Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond2"; - } - - // - bool isCond3Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - false, // Cond 2 ... - true, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond3BullishTrigger = - isCond3Trigger && - IsBullish(triggerDir); - bool isCond3BearishTrigger = - isCond3Trigger && - IsBearish(triggerDir); - if (isCond3Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond3"; - } - - // - bool isCond4Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - true, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond4BullishTrigger = - isCond4Trigger && - IsBullish(triggerDir); - bool isCond4BearishTrigger = - isCond4Trigger && - IsBearish(triggerDir); - if (isCond4Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond4"; - } - - // - bool isCond5Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - true, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond5BullishTrigger = - isCond5Trigger && - IsBullish(triggerDir); - bool isCond5BearishTrigger = - isCond5Trigger && - IsBearish(triggerDir); - if (isCond5Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond5"; - } - - // - bool isCond6Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - true, // Cond 6 ... - false // Cond 7 ... - ); - bool isCond6BullishTrigger = - isCond6Trigger && - IsBullish(triggerDir); - bool isCond6BearishTrigger = - isCond6Trigger && - IsBearish(triggerDir); - if (isCond6Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond6"; - } - - // - bool isCond7Trigger = - mBarAnalyser - .IsValidForTrigger( - iPBar, - triggerDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - true // Cond 7 ... - ); - bool isCond7BullishTrigger = - isCond7Trigger && - IsBullish(triggerDir); - bool isCond7BearishTrigger = - isCond7Trigger && - IsBearish(triggerDir); - if (isCond7Trigger) - { - // - triggerBarPushers++; - namePrefix += "Cond7"; - } - - // - // Summarizing Trigger Bars ... - - // - bool isBullishTriggerBar = - // - isCond1BullishTrigger || - isCond2BullishTrigger || - isCond3BullishTrigger || - isCond4BullishTrigger || - isCond5BullishTrigger || - isCond6BullishTrigger || - isCond7BullishTrigger - // - ; - - // - bool isBearishTriggerBar = - // - isCond1BearishTrigger || - isCond2BearishTrigger || - isCond3BearishTrigger || - isCond4BearishTrigger || - isCond5BearishTrigger || - isCond6BearishTrigger || - isCond7BearishTrigger - // - ; - - // - bool isTriggerBar = - // - triggerBarPushers >= 1 && - (isBullishTriggerBar || - isBearishTriggerBar) - // - ; - - // - // Reading Required Condiions ... - - // - int pIndex = barIndex + 1; - int ppIndex = barIndex + 2; - - // - // PV ... - - // - bool isSamePeak = peakBuffer[pIndex] == peakBuffer[ppIndex]; - bool isSameVale = valeBuffer[pIndex] == valeBuffer[ppIndex]; - - // - bool isPeakOverLast = peakBuffer[pIndex] > peakBuffer[ppIndex]; - bool isPeakUnderLast = peakBuffer[pIndex] < peakBuffer[ppIndex]; - - // - bool isValeOverLast = valeBuffer[pIndex] > valeBuffer[ppIndex]; - bool isValeUnderLast = valeBuffer[pIndex] < valeBuffer[ppIndex]; - - // - bool isSamePeakGolden = peakGoldenBuffer[pIndex] == peakGoldenBuffer[ppIndex]; - bool isSameValeGolden = valeGoldenBuffer[pIndex] == valeGoldenBuffer[ppIndex]; - - // - bool isPeakGoldeOverLast = peakGoldenBuffer[pIndex] > peakGoldenBuffer[ppIndex]; - bool isPeakGoldenUnderLast = peakGoldenBuffer[pIndex] < peakGoldenBuffer[ppIndex]; - - // - bool isValeGoldenOverLast = valeGoldenBuffer[pIndex] > valeGoldenBuffer[ppIndex]; - bool isValeGoldenUnderLast = valeGoldenBuffer[pIndex] < valeGoldenBuffer[ppIndex]; - - // - if (isSamePeak) - { - mSamePeakCount++; - } - else - { - mSamePeakCount = 0; - } - - // - if (isSameVale) - { - mSameValeCount++; - } - else - { - mSameValeCount = 0; - } - - // - if (isSamePeakGolden) - { - mSamePeakGoldenCount++; - } - else - { - mSamePeakGoldenCount = 0; - } - - // - if (isSameValeGolden) - { - mSameValeGoldenCount++; - } - else - { - mSameValeGoldenCount = 0; - } - - // - // SAR ... - - // - bool isSarBullish = sarStateBuffer[pIndex] > 0; - bool isPSarBullish = sarStateBuffer[ppIndex] > 0; - - // - bool isSarBearish = sarStateBuffer[pIndex] < 0; - bool isPSarBearish = sarStateBuffer[ppIndex] < 0; - - // - bool isSarSwitchedToBullish = - isSarBullish && - !isPSarBullish; - - // - bool isSarSwitchedToBearish = - isSarBearish && - !isPSarBearish; - - // - // HKS ... - - // - bool isHKSBullish = hkSBarCloseBuffer[pIndex] > hkSBarOpenBuffer[pIndex]; - bool isPHKSBullish = hkSBarCloseBuffer[ppIndex] > hkSBarOpenBuffer[ppIndex]; - - // - bool isHKSBearish = hkSBarCloseBuffer[pIndex] < hkSBarOpenBuffer[pIndex]; - bool isPHKSBearish = hkSBarCloseBuffer[ppIndex] < hkSBarOpenBuffer[ppIndex]; - - // - bool isHKSSwitchedToBullish = - isHKSBullish && - !isPHKSBullish; - - // - bool isHKSSwitchedToBearish = - isHKSBearish && - !isPHKSBearish; - - // - // SB ... - - // - bool isSBullish = sBarCloseBuffer[pIndex] > sBarOpenBuffer[pIndex]; - bool isPSBullish = sBarCloseBuffer[ppIndex] > sBarOpenBuffer[ppIndex]; - - // - bool isSBearish = sBarCloseBuffer[pIndex] < sBarOpenBuffer[pIndex]; - bool isPSBearish = sBarCloseBuffer[ppIndex] < sBarOpenBuffer[ppIndex]; - - // - bool isSSwitchedToBullish = - isSBullish && - !isPSBullish; - - // - bool isSSwitchedToBearish = - isSBearish && - !isPSBearish; - - // - // KI ... - - // - bool isKIBullish = kiStateBuffer[pIndex] > 0; - bool isPKIBullish = kiStateBuffer[ppIndex] > 0; - - // - bool isKIBearish = kiStateBuffer[pIndex] < 0; - bool isPKIBearish = kiStateBuffer[ppIndex] < 0; - - // - bool isKISwitchedToBullish = - isKIBullish && - !isPKIBullish; - - // - bool isKISwitchedToBearish = - isKIBearish && - !isPKIBearish; - - // - bool isKIBullishBreaked = - iPBar.IsBreaked( - kiBuffer[pIndex], - X_DIRECTION_BULLISH, - X_FIBO_LEVEL_500, - X_BOUNDARY_PRICE_UP_DOWN // - ); - - // - bool isKIBearishBreaked = - iPBar.IsBreaked( - kiBuffer[pIndex], - X_DIRECTION_BEARISH, - X_FIBO_LEVEL_500, - X_BOUNDARY_PRICE_UP_DOWN // - ); - - // - bool isKISame = kiBuffer[pIndex] == kiBuffer[ppIndex]; - bool isKIBullishSame = - isKISame && - isKIBullish; - bool isKIBearishSame = - isKISame && - isKIBearish; - - // - if (isKISame) - { - mSameKICount++; - } - else - { - mSameKICount = 0; - } - - // - if (isKIBullishSame) - { - mSameKIBullishCount++; - } - else - { - mSameKIBullishCount = 0; - } - - // - if (isKIBearishSame) - { - mSameKIBearishCount++; - } - else - { - mSameKIBearishCount = 0; - } - - // - // Validating Trigger Bar based on Conditions ... - if (isTriggerBar) - { - // - // TODO: Remove this if required ... - isTriggerBar = false; - isBullishTriggerBar = false; - isBearishTriggerBar = false; - } - - // - // Detecting Signal ... - - // - // Bullish ... - isBullish = - // - // Conditions Validation ... - isKIBullishBreaked - // isSSwitchedToBullish - // isKISwitchedToBullish - // isSarSwitchedToBullish - // isHKSSwitchedToBullish - // - // Bar Validation ... - // - ; - - // - // Bearish ... - isBearish = - // - // Conditions Validation ... - isKIBearishBreaked - // isSSwitchedToBearish - // isKISwitchedToBearish - // isSarSwitchedToBearish - // isHKSSwitchedToBearish - // - // Bar Validation ... - // - ; - - // - // Summarizing Signal ... - hasSignal = - isBullish || - isBearish; - - // - // Draw Requirements ... - - // - // Draw Trigger Bar ... - if (isTriggerBar) - { - // - int triggerBullishArrowCode = 225; - int triggerBearishArrowCode = 226; - - // - color triggerBarBullishColor = clrLime; - color triggerBarBearishColor = clrRed; - - // - ENUM_ARROW_ANCHOR triggerBullishAnchor = ANCHOR_TOP; - ENUM_ARROW_ANCHOR triggerBearishAnchor = ANCHOR_BOTTOM; - - // - int arrowWidth = 3; - int arrowCode = - isBullishTriggerBar - ? triggerBullishArrowCode - : triggerBearishArrowCode; - ENUM_X_PRICE arrowPriceType = - isBullishTriggerBar - ? X_PRICE_LOW - : X_PRICE_HIGH; - color arrowColor = - isBullishTriggerBar - ? triggerBarBullishColor - : triggerBarBearishColor; - ENUM_ARROW_ANCHOR arrowAnchor = - isBullishTriggerBar - ? triggerBullishAnchor - : triggerBearishAnchor; - - // - XCBarArrowObject *iObj; - has = mDrawer.CreateBarArrow( - iBar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - namePrefix // - ); - if (has) - { - mObjects.Add(iObj); - } - - // - // Converts to Box ... - XBoxZone iBox; - iBox.type = "XTRB"; - iBox.to = iBar.time; - iBox.symbol = _Symbol; - iBox.period = _Period; - iBox.lower = iPBar.low; - iBox.from = iPBar.time; - iBox.upper = iPBar.high; - iBox.dir = - isBullishTriggerBar - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - if (iBox.IsValid()) - { - // - // XCBoxObject *iObj; - // has = mDrawer.DrawBox( - // iBox, - // iObj // - // ); - // if (has) - // { - // mObjects.Add(iObj); - // } - - // - XSignal iSignal; - double iRewardRatios[] = { - 1, - 1.5, - 2 // - }; - has = ToSignal( - iBox, - iSignal, - iRewardRatios, - 0 // Additional SL ... - ); - if (has) - { - // - XCSignalObject *iObj; - has = mDrawer.DrawSignal( - iSignal, - iObj, - 4 // - ); - if (has) - { - mObjects.Add(iObj); - } - } - } - - // - } - - // - // Draw Signal ... - if (hasSignal) - { - // - int bullishArrowCode = 225; - int bearishArrowCode = 226; - - // - color bullishColor = clrLime; - color bearishColor = clrRed; - - // - ENUM_ARROW_ANCHOR bullishAnchor = ANCHOR_TOP; - ENUM_ARROW_ANCHOR bearishAnchor = ANCHOR_BOTTOM; - - // - int arrowWidth = 3; - int arrowCode = - isBullish - ? bullishArrowCode - : bearishArrowCode; - ENUM_X_PRICE arrowPriceType = - isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - color arrowColor = - isBullish - ? bullishColor - : bearishColor; - ENUM_ARROW_ANCHOR arrowAnchor = - isBullish - ? bullishAnchor - : bearishAnchor; - - // - XCBarArrowObject *iObj; - has = mDrawer.CreateBarArrow( - iBar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - namePrefix // - ); - if (has) - { - mObjects.Add(iObj); - } - - // - // Converts to Box ... - XBoxZone iBox; - iBox.type = "XSG"; - iBox.to = iBar.time; - iBox.symbol = _Symbol; - iBox.period = _Period; - iBox.lower = iPBar.low; - iBox.from = iPBar.time; - iBox.upper = iPBar.high; - iBox.dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - if (iBox.IsValid()) - { - // - XSignal iSignal; - double iRewardRatios[] = { - 1, - 1.5, - 2 // - }; - has = ToSignal( - iBox, - iSignal, - iRewardRatios, - 0 // Additional SL ... - ); - if (has) - { - // - XCSignalObject *iObj; - has = mDrawer.DrawSignal( - iSignal, - iObj, - 4 // - ); - if (has) - { - mObjects.Add(iObj); - } - } - } - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - iPBar.Clean(); -} - -//////////////////////////////////////////////////////////////////// - -/** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( bool ) - */ -bool AnalysePVPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractPVPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength, // Max Allowed Loopback ... - validationLength // Validation Length ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XPV", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; -} - -/** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( bool ) - */ -bool AnalyseMAPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractMAPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength, // Max Allowed Loopback ... - validationLength // Validation Length ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XMA", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; -} - -/** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( bool ) - */ -bool AnalyseSARPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractSARPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength // Max Allowed Loopback ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XSAR", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; -} - -/** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( bool ) - */ -bool AnalyseZigZagPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractZigZagPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength // Max Allowed Loopback ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XZG", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; -} - -/** - * Analyse Market based on Specified Bar ... - * - * @param structure: XFIMAMarketStructure, reference to holds result ... - * @param config: XFIMAMarketStructureConfig, reference to Configure Detector ... - * @param barIndex: int, Bar Index ... - */ -void AnalyseMarket( - XFIMAMarketStructure &structure, - XFIMAMarketStructureConfig &config, - int barIndex = 0 // -) -{ - // - // Prepare ... - structure.Clean(); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - bool has = false; - - // - has = structure.bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - structure.Clean(); - return; - } - - // - // Reading Bar Patterns ... - XOHCL iBar; - XPatternAnalysis iPatternAnalysis; - for (int i = barIndex; i < barIndex + config.loopback; i++) - { - // - // Cleanup ... - iBar.Clean(); - iPatternAnalysis.Clean(); - - // - // Initialize Indexed Bar ... - // - has = structure.bar.BarAt(i, iBar); - if (!has) - { - break; - } - - // - // Analyse Indexed Bar ... - has = AnalyseBarPatterns(iBar, iPatternAnalysis, config.barsAnalysisConfig); - if (has) - { - // - AddRef( - iPatternAnalysis, - structure.barsAnalysis // - ); - - // - if (i == barIndex) - { - structure.barAnalysis = iPatternAnalysis; - } - } - - // - // Check Satisfied ... - has = ArraySize(structure.barsAnalysis) >= config.requiredPivots; - if (has) - { - break; - } - } - - // - // Handle Pivot Analysis ... - - // - // XPV ... - if (config.analysePVPivots) - { - // - // Reading Pivots ... - has = AnalysePVPivots( - structure.pvAnalysis, - barIndex, - config.requiredPivots, - config.loopback, - config.pvPivotsValidationLength // - ); - if (!has) - { - structure.pvAnalysis.Clean(); - } - } - - // - // XZG ... - if (config.analyseZGPivots) - { - // - // Reading Pivots ... - has = AnalyseZigZagPivots( - structure.zgAnalysis, - barIndex, - config.requiredPivots, - config.loopback // - ); - if (!has) - { - structure.zgAnalysis.Clean(); - } - } - - // - // Cleanup ... - iBar.Clean(); - iPatternAnalysis.Clean(); -} - -//////////////////////////////////////////////////////////////////// - -/** - * Check Specified Bar has MA Cross or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * - * @return ( bool ) - */ -bool HasMACross( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - double validCrossDiffMultiplier = 1 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast[]; - int fastCount = CopyMAFast(barIndex, 2, fast); - - // - double slow[]; - int slowCount = CopyMASlow(barIndex, 2, slow); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - int count = MathMin(fastCount, slowCount); - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(fast[0]) && - NotEmptyZero(fast[1]) && - NotEmptyZero(slow[0]) && - NotEmptyZero(slow[1]); - - // - isBullish = - notEmpty && - fast[0] > slow[0] && - fast[1] < slow[1]; - - // - isBearish = - notEmpty && - fast[0] < slow[0] && - fast[1] > slow[1]; - - // - result = - isBullish || - isBearish; - - // - // Validate Direction Change ... - if (result && - validCrossDiffMultiplier > 0) - { - // - double _points = GetPoints(GetSymbol()); - double diff = MathAbs(fast[0] - slow[0]); - - // - result = diff >= (validCrossDiffMultiplier * _points); - } - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - - // - return result; -} - -/** - * Check Specified Bar Price is In Boundary or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsInBoundary( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Bar ... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - // Read Boundary Values ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - result = value < max && - value > min; - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar Price is Over Boundary Min ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsOverBoundaryMin( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Boundary ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - return result; - } - - // - // Retrieve Bar .... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - result = value > min; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar Price is Under Boundary Max ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsUnderBoundaryMax( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Boundary ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - return result; - } - - // - // Retrieve Bar .... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - result = value < max; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check Boundary Fake Breaked or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param overMaxPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * @param underMinPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * - * @return ( bool ) - */ -bool IsBoundaryFakeBreaked( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - ENUM_X_PRICE overMaxPriceType = X_PRICE_NONE, - ENUM_X_PRICE underMinPriceType = X_PRICE_NONE // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(overMaxPriceType)) - { - overMaxPriceType = X_PRICE_CLOSE; - } - if (!IsXValid(underMinPriceType)) - { - underMinPriceType = X_PRICE_CLOSE; - } - - // - // Initial Bars ... - XOHCL bar; - XOHCL pBar; - double min; - double max; - double pMin; - double pMax; - double boundaryValues[]; - result = - bar.Init( - mSymbol, - mPeriod, - barIndex // - ) && - bar.GetPreviousBar(pBar) && - GetBoundaryValues(min, max, barIndex) && - GetBoundaryValues(pMin, pMax, barIndex + 1) && - FillBoundaryValues(boundaryValues, barIndex) > 0; - - // - bool isBullish = - result && - pBar.IsBearish() && - bar.IsBullish() && - pBar.GetPrice(underMinPriceType) < pMin && - bar.GetPrice(underMinPriceType) > min && - (bar.GetPrice(underMinPriceType) > FindLesserThan(max, boundaryValues) || - bar.GetPrice(underMinPriceType) > FindBiggerThan(min + ((max - min) / 2), boundaryValues)); - - // - bool isBearish = - result && - pBar.IsBullish() && - bar.IsBearish() && - pBar.GetPrice(overMaxPriceType) > pMax && - bar.GetPrice(overMaxPriceType) < max && - (bar.GetPrice(overMaxPriceType) < FindBiggerThan(min, boundaryValues) || - bar.GetPrice(overMaxPriceType) < FindLesserThan(min + ((max - min) / 2), boundaryValues)); - - // - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Cleanup ... - bar.Clean(); - pBar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar's Price in Hot Place or Not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param overMaxPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * @param underMinPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * - * @return ( bool ) - */ -bool IsInHotPlace( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - ENUM_X_PRICE overMaxPriceType = X_PRICE_NONE, - ENUM_X_PRICE underMinPriceType = X_PRICE_NONE // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(overMaxPriceType)) - { - overMaxPriceType = X_PRICE_LOW; - } - if (!IsXValid(underMinPriceType)) - { - underMinPriceType = X_PRICE_HIGH; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Initialize Bar ... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double overMaxPrice = bar.GetPrice(overMaxPriceType); - double underMinPrice = bar.GetPrice(underMinPriceType); - - // - // Reading Boundary Value ... - double min; - double max; - result = GetBoundaryValues( - min, - max, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - bool isBullish = underMinPrice < min; - bool isBearish = overMaxPrice > max; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar price Crossed in Boundary or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold Crossed in Dir ... - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsCrossedInBoundary( - ENUM_X_DIRECTION &dir, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - int pBarIndex = barIndex + 1; - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Check PrevBar Is in Hot Place ... - result = IsInHotPlace( - dir, - pBarIndex, - X_PRICE_LOW, - X_PRICE_HIGH // - ); - if (!result) - { - // - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Current Bar must Into Boundary ... - result = IsInBoundary(priceType, barIndex); - if (!result) - { - dir = X_DIRECTION_NONE; - } - - // - result = HasDirection(dir); - - // - return result; -} - -/** - * Check Specified Bar price Crossed out Boundary or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold Crossed in Dir ... - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsCrossedOutBoundary( - ENUM_X_DIRECTION &dir, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - int pBarIndex = barIndex + 1; - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Prev Bar Must in Boundary ... - bool isBullish = IsInBoundary(X_PRICE_LOW, pBarIndex); - bool isBearish = IsInBoundary(X_PRICE_HIGH, pBarIndex); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - // Current Bar must Out of Boundary ... - - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - - // - isBullish = - result && - isBullish && - bar.IsBullish() && - !IsInBoundary(priceType, barIndex); - - // - isBearish = - result && - isBearish && - bar.IsBearish() && - !IsInBoundary(priceType, barIndex); - - // - result = isBullish || - isBearish; - if (!result) - { - // - bar.Clean(); - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar has Boundary Trend or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool HasBoundaryTrend( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - result = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower); - if (!result) - { - return result; - } - - // - bool isBullish = - fast > hkBandLower && - slow > hkBandLower && - maBandUpper > hkBandLower && - maBandLower > hkBandLower && - pbBandUpper > hkBandLower && - pbBandLower > hkBandLower; - bool isBearish = - fast < hkBandUpper && - slow < hkBandUpper && - maBandUpper < hkBandUpper && - maBandLower < hkBandUpper && - pbBandUpper < hkBandUpper && - pbBandLower < hkBandUpper; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - return result; -} - -/** - * Check Specified Bar has Boundary Trend Switched or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool HasBoundarySwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - result = HasBoundaryTrend( - dir, - barIndex // - ); - if (!result) - { - return result; - } - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - result = HasBoundaryTrend( - dir, - barIndex + 1 // - ); - if (!result) - { - return result; - } - bool isPBullish = IsXBullish(dir); - bool isPBearish = IsXBearish(dir); - - // - bool isSwitchedToBullish = - isBullish && !isPBullish; - bool isSwitchedToBearish = - isBearish && !isPBearish; - result = isSwitchedToBullish || - isSwitchedToBearish; - if (result) - { - // - dir = isSwitchedToBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - return result; -} - -/** - * Check Fibo Section is Changed or not ... - * - * @param dir: reference to hold section change direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool IsFiboSectionChanged( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = false; - bool isBearish = false; - - // - // Reading Values ... - - // - double iFiboUpper = GetFiboUpper(barIndex); - double pFiboUpper = GetFiboUpper(barIndex + 1); - - // - double iFiboMiddle = GetFiboMiddle(barIndex); - double pFiboMiddle = GetFiboMiddle(barIndex + 1); - - // - double iFiboLower = GetFiboLower(barIndex); - double pFiboLower = GetFiboLower(barIndex + 1); - - // - isBullish = iFiboLower >= pFiboMiddle && - iFiboMiddle >= pFiboUpper; - isBearish = iFiboUpper <= pFiboMiddle && - iFiboMiddle <= pFiboLower; - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (!result) - { - return result; - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - return result; -} - -/** - * Check for Fibo Push Exists or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold result ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, Validation Length ... - * - * @return ( bool ) - */ -bool HasFiboPush( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 3); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL iBar; - bool isBullish = false; - bool isBearish = false; - - // - double iFiboUpper = EMPTY_VALUE; - double pFiboUpper = EMPTY_VALUE; - - // - double iFiboMiddle = EMPTY_VALUE; - double pFiboMiddle = EMPTY_VALUE; - - // - double iFiboLower = EMPTY_VALUE; - double pFiboLower = EMPTY_VALUE; - - // - // Check Zone Validation ... - int start = barIndex; - int end = start + validationLength; - for (int i = start; i < end; i++) - { - // - // Reading Values ... - - // - iFiboUpper = GetFiboUpper(i); - pFiboUpper = GetFiboUpper(i + 1); - - // - iFiboMiddle = GetFiboMiddle(i); - pFiboMiddle = GetFiboMiddle(i + 1); - - // - iFiboLower = GetFiboLower(i); - pFiboLower = GetFiboLower(i + 1); - - // - result = iFiboUpper == pFiboUpper; - if (!result) - { - break; - } - } - - // - if (result) - { - // - result = iBar.Init( - mSymbol, - mPeriod, - barIndex // - ); - - // - if (result) - { - // - iFiboUpper = GetFiboUpper(barIndex); - iFiboMiddle = GetFiboMiddle(barIndex); - iFiboLower = GetFiboLower(barIndex); - - // - isBullish = iBar.IsBullish() && - iBar.close > iFiboLower && - iBar.low < iFiboLower; - isBearish = iBar.IsBearish() && - iBar.close < iFiboUpper && - iBar.high > iFiboUpper; - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; -} - -/** - * Check Has Higher Low Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagHigherLow( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot vales[]; - count = ExtractPivots( - vales, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - vales[0].value > vales[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open > vales[0].value && - bar.close > vales[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; -} - -/** - * Check Has Lower Low Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagLowerLow( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot vales[]; - count = ExtractPivots( - vales, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - vales[0].value < vales[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open < vales[0].value && - bar.close < vales[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; -} - -/** - * Check Has Higher High Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagHigherHigh( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot peaks[]; - count = ExtractPivots( - peaks, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - peaks[0].value > peaks[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open > peaks[0].value && - bar.close > peaks[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; -} - -/** - * Check Has Lower High Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagLowerHigh( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot peaks[]; - count = ExtractPivots( - peaks, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - peaks[0].value < peaks[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open < peaks[0].value && - bar.close < peaks[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; -} - -// -// SAR ... - -/** - * Check Specified Bar has SAR Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool HasSARSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double sars[]; - int count = CopySarState(barIndex, 2, sars); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - isBullish = - sars[0] >= 1 && - sars[1] <= -1; - - // - isBearish = - sars[0] <= -1 && - sars[1] >= 1; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(sars); - - // - return result; -} - -// -// PV ... - -// -// HK ... - -/** - * Check Specified Bar has HK Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool HasHKSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - double open[]; - int openCount = CopyHKOpen(barIndex, 2, open); - - // - double close[]; - int closeCount = CopyHKClose(barIndex, 2, close); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - int count = MathMin(openCount, closeCount); - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - - // - isBullish = - notEmpty && - open[0] < close[0] && - open[1] > close[1]; - - // - isBearish = - notEmpty && - open[0] > close[0] && - open[1] < close[1]; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - - // - return result; -} - -/** - * Check Specified Bar has HK Band Based Trend or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to holds trend direction, if exists ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, validation of trend ... - * - * @return ( bool ) - */ -bool HasHKBasedTrend( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 1); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - // Define Requirements ... - XOHCL iBar; - double hkUpper; - double hkLower; - bool has = false; - int bullishCount = 0; - int bearishCount = 0; - bool isBullish = false; - bool isBearish = false; - - // - // Count Bullish/Bearish Directions ... - int start = barIndex + 1; - int end = start + validationLength; - for (int i = start; i < end; i++) - { - // - // Reading Requirements ... - - // - // Read Indexed Bar ... - iBar.Clean(); - result = iBar.Init( - mSymbol, - mPeriod, - i // - ); - if (!result) - { - break; - } - - // - // Reading Values ... - hkUpper = GetHKBandUpper(i); - hkLower = GetHKBandLower(i); - result = NotEmptyZero(hkUpper) && - NotEmptyZero(hkLower); - if (!result) - { - return result; - } - - // - // Check Trend ... - - // - // Bullish ... - isBullish = iBar.low > hkLower; - if (isBullish) - { - bullishCount++; - } - - // - // Bearish ... - isBearish = iBar.high < hkUpper; - if (isBearish) - { - bearishCount++; - } - - // - iBar.Clean(); - - // - } - - // - // Validate Results ... - isBullish = - bullishCount >= validationLength; - isBearish = - bearishCount >= validationLength; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - - // - // Setting Direction if Has Trend ... - if (result) - { - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup ... - iBar.Clean(); - - // - return result; -} - -/** - * Check Specified Bar has HK Band Based Trend Switch or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to holds trend direction, if exists ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, validation of trend ... - * - * @return ( bool ) - */ -bool IsHKBasedTrendSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // -) -{ - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 1); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - bool hasTrend = HasHKBasedTrend( - dir, - barIndex, - validationLength // - ); - bool isBullish = hasTrend && - IsXBullish(dir); - bool isBearish = hasTrend && - IsXBearish(dir); - - // - bool hasPTrend = HasHKBasedTrend( - dir, - barIndex + 1, - validationLength // - ); - bool isPBullish = hasPTrend && - IsXBullish(dir); - bool isPBearish = hasPTrend && - IsXBearish(dir); - - // - dir = X_DIRECTION_NONE; - - // - // Checking Result ... - isBullish = isBullish && !isPBullish; - isBearish = isBearish && !isPBearish; - - // - result = - (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup ... - - // - return result; -} - -/** - * Check if Price Over HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsOverHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandUpper(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price > value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check if Price Over HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsOverHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandLower(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price > value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check if Price Under HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsUnderHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandUpper(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price < value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check if Price Under HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsUnderHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandLower(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price < value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; -} - -/** - * Check Price Switched Over HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsSwitchedOverHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsOverHKBandUpper(priceType, barIndex); - bool isPBarPassed = !IsOverHKBandUpper(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; -} - -/** - * Check Price Switched Under HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsSwitchedUnderHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsUnderHKBandUpper(priceType, barIndex); - bool isPBarPassed = !IsUnderHKBandUpper(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; -} - -/** - * Check Price Switched Over HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsSwitchedOverHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsOverHKBandLower(priceType, barIndex); - bool isPBarPassed = !IsOverHKBandLower(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; -} - -/** - * Check Price Switched Under HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ -bool IsSwitchedUnderHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsUnderHKBandLower(priceType, barIndex); - bool isPBarPassed = !IsUnderHKBandLower(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastOverHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsOverHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastUnderHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsUnderHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastOverHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsOverHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastUnderHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsUnderHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastSwitchedOverHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedOverHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastSwitchedUnderHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedUnderHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastSwitchedOverHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedOverHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -/** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool FindLastSwitchedUnderHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedUnderHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; -} - -// -// ZigZag Pivots With Liquidity ... - -/** - * Check ZigZag has Lower Low by Liquidity or Not ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagLowerLowByLiquidity( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - XOHCL bar; - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot selected[]; - count = ExtractPivots( - selected, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 3; - if (!result) - { - // - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - // - // Do Calculations ... - result = - // - // Check Pivot ... - selected[0].value < selected[1].value && - // - // Check Liquidity ... - selected[1].value > selected[2].value && - // - // Check Bar Place ... - (!forceBarValidation - ? true - : bar.open > selected[0].value && - bar.close > selected[0].value); - - // - // Cleanup ... - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; -} - -/** - * Check ZigZag has Higher High by Liquidity or Not ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ -bool HasZigZagHigherHighByLiquidity( - int barIndex = 0, - bool forceBarValidation = false // -) -{ - // - bool result = false; - - // - // Normalize ... - XOHCL bar; - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot selected[]; - count = ExtractPivots( - selected, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 3; - if (!result) - { - // - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - // - // Do Calculations ... - result = - // - // Check Pivot ... - selected[0].value > selected[1].value && - // - // Check Liquidity ... - selected[1].value < selected[2].value && - // - // Check Bar Place ... - (!forceBarValidation - ? true - : bar.open < selected[0].value && - bar.close < selected[0].value); - - // - // Cleanup ... - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; -} - -// -// Extractions ... - -/** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( int ) - */ -int ExtractPVPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - bool lookupPeaks = true; - bool lookupVales = true; - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - int samePeaksCount = 0; - int sameValesCount = 0; - double tmpPeaksBuffer[]; - double tmpValesBuffer[]; - string symbol = GetSymbol(); - double iPValue = EMPTY_VALUE; - double iVValue = EMPTY_VALUE; - double pPValue = EMPTY_VALUE; - double pVValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Detecting ... - - // - // Peak ... - if (lookupPeaks) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_PEAK_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpPeaksBuffer // Buffer ... - ); - ArraySetAsSeries(tmpPeaksBuffer, true); - - // - // Reading Values ... - iPValue = tmpPeaksBuffer[0]; - pPValue = tmpPeaksBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iPValue)) - { - // - // Check New Peak ... - has = - !NotEmptyZero(pPValue) - ? true - : iPValue != pPValue; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - iPValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : samePeaksCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iPValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_PV); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - samePeaksCount = 0; - } - else if (iPValue == pPValue) - { - samePeaksCount++; - } - } - } - - // - // Vale ... - if (lookupVales) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_VALE_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpValesBuffer // Buffer ... - ); - ArraySetAsSeries(tmpValesBuffer, true); - - // - // Reading Values ... - iVValue = tmpValesBuffer[0]; - pVValue = tmpValesBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iVValue)) - { - // - // Check New Vale ... - has = - !NotEmptyZero(pVValue) - ? true - : iVValue != pVValue; - if (has) - { - // - // Calculate and Validate Type ... - // Vales Only Valid when Confirmed by Bar Low ... - iType = - iVValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : sameValesCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iVValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_PV); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - sameValesCount = 0; - } - else if (iVValue == pVValue) - { - sameValesCount++; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - return result; -} - -/** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ -int ExtractMAPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - double validCrossDiffMultiplier = 1, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double fast[]; - double slow[]; - XPivot iPivot; - int count = 0; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - double iFValue = EMPTY_VALUE; - double pFValue = EMPTY_VALUE; - double iSValue = EMPTY_VALUE; - double pSValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - int fastCount = CopyMAFast(idx, 2, fast); - int slowCount = CopyMASlow(idx, 2, slow); - count = MathMin(fastCount, slowCount); - has = IsValidSize(count); - - // - // Reading Values ... - - // - iFValue = fast[0]; - pFValue = fast[1]; - - // - iSValue = slow[0]; - pSValue = slow[1]; - - // - // Validate Value ... - has = - HasMACross( - iDir, - idx, - validCrossDiffMultiplier // - ) && - NotEmptyZero(iFValue) && - NotEmptyZero(iSValue) && - NotEmptyZero(pFValue) && - NotEmptyZero(pSValue); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(iFValue, iSValue) - : MathMin(iFValue, iSValue); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_MA_CROSS); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - return result; -} - -/** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ -int ExtractHKPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double open[]; - XPivot iPivot; - int count = 0; - double close[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - int openCount = CopyHKOpen(idx, 2, open); - int closeCount = CopyHKClose(idx, 2, close); - count = MathMin(openCount, closeCount); - has = IsValidSize(count); - - // - // Validate Value ... - has = - HasHKSwitch( - iDir, - idx // - ) && - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_HK); - - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(open[0], close[0]) - : MathMin(open[0], close[0]); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - return result; -} - -/** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ -int ExtractSARPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XOHCL pBar; - XPivot iPivot; - bool has = false; - double tmpSarBuffer[]; - int idx = barIndex - 1; - string symbol = GetSymbol(); - double iValue = EMPTY_VALUE; - double pValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - has = - has && - iBar.GetPreviousBar(pBar); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_SAR_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpSarBuffer // Buffer ... - ); - ArraySetAsSeries(tmpSarBuffer, true); - - // - // Reading Values ... - iValue = tmpSarBuffer[0]; - pValue = tmpSarBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iValue)) - { - // - // Check Sar Direction Changed ... - isSwitchedToBullish = iValue < iBar.low && - pValue > pBar.high; - isSwitchedToBearish = iValue > iBar.high && - pValue < pBar.low; - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_SAR_SWITCH); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - return result; -} - -/** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ -int ExtractZigZagPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - double tmpZigZagBuffer[]; - double iValue = EMPTY_VALUE; - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_ZIGZAG_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 1, // Number of Requirements ... - tmpZigZagBuffer // Buffer ... - ); - ArraySetAsSeries(tmpZigZagBuffer, true); - - // - // Read and Validate Value ... - iValue = tmpZigZagBuffer[0]; - has = NotEmptyZero(iValue); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Type ... - iType = - iValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : iValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Dir ... - iDir = - IsXVale(iType) - ? X_DIRECTION_BULLISH - : IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(iDir); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_ZIGZAG); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - return result; -} - -/** - * Extract Validated Zones ... - * - * @param zones: XBoxZone, collection reference to holds results ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFZones: int, required Number of Zones ... - * @param breakValidLength: int, Breake Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * @param shadowMultiplier: double a Shadow Multiplier for Validation ... - * @param validationStrength: double, Minimum Strngth Multiplier in Point to Validate ... - * @param validationLength: int, Validation Length of Zones ... - * @param maxAllowedLoopbackLength: int, max Allowed Loopback Length ... - * - * @return ( int ) - */ -int ExtractHKZones( - XBoxZone &zones[], - int barIndex = 0, - int requiredNumberOFZones = 50, - int breakValidLength = 3, - bool validateFakeBreakes = true, - double shadowMultiplier = 3, - double validationStrength = 1, - int validationLength = 21, - int maxAllowedLoopbackLength = 1500 // -) -{ - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(zones); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 7); - shadowMultiplier = NormalizeDouble(shadowMultiplier, 1); - validationStrength = NormalizeDouble(validationStrength, 1); - requiredNumberOFZones = NormalizeInt(requiredNumberOFZones, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 100); - - // - // Reading Values ... - - // - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - double minAllowedStrength = (validationStrength * GetPoints(symbol)); - - // - int count = 0; - XBoxZone zone; - bool has = false; - int start = barIndex; - bool isBullish = false; - bool isBearish = false; - double up = EMPTY_VALUE; - double low = EMPTY_VALUE; - double open = EMPTY_VALUE; - double high = EMPTY_VALUE; - double down = EMPTY_VALUE; - double body = EMPTY_VALUE; - double close = EMPTY_VALUE; - double range = EMPTY_VALUE; - bool lowShadowPassed = false; - bool highShadowPassed = false; - double lowShadow = EMPTY_VALUE; - double highShadow = EMPTY_VALUE; - double startHKLow = EMPTY_VALUE; - double startHKOpen = EMPTY_VALUE; - double startHKHigh = EMPTY_VALUE; - double startHKClose = EMPTY_VALUE; - ENUM_X_DIRECTION dir = X_DIRECTION_NONE; - int end = start + maxAllowedLoopbackLength; - for (int i = start; i < end; i++) - { - // - // Cleanup ... - zone.Clean(); - dir = X_DIRECTION_NONE; - - // - // Reading HK Buffesr ... - low = GetHKLow(i); - open = GetHKOpen(i); - high = GetHKHigh(i); - close = GetHKClose(i); - - // - // Initialized Start Bar ... - if (i == start) - { - // - startHKLow = low; - startHKOpen = open; - startHKHigh = high; - startHKClose = close; - } - - // - // Check Direction ... - isBullish = open < close; - isBearish = open > close; - dir = - (isBullish && !isBearish) - ? X_DIRECTION_BULLISH - : (isBearish && !isBullish) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(dir); - if (!has) - { - continue; - } - - // - // Calculate Requirements for Processing ... - up = isBullish - ? close - : open; - down = isBullish - ? open - : close; - body = MathAbs(up - down); - range = high - low; - highShadow = high - up; - lowShadow = down - low; - - // - // Detecting Shadows ... - - // - // Low Shadow ... - lowShadowPassed = lowShadow >= (shadowMultiplier * highShadow); - - // - // High Shadow ... - highShadowPassed = highShadow >= (shadowMultiplier * lowShadow); - - // - has = (lowShadowPassed && !highShadowPassed) || - (highShadowPassed && !lowShadowPassed); - if (!has) - { - continue; - } - - // - // Filling Zone ... - - // - zone.symbol = symbol; - zone.period = period; - zone.from = GetBarTime( - zone.symbol, - zone.period, - i // - ); - zone.dir = lowShadowPassed - ? X_DIRECTION_BULLISH - : highShadowPassed - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - zone.upper = - IsXBullish(zone.dir) - ? down - : IsXBearish(zone.dir) - ? high - : EMPTY_VALUE; - - // - zone.lower = - IsXBullish(zone.dir) - ? low - : IsXBearish(zone.dir) - ? up - : EMPTY_VALUE; - - // - zone.to = TimeCurrent(); - zone.type = ToXString(XFIMA_PIVOT_HK) + "_" + (IsXBullish(zone.dir) ? "Support" : IsXBearish(zone.dir) ? "Resistance" - : ""); - - // - // Validate ... - has = - zone.IsValid() && - HasDirection(zone.dir) && - NotEmptyZero(zone.upper) && - NotEmptyZero(zone.lower) && - (zone.IsBullish() - ? startHKLow > zone.upper - : startHKHigh < zone.lower) && - (zone.upper - zone.lower) >= minAllowedStrength && - ValidateHKZone(zone, validationLength, breakValidLength, validateFakeBreakes); - if (has) - { - // - AddIfNotExists( - zone, - zones // - ); - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - // Validating ... - result = ArraySize(zones); - has = IsValidSize(result) && - result >= requiredNumberOFZones; - if (has) - { - break; - } - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - return result; -} - -// -// Values Retrievers ... - -/** - * Filling Specified Bar index Boundary Values ... - * - * @param dest: double, reference collection to hold boundary Values ... - * @param barIndex: int, Specified Bar's Index ... - * @param containsFastSlow: bool, Contains XMA Fast / Slow ... - * @param containsMABand: bool, Contains XMA Boundary Upper / Lower ... - * @param containsHKBound: bool, Contains XHK Boundary Upper / Lower ... - * @param containsPBBand: bool, Contains XPB Boundary Upper / Lower ... - * @param containsFiboLevels: nool, Contains XFIBO Levels ... - * - * @return ( int ) - */ -int FillBoundaryValues( - double &dest[], - int barIndex = 0, - bool containsFastSlow = true, - bool containsMABand = true, - bool containsHKBound = true, - bool containsPBBand = true, - bool containsFiboLevels = false // -) -{ - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - // Read and Validate Values ... - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - double fiboUpper = GetFiboUpper(barIndex); - double fiboLower = GetFiboLower(barIndex); - double fiboMiddle = GetFiboMiddle(barIndex); - - // - has = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(fiboLower) && - NotEmptyZero(fiboUpper) && - NotEmptyZero(fiboMiddle) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower); - if (!has) - { - return result; - } - - // - // Fill Dest ... - - // - // XMA Fast / Slow ... - if (containsFastSlow) - { - // - Add(fast, dest); - Add(slow, dest); - } - - // - // XMA Bound ... - if (containsMABand) - { - // - Add(maBandUpper, dest); - Add(maBandLower, dest); - } - - // - // XHK Band ... - if (containsHKBound) - { - // - Add(hkBandUpper, dest); - Add(hkBandLower, dest); - } - - // - // XPB Band ... - if (containsPBBand) - { - // - Add(pbBandUpper, dest); - Add(pbBandLower, dest); - } - - // - // XFIBO Zones ... - if (containsFiboLevels) - { - // - Add(fiboLower, dest); - Add(fiboUpper, dest); - Add(fiboMiddle, dest); - } - - // - result = ArraySize(dest); - - // - return result; -} - -/** - * Retrieve Fast, Slow, MA Band Upper/Lower, HK Band Upper/Lower and PB Band Upper/Lower Min/Max ... - * - * @param min: double, minimum value ... - * @param max: double, maximum value ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool GetBoundaryValues( - double &min, - double &max, - int barIndex = 0, - bool containsFastSlow = true, - bool containsMABand = true, - bool containsHKBound = true, - bool containsPBBand = true, - bool containsFiboLevels = false // -) -{ - // - bool result = false; - - // - // Prepare ... - min = EMPTY_VALUE; - max = EMPTY_VALUE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - double fiboUpper = GetFiboUpper(barIndex); - double fiboLower = GetFiboLower(barIndex); - double fiboMiddle = GetFiboMiddle(barIndex); - - // - result = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(fiboLower) && - NotEmptyZero(fiboUpper) && - NotEmptyZero(fiboMiddle) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower); - if (!result) - { - return result; - } - - // - double values[]; - - // - if (containsFastSlow) - { - // - Add(fast, values); - Add(slow, values); - } - - // - if (containsMABand) - { - // - Add(maBandUpper, values); - Add(maBandLower, values); - } - - // - if (containsHKBound) - { - // - Add(hkBandUpper, values); - Add(hkBandLower, values); - } - - // - if (containsPBBand) - { - // - Add(pbBandUpper, values); - Add(pbBandLower, values); - } - - // - if (containsFiboLevels) - { - // - Add(fiboLower, values); - Add(fiboUpper, values); - Add(fiboMiddle, values); - } - - // - result = HasChild(values); - if (!result) - { - return result; - } - - // - min = GetMin(values); - max = GetMax(values); - - // - result = - NotEmptyZero(min) && - NotEmptyZero(max) && - min < max; - - // - return result; -} diff --git a/Documents/BKP/tmp.poi.drawer.codes.mq5 b/Documents/BKP/tmp.poi.drawer.codes.mq5 deleted file mode 100644 index 520477d6..00000000 --- a/Documents/BKP/tmp.poi.drawer.codes.mq5 +++ /dev/null @@ -1,379 +0,0 @@ - - /** - * Create Bar Object ... - * - * @param bar: XOHCL instance Reference ... - * @param object: XCOHCLObject pointer Reference .. - * @param to: Datetime ... - * - * @return ( bool ) - */ - bool CreateBar( - XOHCL &bar, - XCOHCLObject *&object, - datetime to = NULL // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - to = NormalizeTime(to); - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int width = BarWidth(); - - // - color mBullishColor = BarBullishColor(); - color mBearishColor = BarBearishColor(); - - // - bool fillBody = BarFillBody(); - bool fillHighShadow = BarFillHighShadow(); - bool fillLowShadow = BarFillLowShadow(); - - // - ENUM_LINE_STYLE bodyStyle = BarBodyStyle(); - ENUM_LINE_STYLE highShadowStyle = BarHighShadowStyle(); - ENUM_LINE_STYLE lowShadowStyle = BarLowShadowStyle(); - - // - object = new XCOHCLObject(); - result = object.Create( - chartID, - window, - bar, - to, - prefix // - ); - if (result) - { - // - // Apply Styling ... - - // - object.BodyWidth(width); - object.LowShadowWidth(width); - object.HighShadowWidth(width); - - // - object.BodyStyle(bodyStyle); - object.LowShadowStyle(lowShadowStyle); - object.HighShadowStyle(highShadowStyle); - - // - bool isBullish = bar.IsBullish(); - if (isBullish) - { - // - object.BodyColor(mBullishColor); - object.LowShadowColor(mBullishColor); - object.HighShadowColor(mBullishColor); - } - else - { - // - object.BodyColor(mBearishColor); - object.LowShadowColor(mBearishColor); - object.HighShadowColor(mBearishColor); - } - - // - object.BodyFill(fillBody); - object.HighShadowFill(fillHighShadow); - object.LowShadowFill(fillLowShadow); - } - - // - return result; - } - - /** - * Create Bar Arrow Object ... - * - * @param bar: XOHCL instance Reference ... - * @param priceType: ENUM_X_PRICE member ... - * @param arrow: int, Arrow Code ... - * @param clr: color, Arro Color ... - * @param width: int, Arrow Width ... - * @param anchor: ENUM_ARROW_ANCHOR, anchor of Arrow ... - * @param name: string, name of Arrow ... - * - * @return ( bool ) - */ - bool CreateBarArrow( - XOHCL &bar, - XCBarArrowObject *&object, - ENUM_X_PRICE priceType, - int arrow = 159, - color clr = clrYellow, - int width = 3, - ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, - string name = NULL // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - string barTag = bar.GetTag(name); - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - color mBullishColor = BarBullishColor(); - color mBearishColor = BarBearishColor(); - - // - prefix = - (IsValid(prefix) - ? prefix + "_" - : prefix) + - barTag; - - // - object = new XCBarArrowObject(); - result = object - .CreateByBar( - chartID, - prefix, - window, - arrow, - bar, - priceType // - ); - if (result) - { - // - object.ArrowColor(clr); - object.ArrowWidth(width); - } - - // - return result; - } - - /** - * Create Specific Box on Chart ... - * - * @param upper: Double ... - * @param lower: Double ... - * @param from: Datetime ... - * @param to: Datetime ... - * @param clr: Color ... - * @param width: Integer ... - * @param fill: Boolean ... - * @param style: ENUM_LINE_STYLE member ... - * - * @return ( bool ) - */ - bool CreateBox( - XCBoxObject *&object, - string name, - double upper, - double lower, - datetime from, - datetime to, - datetime at, - color clr = clrYellowGreen, - int width = 1, - bool fill = false, - ENUM_LINE_STYLE style = STYLE_SOLID // - ) - { - // - bool result = false; - - // - object = NULL; - - // - to = NormalizeTime(to); - - // - string dateStr = ToFormatString(from) + "|" + ToFormatString(to); - string dateMD5 = ToMD5(dateStr); - if (!IsValid(name)) - { - // - name = "XBox_" + - ToXString(upper) + "_" + - ToXString(lower) + "_" + - dateMD5; - } - - // - result = - upper > 0 && - lower > 0 && - to > from && - IsValid(to) && - IsValid(name) && - IsValid(from) && - upper > lower; - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCBoxObject(); - result = object.Create( - chartID, - window, - name, - upper, - lower, - from, - to, - at, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.BoxColor(clr); - object.BoxFill(fill); - object.BoxWidth(width); - object.BoxStyle(style); - - // - return result; - } - - - /** - * Create Specific Box on Chart ... - * - * @param box: XBoxZone instance Reference ... - * @param clr: Color ... - * @param width: Integer ... - * @param fill: Boolean ... - * @param style: ENUM_LINE_STYLE member ... - * - * @return ( bool ) - */ - bool CreateBox( - XBoxZone &box, - XCBoxObject *&object, - color clr = clrYellowGreen, - int width = 1, - bool fill = false, - ENUM_LINE_STYLE style = STYLE_SOLID // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - string name = box.GetTag(); - - // - result = CreateBox( - object, - name, - box.upper, - box.lower, - box.from, - box.to, - box.at, - clr, - width, - fill, - style // - ); - - // - return result; - } - - // - // Testing Draws ... - - // - XFIMAMarketStructure pivots[]; - - // - XPivot pvPivots[]; - XPivot hkPivots[]; - XPivot maPivots[]; - XPivot zgPivots[]; - XPivot sarPivots[]; - - // - poiDetector.CollectZGPivots(zgPivots); - poiDetector.CollectMAPivots(maPivots); - poiDetector.CollectHKPivots(hkPivots); - poiDetector.CollectPVPivots(pvPivots); - poiDetector.CollectSARPivots(sarPivots); - - // - // Merging All Pivots ... - Copy(pvPivots, pivots, false); - Copy(zgPivots, pivots, false); - Copy(maPivots, pivots, false); - Copy(hkPivots, pivots, false); - Copy(sarPivots, pivots, false); - - // - if (HasChild(pivots)) - { - poiDrawer.DrawPivots(pivots, iDrawConfig); - } - - // - // Cleanup ... - XClean(pivots); - XClean(pvPivots); - XClean(hkPivots); - XClean(maPivots); - XClean(zgPivots); - XClean(sarPivots); diff --git a/Documents/BKP/tmp.poi.mq5 b/Documents/BKP/tmp.poi.mq5 deleted file mode 100644 index 303dab0c..00000000 --- a/Documents/BKP/tmp.poi.mq5 +++ /dev/null @@ -1,7182 +0,0 @@ -// -// All Available POI(s) ... -enum ENUM_XPOIS -{ - // - X_POI_NONE, - // - X_POI_TICKS_ZONES, // Ticks Zone ... - // - // Trading Day ... - X_POI_TRADING_DAY, // Trading Day ... - // - // Market Session ... - X_POI_MARKET_SESSION, // Market Session ... - // - // Momentum Bar ... - X_POI_MOMENTUM_BAR, // Momentum Bar ... - // - // Rejection Bar ... - X_POI_REJECTION_BAR, // Rejection Bar ... - // - // Swings ... - X_POI_SWING_HIGH, // Simple Swing High ... - X_POI_SWING_LOW, // Simple Swing Low ... - // - // Support nad Resistance ... - X_POI_SUPPORT_ZONE, // Support Zone ... - X_POI_RESISTANCE_ZONE, // Resistance Zone ... - // - // Supply and Demand Zones ... - X_POI_SUPPLY_ZONE, // Supply Zone ... - X_POI_DEMAND_ZONE, // Demand Zone ... - // - // Order Blocks ... - X_POI_BULLISH_ORDERBLOCK, // Bullish Order Block ... - X_POI_BEARISH_ORDERBLOCK, // Bearish Order Block ... - // - // Fair Value Gaps ... - X_POI_BULLISH_FVG, // Bullish Order Block ... - X_POI_BEARISH_FVG, // Bearish Order Block ... - // - X_BULLISH_CONSOLIDATION_ZONE, - X_BEARISH_CONSOLIDATION_ZONE, - // - X_BULLISH_SHARP, - X_BEARISH_SHARP, - // - X_BULLISH_SPIKE, - X_BEARISH_SPIKE, - // - X_BULLISH_PULLBACK, - X_BEARISH_PULLBACK, -}; - -// -// Event Types ... -enum ENUM_XPOI_EVENTS -{ - // - X_POI_EVENT_NONE, - // - // Trading Days ... - X_TRADE_DAY_FIRST_BAR, // Trading Day First Bar ... - X_TRADE_DAY_LAST_BAR, // Trading Day Last Bar ... - // - // Session ... - X_SESSION_FIRST_BAR, // Session First Bar ... - X_SESSION_LAST_BAR, // Session Last Bar ... - // - // Momentum Bar ... - X_BULLISH_MOMENTUM_BAR_DETECTED, - X_BEARISH_MOMENTUM_BAR_DETECTED, - // - // Rejection Bar ... - X_BULLISH_REJECTION_BAR_DETECTED, - X_BEARISH_REJECTION_BAR_DETECTED, - // - // Swings ... - X_SWING_HIGH_DETECTED, - X_SWING_LOW_DETECTED, - // - // Support nad Resistance ... - X_SUPPORT_ZONE_DETECTED, // Support Zone ... - X_RESISTANCE_ZONE_DETECTED, // Resistance Zone ... - // - // Supply nad Demand ... - X_SUPPLY_ZONE_DETECTED, // Supply Zone ... - X_DEMAND_ZONE_DETECTED, // Demand Zone ... - // - // Order Blocks ... - X_BULLISH_ORDERBLOCK_DETECTED, // Bullish Order Block ... - X_BEARISH_ORDERBLOCK_DETECTED, // Bearish Order Block ... - // - // Fair Value Gaps ... - X_BULLISH_FVG_DETECTED, // Bullish Fair Value GapÙ‘ ... - X_BEARISH_FVG_DETECTED, // Bearish Fair Value GapÙ‘ ... - X_BULLISH_CONSOLIDATION_ZONE_DETECTED, - X_BEARISH_CONSOLIDATION_ZONE_DETECTED, - X_BULLISH_SHARP_DETECTED, - X_BEARISH_SHARP_DETECTED, - X_BULLISH_SPIKE_DETECTED, - X_BEARISH_SPIKE_DETECTED, - X_BULLISH_PULLBACK_DETECTED, - X_BEARISH_PULLBACK_DETECTED, -}; - -// -enum ENUM_XZONE_STATE -{ - XZONE_STATE_NONE, - XZONE_STATE_PASSED, - XZONE_STATE_FAILED, - XZONE_STATE_IGNORED, -}; - -// -// Forext Sessions ... -enum ENUM_XSESSION -{ - X_TOKYO, - X_SYDNEY, - X_LONDON, - X_NEW_YORK, - X_FRANKFORT, -}; - -/** - * Converts ENUM_XPOI value to String Representation ... - * - * @param value: ENUM_XPOI member ... - * - * @return ( string ) - */ -string ToString(ENUM_XPOIS value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_POI_TRADING_DAY: - result = "XTDAY"; - break; - - // - case X_POI_MARKET_SESSION: - result = "XMSESS"; - break; - - // - case X_POI_MOMENTUM_BAR: - result = "XMNTMB"; - break; - - // - case X_POI_REJECTION_BAR: - result = "XRJCTB"; - break; - - // - case X_POI_SWING_HIGH: - result = "XSPH"; - break; - - // - case X_POI_SWING_LOW: - result = "XSPL"; - break; - - // - case X_POI_SUPPORT_ZONE: - result = "XSUP"; - break; - - // - case X_POI_RESISTANCE_ZONE: - result = "XRES"; - break; - - // - case X_POI_SUPPLY_ZONE: - result = "XSUPPLY"; - break; - - // - case X_POI_DEMAND_ZONE: - result = "XDEMAND"; - break; - - // - case X_POI_BULLISH_ORDERBLOCK: - result = "XBULLOB"; - break; - - // - case X_POI_BEARISH_ORDERBLOCK: - result = "XBEAROB"; - break; - - // - case X_POI_BULLISH_FVG: - result = "XBULLFVG"; - break; - - // - case X_POI_BEARISH_FVG: - result = "XBEARFVG"; - break; - - // - case X_POI_TICKS_ZONES: - result = "XTKSZ"; - break; - - // - case X_BULLISH_CONSOLIDATION_ZONE: - result = "XBULLCZ"; - break; - - // - case X_BEARISH_CONSOLIDATION_ZONE: - result = "XBEARCZ"; - break; - - // - case X_BULLISH_SPIKE: - result = "XBULLSPK"; - break; - - // - case X_BEARISH_SPIKE: - result = "XBEARSPK"; - break; - } - - // - return result; -} - -/** - * Converts ENUM_XSESSION value to String Representation ... - * - * @param value: ENUM_XSESSION member ... - * - * @return ( string ) - */ -string ToString(ENUM_XSESSION value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_SYDNEY: - result = "Sydney"; - break; - - // - case X_TOKYO: - result = "Tokyo"; - break; - - // - case X_FRANKFORT: - result = "FrankGurt"; - break; - - // - case X_LONDON: - result = "London"; - break; - - // - case X_NEW_YORK: - result = "NewYork"; - break; - } - - // - return result; -} - -/** - * Generate General Event Messages ... - * - * @param value: ENUM_XPOI_EVENTS member ... - * - * @return ( string ) - */ -string ToString(ENUM_XPOI_EVENTS value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_TRADE_DAY_FIRST_BAR: - result = "First Bar of Day"; - break; - - // - case X_TRADE_DAY_LAST_BAR: - result = "Last Bar of Day"; - break; - - // - case X_SESSION_FIRST_BAR: - result = "First Bar of Session"; - break; - - // - case X_SESSION_LAST_BAR: - result = "Last Bar of Session"; - break; - - // - case X_BULLISH_MOMENTUM_BAR_DETECTED: - result = "Bullish Momentum Bar Detected"; - break; - - // - case X_BEARISH_MOMENTUM_BAR_DETECTED: - result = "Bearish Momentum Bar Detected"; - break; - - // - case X_BULLISH_REJECTION_BAR_DETECTED: - result = "Bullish Rejection Bar Detected"; - break; - - // - case X_BEARISH_REJECTION_BAR_DETECTED: - result = "Bearish Rejection Bar Detected"; - break; - - // - case X_SWING_HIGH_DETECTED: - result = "Swing High Detected"; - break; - - // - case X_SWING_LOW_DETECTED: - result = "Swing Low Detected"; - break; - - // - case X_SUPPORT_ZONE_DETECTED: - result = "Support Zone Detected"; - break; - - // - case X_RESISTANCE_ZONE_DETECTED: - result = "Resistance Zone Detected"; - break; - - // - case X_SUPPLY_ZONE_DETECTED: - result = "Supply Zone Detected"; - break; - - // - case X_DEMAND_ZONE_DETECTED: - result = "Demand Zone Detected"; - break; - - // - case X_BULLISH_ORDERBLOCK_DETECTED: - result = "Bullish Order Block Detected"; - break; - - // - case X_BEARISH_ORDERBLOCK_DETECTED: - result = "Bearish Orer Block Detected"; - break; - - // - case X_BULLISH_FVG_DETECTED: - result = "Bullish FVG Detected"; - break; - - // - case X_BEARISH_FVG_DETECTED: - result = "Bearish FVg Detected"; - break; - } - - // - return result; -} - -// -// Implementation ... - -// -// Base POI Model Class ... -class XCBasePOI : public XCBase -{ - // - public: - // - - // - // Constructor ... - void XCBasePOI() - { - // - Clean(); - - // - mSep = "_"; - mLineSep = "\n"; - } - - // - // Deconstructor ... - void ~XCBasePOI() - { - Clean(); - } - - // - // Virtual ... - - /** - * Cleanup ... - */ - virtual void Clean() - { - mType = X_POI_NONE; - } - - /** - * Validate ... - * - * @return ( virtual bool ) - */ - virtual bool IsValid() - { - return false; - } - - /** - * Retrieve POI Type ... - * - * @return ( virtual ENUM_XPOIS member ) - */ - virtual ENUM_XPOIS Type() - { - return mType; - } - - /** - * Retrieve POI Type ... - * - * @return ( virtual string ) - */ - virtual string TypeAsString() - { - return ToString(mType); - } - - /** - * Retrieve POI Tag ... - * - * @return ( virtual string ) - */ - virtual string GetTag() - { - return NULL; - } - - /** - * Retrieve POI Tooltip ... - * - * @return ( virtual string ) - */ - virtual string GetTooltip() - { - return NULL; - } - - // - protected: - // - // Props ... - string mSep; // Separator ... - string mLineSep; // Line Separator ... - ENUM_XPOIS mType; // Type ... - - // - private: - // -}; - -// -typedef void (*TOnPOIEvent)(ENUM_XPOI_EVENTS event, - XCBasePOI *param // -); - -// -// Zone POI Class ... -class XCZone : public XCBasePOI -{ - // - public: - // - - // - // Constructor ... - void XCZone() - { - } - - // - // Deconstructor ... - void ~XCZone() - { - } - - // - // Tools ... - - // - // Getter(s) / Setter(s) ... - - /** - * Get Zone Upper Boundary ... - * - * @return ( double ) - */ - double Upper() - { - return mUpper; - } - - /** - * Set Zone Upper Boundary ... - */ - void Upper(double value) - { - mUpper = value; - } - - /** - * Get Zone Lower Boundary ... - * - * @return ( double ) - */ - double Lower() - { - return mLower; - } - - /** - * Set Zone Lower Boundary ... - */ - void Lower(double value) - { - mLower = value; - } - - /** - * Retrieve Zone Range ... - * - * @return ( double ) - */ - double Range() - { - // - double result = 0; - - // - double upper = Upper(); - double lower = Lower(); - - // - if (upper > 0 && lower > 0 && upper > lower) - { - result = upper - lower; - } - - // - return result; - } - - double RangePercent() - { - // - double result = 0; - - // - double range = Range(); - if (range > 0) - { - result = range / 100; - } - - // - return result; - } - - // - // Virtuals ... - - /** - * Get Zone Start Date ... - * - * @return ( virtual datetime ) - */ - virtual datetime From() - { - return NULL; - } - - /** - * Get Zone End Date ... - * - * @return ( virtual datetime ) - */ - virtual datetime To() - { - return NULL; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - // - // Validators ... - - /** - * Validate Upper and Lower of Zone ... - * - * @return ( bool ) - */ - bool IsValidBoundary() - { - // - bool result = false; - - // - result = - // - mUpper > 0 && - mLower > 0 && - mUpper >= mLower - // - ; - - // - return result; - } - - /** - * Check From Date of Zone is Valid ... - * - * @return ( bool ) - */ - bool IsValidFrom() - { - // - bool result = false; - - // - datetime from = From(); - result = IsSpecifiedValid(from); - - // - return result; - } - - // - protected: - // - // Props ... - double mUpper; // Zone Upper ... - double mLower; // Zone Lower ... - - // - private: - // - // Props ... - - // -}; - -// -// From To Zone ... -class XCFromToZone : public XCBasePOI -{ - // - public: - // - - // - // Constructor ... - void XCFromToZone() - { - } - - // - // Deconstructor ... - void ~XCFromToZone() - { - } - - // - // Tools ... - - bool InitFromTo( - ENUM_XPOIS type, - string title, - datetime from // - ) - { - // - bool result = false; - - // - result = type != X_POI_NONE && - IsSpecifiedValid(from) && - IsSpecifiedValid(title); - - // - mType = type; - mFrom = from; - mTitle = title; - mTo = TimeCurrent(); - - // - result = IsValid(); - - // - return result; - } - - bool InitFromTo( - ENUM_XPOIS type, - string title, - datetime from, - datetime to // - ) - { - // - bool result = false; - - // - result = IsValid(); - - // - result = InitFromTo( - type, - title, - from // - ); - if (!result) - { - return result; - } - - // - to = NormalizeTime(to); - mTo = to; - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Get Zone Start Time ... - * - * @return ( datetime ) - */ - datetime From() - { - return mFrom; - } - - /** - * Set Zone Start Time ... - * - * @param value: Datetime - */ - void From(datetime value) - { - // - value = NormalizeTime(value); - - // - mFrom = value; - } - - /** - * Get Zone End Time ... - * - * @return ( datetime ) - */ - datetime To() - { - return mTo; - } - - /** - * Set Zone End Time ... - * - * @param value: Datetime - */ - void To(datetime value) - { - // - value = NormalizeTime(value); - - // - mTo = value; - } - - /** - * Get Title ... - * - * @return ( string ) - */ - string Title() - { - return mTitle; - } - - /** - * Set Title ... - * - * @param value: String ... - */ - // void Title(string value) - // { - // mTitle = value; - // } - - // - // Overrides ... - - void Clean() override - { - // - mTo = NULL; - mFrom = NULL; - mType = X_POI_NONE; - } - - bool IsValid() override - { - // - bool result = false; - - // - result = - // - mType != X_POI_NONE && - IsSpecifiedValid(mTo) && - IsSpecifiedValid(mFrom) && - IsSpecifiedValid(mTitle) - // - ; - - // - return result; - } - - string GetTag() override - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - string hash = TypeAsString() + mSep + ToString(From()) + mSep + Title(); - hash = ToMD5(hash); - - // - result = TypeAsString() + "[" + Title() + "]" + mSep + hash; - - // - return result; - } - - // - protected: - // - - // - private: - // - // Props ... - datetime mFrom; // Start Date - datetime mTo; // End Date - string mTitle; // Zone Title - - // -}; - -// -// Bar Zone ... -class XCBarZone : public XCZone -{ - // - public: - // - - // - // Constructor ... - void XCBarZone() - { - } - - // - // Deconstructor ... - void ~XCBarZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param type: ENUM_XPOIS member ... - * @param upperPrice: ENUM_X_PRICE member ... - * @param lowerPrice: ENUM_X_PRICE member ... - * - * @return ( bool ) - */ - bool InitBarZone( - XOHCL &bar, - ENUM_XPOIS type, - ENUM_X_PRICE upperPrice, - ENUM_X_PRICE lowerPrice // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - type != X_POI_NONE && - upperPrice != lowerPrice; - if (!result) - { - return result; - } - - // - mBar = bar; - mType = type; - mUpperPrice = upperPrice; - mLowerPrice = lowerPrice; - mUpper = bar.GetPrice(upperPrice); - mLower = bar.GetPrice(lowerPrice); - - // - result = IsValidBarZone(); - if (result) - { - // - From(bar.time); - To(TimeCurrent()); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Fill Bar as XOHCL struct ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool FillBar( - XOHCL &bar // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - bar = mBar; - result = mBar.IsValid(); - - // - return result; - } - - /** - * Set From Date ... - * - * @param value: DateTime ... - */ - void From(datetime value) - { - // - if (!IsValidBarZone()) - { - return; - } - - // - value = NormalizeTime(value); - - // - mFrom = value; - } - - /** - * Set To Date ... - * - * @param value: DateTime ... - */ - void To(datetime value) - { - // - if (!IsValidBarZone()) - { - return; - } - - // - value = NormalizeTime(value); - - // - mTo = value; - } - - /** - * Retrieve Bar Time ... - * - * @return ( datetime ) - */ - datetime BarTime() - { - return mBar.time; - } - - /** - * Get Symbol ... - * - * @return ( string ) - */ - string GetSymbol() - { - // - string result = NULL; - - // - if (!mBar.IsValid()) - { - return result; - } - - // - return mBar.symbol; - - // - return result; - } - - /** - * Get Period ... - * - * @return ( int ) - */ - ENUM_TIMEFRAMES GetPeriod() - { - // - ENUM_TIMEFRAMES result = NULL; - - // - if (!mBar.IsValid()) - { - return result; - } - - // - return mBar.period; - - // - return result; - } - - /** - * Check Zone Started or not ... - * First Exit in Direction of Zone after From ... - * - * @param forDir: exit direction ... - * @param startedBar: specified Start Bar ... - * @param isBodyOut: specified Start Bar Close is Out of Zone or not ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsStarted( - ENUM_X_DIRECTION forDir, - XOHCL &startedBar, - bool &isBodyOut, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - startedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - // Detect From Bar Index ... - int fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - isBullish - ? isBreakedFromUpper - : isBreakedFromLower; - if (result) - { - // - startedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = startedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? startedBar.IsBullish() && - startedBar.GetUp() > Upper() - : startedBar.IsBearish() && - startedBar.GetDown() < Lower(); - } - - // - return result; - } - - /** - * Check Zone Activated or not ... - * First Enter in Opposit Direction of Zone after Start ... - * - * @param forDir: exit direction ... - * @param activatedBar: specified Activation Bar ... - * @param isBodyIn: specified Activation Bar Close is Inside of Zone or not ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsActivated( - ENUM_X_DIRECTION forDir, - XOHCL &activatedBar, - bool &isBodyIn, - bool forceBodyOutStarted = true, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyIn = false; - activatedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - XOHCL startedBar; - bool isBodyOut = false; - bool isStarted = IsStarted( - forDir, - startedBar, - isBodyOut, - forPeriod // - ); - result = - !forceBodyOutStarted - ? isStarted - : isStarted && - isBodyOut; - if (!result) - { - // - startedBar.Clean(); - return result; - } - - // - int fromIndex = startedBar.Index() - 1; - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isInsideFromUpper = - // - iBar.high < Upper() || - (iBar.high > Upper() && - iBar.low <= Upper() && - iBar.close <= Upper()) - // - ; - - // - bool isInsideFromLower = - // - iBar.low > Lower() || - (iBar.low < Lower() && - iBar.high >= Lower() && - iBar.close >= Lower()) - // - ; - - // - bool isInside = - isInsideFromUpper || - isInsideFromLower; - if (isInside) - { - // - result = isInside && - isBullish - ? isInsideFromUpper - : isInsideFromLower; - if (result) - { - // - activatedBar = iBar; - iBar.Clean(); - startedBar.Clean(); - break; - } - } - - // - iBar.Clean(); - startedBar.Clean(); - } - - // - result = activatedBar.IsValid(); - if (result) - { - // - isBodyIn = - isBullish - ? activatedBar.IsBearish() && - activatedBar.GetDown() < Upper() - : activatedBar.IsBullish() && - activatedBar.GetUp() > Lower(); - } - - // - return result; - } - - /** - * Check Zone Breaked or not ... - * - * @param forDir: exit direction ... - * @param breakedBar: specified Breaked Bar ... - * @param isBodyOut: specified Breaked Bar Close is Out of Zone or not ... - * @param ignoreStart: Ignore Zone Start (Calculate from From()) ... - * @param startedBodyOut: Started Bar Body Close State, if use Start for Calculation ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsBreaked( - ENUM_X_DIRECTION forDir, - XOHCL &breakedBar, - bool &isBodyOut, - bool ignoreStart = false, - bool startedBodyOut = false, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - breakedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - int fromIndex = -1; - if (!ignoreStart) - { - // - XOHCL startedBar; - bool isBodyOut = false; - bool isStarted = IsStarted( - forDir, - startedBar, - isBodyOut, - forPeriod // - ); - - // - bool isStartPassed = - !startedBodyOut - ? isStarted - : isStarted && - isBodyOut; - if (isStartPassed) - { - fromIndex = startedBar.Index() - 1; - } - - // - startedBar.Clean(); - } - else - { - // - fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - } - - // - result = IsValidIndex(fromIndex); - if (!result) - { - return result; - } - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - (isBullish - ? isBreakedFromLower - : isBreakedFromUpper); - if (result) - { - // - breakedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = breakedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? breakedBar.IsBearish() && - breakedBar.GetDown() < Lower() - : breakedBar.IsBullish() && - breakedBar.GetUp() > Upper(); - } - - // - return result; - } - - /** - * Check Zone Worked or not ... - * - * @param forDir: exit direction ... - * @param workedBar: specified Worked Bar ... - * @param isBodyOut: specified Worked Bar Close is Out of Zone or not ... - * @param ignoreActivation: Ignore Zone Activation (Calculate from From()) ... - * @param activationStartedOut: Specified Zone Start Bar State ... - * @param activationBodyIn: Specified Zone Activation Bar State ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsWorked( - ENUM_X_DIRECTION forDir, - XOHCL &workedBar, - bool &isBodyOut, - bool ignoreActivation = false, - bool activationStartedOut = false, - bool activationBodyIn = false, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - workedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - int fromIndex = -1; - if (!ignoreActivation) - { - // - XOHCL activatedBar; - bool isBodyIn = false; - bool isActivated = IsActivated( - forDir, - activatedBar, - isBodyIn, - activationStartedOut, - forPeriod // - ); - - // - bool isActivationPassed = - !activationBodyIn - ? isActivated - : isActivated && - isBodyIn; - if (isActivationPassed) - { - fromIndex = activatedBar.Index() - 1; - } - - // - activatedBar.Clean(); - } - else - { - // - fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - } - - // - result = IsValidIndex(fromIndex); - if (!result) - { - return result; - } - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - isBullish - ? isBreakedFromUpper - : isBreakedFromLower; - if (result) - { - // - workedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = workedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? workedBar.IsBullish() && - workedBar.GetUp() > Upper() - : workedBar.IsBearish() && - workedBar.GetDown() < Lower(); - } - - // - return result; - } - - /** - * Check to Find Nearest Bar which Breakes Upper ... - * - * @param bar: XOHCL instance Reference, Breaker Bar ... - * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... - * - * @return ( bool ) - */ - bool FindNearestInsideBarFromUpper( - XOHCL &bar, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - bar.Clean(); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int from = 1; - int to = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = from; i < to; i++) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - if (!isInited) - { - break; - } - - // - bool isInside = iBar.low < Upper(); - if (isInside) - { - // - bar = iBar; - break; - } - } - - // - result = bar.IsValid(); - - // - return result; - } - - /** - * Check to Find Nearest Bar which Breakes Lower ... - * - * @param bar: XOHCL instance Reference, Breaker Bar ... - * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... - * - * @return ( bool ) - */ - bool FindNearestInsideBarFromLower( - XOHCL &bar, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - bar.Clean(); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int from = 1; - int to = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = from; i < to; i++) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - if (!isInited) - { - break; - } - - // - bool isInside = iBar.high > Lower(); - if (isInside) - { - // - bar = iBar; - break; - } - } - - // - result = bar.IsValid(); - - // - return result; - } - - // - // Overrides ... - - void Clean() override - { - // - mBar.Clean(); - mUpper = 0; - mLower = 0; - mType = X_POI_NONE; - } - - datetime From() override - { - return mFrom; - } - - datetime To() override - { - return mTo; - } - - string GetTag() override - { - // - string result = NULL; - - // - if (!IsValidBarZone()) - { - return result; - } - - // - string hash = ToMD5(mBar.GetTag()); - - // - result = - // - TypeAsString() + mSep + - ToString(mBar.period) + mSep + - hash - // - ; - - // - return result; - } - - string GetTooltip() override - { - // - string result = NULL; - - // - if (!IsValidBarZone()) - { - return result; - } - - // - return result; - } - - // - protected: - // - // Props ... - XOHCL mBar; // Bar ... - ENUM_X_PRICE mUpperPrice; // Upper Price Selection - ENUM_X_PRICE mLowerPrice; // Lower Price Selection - - /** - * Check Bar Zone Validation ... - * - * @return ( bool ) - */ - bool IsValidBarZone() - { - // - bool result = false; - - // - result = mBar.IsValid() && - mType != X_POI_NONE && - IsValidBoundary(); - - // - return result; - } - - // - private: - // - // Props ... - datetime mFrom; - datetime mTo; - - // -}; -class XCTwoBarZone : public XCZone -{ - // - public: - // - - // - // Constructor ... - void XCTwoBarZone() - { - } - - // - // Deconstructor ... - void ~XCTwoBarZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param type: ENUM_XPOIS member ... - * @param upperPrice: ENUM_X_PRICE member ... - * @param lowerPrice: ENUM_X_PRICE member ... - * - * @return ( bool ) - */ - bool InitTwoBarZone( - XOHCL &startBar, - XOHCL &endBar, - ENUM_XPOIS type, - ENUM_X_PRICE startPrice, - ENUM_X_PRICE endPrice // - ) - { - // - bool result = false; - - // - result = startBar.IsValid() && - endBar.IsValid() && - startBar.symbol == endBar.symbol && - startBar.period == endBar.period && - startBar.time < endBar.time && - type != X_POI_NONE; - if (!result) - { - return result; - } - - // - mType = type; - mEndBar = endBar; - mStartBar = startBar; - - // - int startIndex = startBar.Index(); - int endIndex = endBar.Index(); - - // - double mStartPrice = startBar.GetPrice(startPrice); - double mEndPrice = endBar.GetPrice(endPrice); - bool isStartOverEnd = mStartPrice > mEndPrice; - - // - if (isStartOverEnd) - { - // - mUpperPrice = startPrice; - mLowerPrice = endPrice; - } - else - { - // - mUpperPrice = endPrice; - mLowerPrice = startPrice; - } - - // - mUpper = MathMax(mStartPrice, mEndPrice); - mLower = MathMin(mStartPrice, mEndPrice); - - // - result = IsValidTwoBarZone(); - if (result) - { - // - From(startBar.time); - To(endBar.time); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set From Date ... - * - * @param value: DateTime ... - */ - void From(datetime value) - { - // - if (!IsValidTwoBarZone()) - { - return; - } - - // - value = NormalizeTime(value); - - // - mFrom = value; - } - - /** - * Set To Date ... - * - * @param value: DateTime ... - */ - void To(datetime value) - { - // - if (!IsValidTwoBarZone()) - { - return; - } - - // - value = NormalizeTime(value); - - // - mTo = value; - } - - /** - * Fill Start Bar ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool FillStartBar(XOHCL &bar) - { - // - bool result = false; - - // - result = IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bar = mStartBar; - - // - return result; - } - - /** - * Fill End Bar ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool FillEndBar(XOHCL &bar) - { - // - bool result = false; - - // - result = IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bar = mEndBar; - - // - return result; - } - - /** - * Get Symbol ... - * - * @return ( string ) - */ - string GetSymbol() - { - // - string result = NULL; - - // - if (!mStartBar.IsValid()) - { - return result; - } - - // - return mStartBar.symbol; - - // - return result; - } - - /** - * Get Period ... - * - * @return ( int ) - */ - ENUM_TIMEFRAMES GetPeriod() - { - // - ENUM_TIMEFRAMES result = NULL; - - // - if (!mStartBar.IsValid()) - { - return result; - } - - // - return mStartBar.period; - - // - return result; - } - - /** - * Check Zone Started or not ... - * First Exit in Direction of Zone after From ... - * - * @param forDir: exit direction ... - * @param startedBar: specified Start Bar ... - * @param isBodyOut: specified Start Bar Close is Out of Zone or not ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsStarted( - ENUM_X_DIRECTION forDir, - XOHCL &startedBar, - bool &isBodyOut, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - startedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - // Detect From Bar Index ... - int fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - isBullish - ? isBreakedFromUpper - : isBreakedFromLower; - if (result) - { - // - startedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = startedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? startedBar.IsBullish() && - startedBar.GetUp() > Upper() - : startedBar.IsBearish() && - startedBar.GetDown() < Lower(); - } - - // - return result; - } - - /** - * Check Zone Activated or not ... - * First Enter in Opposit Direction of Zone after Start ... - * - * @param forDir: exit direction ... - * @param activatedBar: specified Activation Bar ... - * @param isBodyIn: specified Activation Bar Close is Inside of Zone or not ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsActivated( - ENUM_X_DIRECTION forDir, - XOHCL &activatedBar, - bool &isBodyIn, - bool forceBodyOutStarted = true, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyIn = false; - activatedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - XOHCL startedBar; - bool isBodyOut = false; - bool isStarted = IsStarted( - forDir, - startedBar, - isBodyOut, - forPeriod // - ); - result = - !forceBodyOutStarted - ? isStarted - : isStarted && - isBodyOut; - if (!result) - { - // - startedBar.Clean(); - return result; - } - - // - int fromIndex = startedBar.Index() - 1; - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isInsideFromUpper = - // - iBar.high < Upper() || - (iBar.high > Upper() && - iBar.low <= Upper() && - iBar.close <= Upper()) - // - ; - - // - bool isInsideFromLower = - // - iBar.low > Lower() || - (iBar.low < Lower() && - iBar.high >= Lower() && - iBar.close >= Lower()) - // - ; - - // - bool isInside = - isInsideFromUpper || - isInsideFromLower; - if (isInside) - { - // - result = isInside && - isBullish - ? isInsideFromUpper - : isInsideFromLower; - if (result) - { - // - activatedBar = iBar; - iBar.Clean(); - startedBar.Clean(); - break; - } - } - - // - iBar.Clean(); - startedBar.Clean(); - } - - // - result = activatedBar.IsValid(); - if (result) - { - // - isBodyIn = - isBullish - ? activatedBar.IsBearish() && - activatedBar.GetDown() < Upper() - : activatedBar.IsBullish() && - activatedBar.GetUp() > Lower(); - } - - // - return result; - } - - /** - * Check Zone reaked or not ... - * - * @param forDir: exit direction ... - * @param breakedBar: specified Breaked Bar ... - * @param isBodyOut: specified Breaked Bar Close is Out of Zone or not ... - * @param ignoreStart: Ignore Zone Start (Calculate from From()) ... - * @param startedBodyOut: Started Bar Body Close State, if use Start for Calculation ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsBreaked( - ENUM_X_DIRECTION forDir, - XOHCL &breakedBar, - bool &isBodyOut, - bool ignoreStart = false, - bool startedBodyOut = false, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - breakedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - int fromIndex = -1; - if (!ignoreStart) - { - // - XOHCL startedBar; - bool isBodyOut = false; - bool isStarted = IsStarted( - forDir, - startedBar, - isBodyOut, - forPeriod // - ); - - // - bool isStartPassed = - !startedBodyOut - ? isStarted - : isStarted && - isBodyOut; - if (isStartPassed) - { - fromIndex = startedBar.Index() - 1; - } - - // - startedBar.Clean(); - } - else - { - // - fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - } - - // - result = IsValidIndex(fromIndex); - if (!result) - { - return result; - } - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - (isBullish - ? isBreakedFromLower - : isBreakedFromUpper); - if (result) - { - // - breakedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = breakedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? breakedBar.IsBearish() && - breakedBar.GetDown() < Lower() - : breakedBar.IsBullish() && - breakedBar.GetUp() > Upper(); - } - - // - return result; - } - - /** - * Check Zone Worked or not ... - * - * @param forDir: exit direction ... - * @param workedBar: specified Worked Bar ... - * @param isBodyOut: specified Worked Bar Close is Out of Zone or not ... - * @param ignoreActivation: Ignore Zone Activation (Calculate from From()) ... - * @param activationStartedOut: Specified Zone Start Bar State ... - * @param activationBodyIn: Specified Zone Activation Bar State ... - * @param forPeriod: specified Period ... - * - * @return ( bool ) - */ - bool IsWorked( - ENUM_X_DIRECTION forDir, - XOHCL &workedBar, - bool &isBodyOut, - bool ignoreActivation = false, - bool activationStartedOut = false, - bool activationBodyIn = false, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - isBodyOut = false; - workedBar.Clean(); - - // - result = HasDirection(forDir) && - IsValidTwoBarZone(); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - int fromIndex = -1; - if (!ignoreActivation) - { - // - XOHCL activatedBar; - bool isBodyIn = false; - bool isActivated = IsActivated( - forDir, - activatedBar, - isBodyIn, - activationStartedOut, - forPeriod // - ); - - // - bool isActivationPassed = - !activationBodyIn - ? isActivated - : isActivated && - isBodyIn; - if (isActivationPassed) - { - fromIndex = activatedBar.Index() - 1; - } - - // - activatedBar.Clean(); - } - else - { - // - fromIndex = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - } - - // - result = IsValidIndex(fromIndex); - if (!result) - { - return result; - } - - // - for (int i = fromIndex; i >= 0; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - result = isInited; - if (!result) - { - // - iBar.Clean(); - continue; - } - - // - bool isBreakedFromUpper = - // - iBar.low > Upper() || - (iBar.low <= Upper() && - iBar.high > Upper() && - iBar.close > Upper()) - // - ; - - // - bool isBreakedFromLower = - // - iBar.low < Lower() || - (iBar.high >= Lower() && - iBar.low < Lower() && - iBar.close < Lower()) - // - ; - - // - bool isBreaked = - isBreakedFromUpper || - isBreakedFromLower; - if (isBreaked) - { - // - result = isBreaked && - isBullish - ? isBreakedFromUpper - : isBreakedFromLower; - if (result) - { - // - workedBar = iBar; - iBar.Clean(); - break; - } - } - - // - iBar.Clean(); - } - - // - result = workedBar.IsValid(); - if (result) - { - // - isBodyOut = - isBullish - ? workedBar.IsBullish() && - workedBar.GetUp() > Upper() - : workedBar.IsBearish() && - workedBar.GetDown() < Lower(); - } - - // - return result; - } - - /** - * Check to Find Nearest Bar which Breakes Upper ... - * - * @param bar: XOHCL instance Reference, Breaker Bar ... - * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... - * - * @return ( bool ) - */ - bool FindNearestInsideBarFromUpper( - XOHCL &bar, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - bar.Clean(); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int from = 1; - int to = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = from; i < to; i++) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - if (!isInited) - { - break; - } - - // - bool isInside = iBar.low < Upper(); - if (isInside) - { - // - bar = iBar; - break; - } - } - - // - result = bar.IsValid(); - - // - return result; - } - - /** - * Check to Find Nearest Bar which Breakes Lower ... - * - * @param bar: XOHCL instance Reference, Breaker Bar ... - * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... - * - * @return ( bool ) - */ - bool FindNearestInsideBarFromLower( - XOHCL &bar, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - bar.Clean(); - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = GetPeriod(); - } - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int from = 1; - int to = iBarShift( - GetSymbol(), - forPeriod, - From() // - ); - - // - for (int i = from; i < to; i++) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - GetSymbol(), - forPeriod, - i // - ); - if (!isInited) - { - break; - } - - // - bool isInside = iBar.high > Lower(); - if (isInside) - { - // - bar = iBar; - break; - } - } - - // - result = bar.IsValid(); - - // - return result; - } - - // - // Overrides ... - - void Clean() override - { - // - mStartBar.Clean(); - mEndBar.Clean(); - mUpper = 0; - mLower = 0; - mUseStartBarForUpper = false; - mType = X_POI_NONE; - } - - datetime From() override - { - return mFrom; - } - - datetime To() override - { - return mTo; - } - - string GetTag() override - { - // - string result = NULL; - - // - if (!IsValidTwoBarZone()) - { - return result; - } - - // - string hash = ToMD5(mStartBar.GetTag() + mSep + mEndBar.GetTag()); - - // - result = - // - TypeAsString() + mSep + - ToString(mStartBar.period) + mSep + - hash - // - ; - - // - return result; - } - - string GetTooltip() override - { - // - string result = NULL; - - // - if (!IsValidTwoBarZone()) - { - return result; - } - - // - return result; - } - - // - protected: - // - // Props ... - XOHCL mStartBar; // Start (Oldest) Bar ... - XOHCL mEndBar; // End (Newest) Bar ... - bool mUseStartBarForUpper; // Use Start Bar for Upper Calculation ... - ENUM_X_PRICE mUpperPrice; // Upper Price Selection - ENUM_X_PRICE mLowerPrice; // Lower Price Selection - - /** - * Check Two Bar Zone Validation ... - * - * @return ( bool ) - */ - bool IsValidTwoBarZone() - { - // - bool result = false; - - // - result = mStartBar.IsValid() && - mEndBar.IsValid() && - mStartBar.symbol == mEndBar.symbol && - mStartBar.period == mEndBar.period && - mStartBar.time < mEndBar.time && - mType != X_POI_NONE && - IsValidBoundary(); - - // - return result; - } - - // - private: - // - // Props ... - datetime mFrom; - datetime mTo; - - // -}; - -// -// Swing Class ... -class XCSwing : public XCBasePOI -{ - // - public: - // - - // - // Constructor ... - void XCSwing() - { - } - - // - // Deconstructor ... - void ~XCSwing() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param type: ENUM_XPOIS member ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - ENUM_XPOIS type // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - (type == X_POI_SWING_HIGH || - type == X_POI_SWING_LOW); - if (!result) - { - return result; - } - - // - mBar = bar; - mType = type; - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Fill Bar as XOHCL struct ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool FillBar( - XOHCL &bar // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - bar = mBar; - result = mBar.IsValid(); - - // - return result; - } - - /** - * Get Time of Swing ... - * - * @return ( datetime ) - */ - datetime GetTime() - { - // - datetime result = NULL; - - // - if (!IsValid() || !mBar.IsValid()) - { - return result; - } - - // - result = mBar.time; - - // - return result; - } - - ENUM_TIMEFRAMES GetPeriod() - { - // - ENUM_TIMEFRAMES result = NULL; - - // - XOHCL bar; - bool isFilled = FillBar(bar); - if (!isFilled) - { - return result; - } - - // - result = bar.period; - - // - return result; - } - - /** - * Check Swing High or not ... - * - * @return ( bool ) - */ - bool IsSwingHigh() - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - result = - Type() == X_POI_SWING_HIGH; - - // - return result; - } - - /** - * Check Swing Low or not ... - * - * @return ( bool ) - */ - bool IsSwingLow() - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - result = - Type() == X_POI_SWING_LOW; - - // - return result; - } - - /** - * Get Swing Value ... - * - * @return ( double ) - */ - double GetValue() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = - IsSwingHigh() - ? mBar.high - : mBar.low; - - // - return result; - } - - // - // Overrides ... - - void Clean() override - { - // - mBar.Clean(); - mType = X_POI_NONE; - } - - bool IsValid() override - { - // - bool result = false; - - // - result = mBar.IsValid() && - (mType == X_POI_SWING_HIGH || - mType == X_POI_SWING_LOW); - - // - return result; - } - - string GetTag() override - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - string hash = ToMD5(mBar.GetTag()); - - // - string subType = IsSwingHigh() - ? "High" - : "Low"; - - // - result = - // - TypeAsString() + mSep + - subType + mSep + - ToString(mBar.period) + mSep + - hash - // - ; - - // - return result; - } - - string GetTooltip() override - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - return result; - } - - // - protected: - // - // Props ... - XOHCL mBar; // Swing Bar ... - - // - private: - // -}; - -// -// Supply Zone ... -class XCSupplyZone : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCSupplyZone() - { - } - - // - // Deconstructor ... - void ~XCSupplyZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param range: Integer, Detection Range ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - int range = 0, - bool useRangeAsStart = false // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - result = InitBarZone( - bar, - X_POI_SUPPLY_ZONE, - X_PRICE_HIGH, - X_PRICE_LOW // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - if (result && - range > 0) - { - // - datetime time = bar.time; - int periodSeconds = PeriodSeconds(bar.period); - - // - datetime from = - !useRangeAsStart - ? (datetime)((int)time - (range * periodSeconds)) - : time; - datetime to = (datetime)((int)time + (range * periodSeconds)); - - // - From(from); - To(to); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_SUPPLY_ZONE; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Demand Zone ... -class XCDemandZone : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCDemandZone() - { - } - - // - // Deconstructor ... - void ~XCDemandZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param range: Integer, Detection Range ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - int range = 0, - bool useRangeAsStart = false // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - result = InitBarZone( - bar, - X_POI_DEMAND_ZONE, - X_PRICE_HIGH, - X_PRICE_LOW // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - if (result && - range > 0) - { - // - datetime time = bar.time; - int periodSeconds = PeriodSeconds(bar.period); - - // - datetime from = - !useRangeAsStart - ? (datetime)((int)time - (range * periodSeconds)) - : time; - datetime to = (datetime)((int)time + (range * periodSeconds)); - - // - From(from); - To(to); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_DEMAND_ZONE; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Support Zone ... -class XCSupportZone : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCSupportZone() - { - } - - // - // Deconstructor ... - void ~XCSupportZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param range: Integer, Detection Range ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - int range = 0, - bool useRangeAsStart = false // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - result = InitBarZone( - bar, - X_POI_SUPPORT_ZONE, - X_PRICE_DOWN, - X_PRICE_LOW // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - if (result && - range > 0) - { - // - datetime time = bar.time; - int periodSeconds = PeriodSeconds(bar.period); - - // - datetime from = - !useRangeAsStart - ? (datetime)((int)time - (range * periodSeconds)) - : time; - datetime to = (datetime)((int)time + (range * periodSeconds)); - - // - From(from); - To(to); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_SUPPORT_ZONE; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Resistance Zone ... -class XCResistanceZone : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCResistanceZone() - { - } - - // - // Deconstructor ... - void ~XCResistanceZone() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param range: Integer, Detection Range ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - int range = 0, - bool useRangeAsStart = false // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - result = InitBarZone( - bar, - X_POI_RESISTANCE_ZONE, - X_PRICE_HIGH, - X_PRICE_UP // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - if (result && - range > 0) - { - // - datetime time = bar.time; - int periodSeconds = PeriodSeconds(bar.period); - - // - datetime from = - !useRangeAsStart - ? (datetime)((int)time - (range * periodSeconds)) - : time; - datetime to = (datetime)((int)time + (range * periodSeconds)); - - // - From(from); - To(to); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_RESISTANCE_ZONE; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Order Block ... -class XCOrderBlock : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCOrderBlock() - { - } - - // - // Deconstructor ... - void ~XCOrderBlock() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * @param dir: ENUM_X_DIRECTION member ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar, - ENUM_X_DIRECTION dir // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - (dir == X_DIRECTION_BULLISH || - dir == X_DIRECTION_BEARISH); - if (!result) - { - return result; - } - - // - ENUM_XPOIS mTT = - IsSpecifiedBullish(dir) - ? X_POI_BULLISH_ORDERBLOCK - : X_POI_BEARISH_ORDERBLOCK; - - // - result = InitBarZone( - bar, - mTT, - X_PRICE_HIGH, - X_PRICE_LOW // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Check is Bullish ... - * - * @return ( bool ) - */ - bool IsBullish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_BULLISH_ORDERBLOCK; - - // - return result; - } - - /** - * Check is Bearish ... - * - * @return ( bool ) - */ - bool IsBearish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_BEARISH_ORDERBLOCK; - - // - return result; - } - - ENUM_X_DIRECTION GetDirection() - { - // - ENUM_X_DIRECTION result = X_DIRECTION_NONE; - - // - if (!IsValid()) - { - return result; - } - - // - result = - IsBullish() - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - return result; - } - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - (mType == X_POI_BULLISH_ORDERBLOCK || - mType == X_POI_BEARISH_ORDERBLOCK); - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Rejection Bar ... -class XCRejectionBar : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCRejectionBar() - { - } - - // - // Deconstructor ... - void ~XCRejectionBar() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = - bar.GetLowShadow() > bar.GetHighShadow(); - bool isBearish = - bar.GetHighShadow() > bar.GetLowShadow(); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - ENUM_X_PRICE upPrice = isBullish - ? X_PRICE_HIGH - : X_PRICE_DOWN; - // - ENUM_X_PRICE loPrice = isBullish - ? X_PRICE_UP - : X_PRICE_LOW; - - // - result = InitBarZone( - bar, - X_POI_REJECTION_BAR, - upPrice, - loPrice // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Check is Bullish ... - * - * @return ( bool ) - */ - bool IsBullish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_REJECTION_BAR && - mBar.GetLowShadow() > mBar.GetHighShadow(); - - // - return result; - } - - /** - * Check is Bearish ... - * - * @return ( bool ) - */ - bool IsBearish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_REJECTION_BAR && - mBar.GetHighShadow() > mBar.GetLowShadow(); - - // - return result; - } - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_REJECTION_BAR; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Momentum Bar ... -class XCMomentumBar : public XCBarZone -{ - // - public: - // - - // - // Constructor ... - void XCMomentumBar() - { - } - - // - // Deconstructor ... - void ~XCMomentumBar() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param bar: XOHCL instance ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &bar // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = bar.IsBullish(); - bool isBearish = bar.IsBearish(); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - result = InitBarZone( - bar, - X_POI_MOMENTUM_BAR, - X_PRICE_HIGH, - X_PRICE_LOW // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Check is Bullish ... - * - * @return ( bool ) - */ - bool IsBullish() - { - // - bool result = false; - - // - result = IsValid() && - mBar.IsBullish() && - Type() == X_POI_MOMENTUM_BAR; - - // - return result; - } - - /** - * Check is Bearish ... - * - * @return ( bool ) - */ - bool IsBearish() - { - // - bool result = false; - - // - result = IsValid() && - mBar.IsBearish() && - Type() == X_POI_MOMENTUM_BAR; - - // - return result; - } - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidBarZone() && - mType == X_POI_MOMENTUM_BAR; - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Fair Value Gap ... -class XCFVG : public XCTwoBarZone -{ - // - public: - // - - // - // Constructor ... - void XCFVG() - { - } - - // - // Deconstructor ... - void ~XCFVG() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param startBar: XOHCL instance ... - * @param endBar: XOHCL instance ... - * @param dir: ENUM_X_DIRECTION member ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &startBar, - XOHCL &endBar, - ENUM_X_DIRECTION dir // - ) - { - // - bool result = false; - - // - result = endBar.IsValid() && - startBar.IsValid() && - (dir == X_DIRECTION_BULLISH || - dir == X_DIRECTION_BEARISH); - if (!result) - { - return result; - } - - // - bool isDirBullish = IsSpecifiedBullish(dir); - ENUM_XPOIS mTT = - isDirBullish - ? X_POI_BULLISH_FVG - : X_POI_BEARISH_FVG; - - // - ENUM_X_PRICE startPrice = isDirBullish - ? X_PRICE_HIGH - : X_PRICE_LOW; - ENUM_X_PRICE endPrice = isDirBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - result = InitTwoBarZone( - startBar, - endBar, - mTT, - startPrice, - endPrice // - ); - if (!result) - { - return result; - } - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Check is Bullish ... - * - * @return ( bool ) - */ - bool IsBullish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_BULLISH_FVG; - - // - return result; - } - - /** - * Check is Bearish ... - * - * @return ( bool ) - */ - bool IsBearish() - { - // - bool result = false; - - // - result = IsValid() && - Type() == X_POI_BEARISH_FVG; - - // - return result; - } - - ENUM_X_DIRECTION GetDirection() - { - // - ENUM_X_DIRECTION result = X_DIRECTION_NONE; - - // - if (!IsValid()) - { - return result; - } - - // - result = - IsBullish() - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - return result; - } - - // - // Overrides ... - - bool IsValid() override - { - // - bool result = false; - - // - result = IsValidTwoBarZone() && - (mType == X_POI_BULLISH_FVG || - mType == X_POI_BEARISH_FVG); - - // - return result; - } - - // - protected: - // - - // - private: - // - - // -}; - -// -// Ticks Zones ... - -// -class XCTickZone : public CObject -{ - // - // Public ... - public: - // - // Props ... - string symbol; - ENUM_TIMEFRAMES period; - - // - double high; - double low; - int ticks; - double percent; - - // - ulong volume; - double volumePercent; - - // - // Compare Two Zone With Each Other ... - virtual int Compare( - const CObject *node, - const int mode = 0 // - ) const - { - // - const XCTickZone *other = (XCTickZone *)node; - - // - return other.ticks - ticks; - } - - // - bool IsValid() - { - // - bool result = false; - - // - result = high > 0 && - low > 0 && - high > low && - ticks > 0 && - percent > 0; - - // - return result; - } - - // - // Protected ... - protected: - // - // Private ... - private: - // -}; - -// -class XCTicksZone : public XCTwoBarZone -{ - // - public: - // - - // - // Constructor ... - void XCTicksZone() - { - Default(); - } - - // - // Deconstructor ... - void ~XCTicksZone() - { - } - - // - // Getter(s) / Setter(s) ... - - /** - * Get Number of Ticks Levels ... - * - * @return ( int ) - */ - int Levels() - { - return mLevels; - } - - /** - * Set Number of Ticks Levels ... - * - * @return ( int ) - */ - void Levels(int value) - { - // - if (value < 2) - { - value = 2; - } - - // - mLevels = value; - } - - /** - * Apply Default Config ... - */ - virtual void Default() - { - // - Levels(10); - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @param startBar: XOHCL instance ... - * @param endBar: XOHCL instance ... - * - * @return ( bool ) - */ - bool Init( - XOHCL &startBar, - XOHCL &endBar, - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - bool result = false; - - // - result = endBar.IsValid() && - startBar.IsValid(); - if (!result) - { - return result; - } - - // - if (!IsSpecifiedValid(forPeriod)) - { - forPeriod = endBar.period; - } - - // - // Calculate Start and End Time ... - datetime from = startBar.time; - datetime to = endBar.time; - ulong fromM = ((ulong)to * 1000); - ulong toM = ((ulong)from * 1000); - - // - // Symbol and Period ... - string symbol = startBar.symbol; - ENUM_TIMEFRAMES period = startBar.period; - - // - // Prepare Zones Array ... - mZones.Clear(); - - // - // Retrieve Ticks between Times ... - SpecificClean(mTicks); - int res = CopyTicksRange( - symbol, - mTicks, - COPY_TICKS_ALL, - fromM, - toM // - ); - - // - // Ticks Volumes ... - int ticksVolumeCount = CopyTickVolume( - symbol, - forPeriod, - from, - to, - mTickVolumes // - ); - if (IsValidSize(ticksVolumeCount)) - { - // - mVolumes = 0; - for (int i = 0; i < ticksVolumeCount; i++) - { - mVolumes += mTickVolumes[i]; - } - } - - // - // Retrieve Highs ... - SpecificClean(mHighs); - CopyHigh( - symbol, - period, - from, - to, - mHighs // - ); - - // - // Retrieve Lows ... - SpecificClean(mLows); - CopyLow( - symbol, - period, - from, - to, - mLows // - ); - - // - // Find Highest Value in Range ... - int highIDX = ArrayMaximum(mHighs); - mRangeHigh = mHighs[highIDX]; - - // - // Find Lowest Value in Range ... - int lowIDX = ArrayMinimum(mLows); - mRangeLow = mLows[lowIDX]; - - // - datetime mTimes[]; - CopyTime( - symbol, - period, - from, - to, - mTimes // - ); - mRangeHighTime = mTimes[highIDX]; - mRangeLowTime = mTimes[lowIDX]; - - // - double mRangeSize = mRangeHigh - mRangeLow; - - // - // Create Zones ... - for (int i = 0; i < Levels(); i++) - { - // - // Instance a New Zone ... - XCTickZone *iZone = new XCTickZone(); - - // - iZone.symbol = symbol; - iZone.period = period; - - // - // Calculate Each Zones High / Low based on Range ... - double iH = mRangeHigh - mRangeSize * i / Levels(); - double iL = mRangeHigh - mRangeSize * (i + 1) / Levels(); - - // - // Set Zone High Low Properties ... - iZone.low = iL; - iZone.high = iH; - - // - // Add Zone to Zone Array Objects ... - mZones.Add(iZone); - } - - // - // Calculate Each Zone Ticks ... - int ticksCount = ArraySize(mTicks); - for (int i = 0; i < ticksCount; i++) - { - // - // Retrieve Tick ... - MqlTick iTick = mTicks[i]; - - // - // Loop through Zones ... - for (int j = 0; j < Levels(); j++) - { - // - // Rejrieve j indexed Zone Object ... - XCTickZone *jZone = mZones.At(j); - - // - bool isInRange = IsTickInZoneRange( - iTick, - jZone // - ); - if (isInRange) - { - // - jZone.ticks++; - break; - } - } - } - - // - // Calculating Zone Percents ... - for (int i = 0; i < Levels(); i++) - { - // - XCTickZone *iZone = mZones.At(i); - - // - double percent = CalculateZoneTickPercent(iZone); - iZone.percent = percent; - } - - // - // Sort Zones Based on Percents ... - mZones.Sort(); - - // - mUpper = mRangeHigh; - mLower = mRangeLow; - mType = X_POI_TICKS_ZONES; - mEndBar = endBar; - mStartBar = startBar; - From(endBar.time); - To(startBar.time); - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - // Try to Find Out PERIOD_1M times in each zone ... - datetime to1M = (datetime)((int)endBar.time + PeriodSeconds(period) - 60); - int to1MIndex = iBarShift( - symbol, - forPeriod, - to1M // - ); - int from1MIndex = iBarShift( - symbol, - forPeriod, - from // - ); - for (int i = from1MIndex; i > to1MIndex; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - symbol, - forPeriod, - i // - ); - if (!isInited) - { - continue; - } - ulong iVolume = iTickVolume( - symbol, - forPeriod, - i // - ); - - // - // Loop through Zones ... - for (int j = 0; j < Levels(); j++) - { - // - XCTickZone *jZone = mZones.At(j); - if (!jZone.IsValid()) - { - continue; - } - - // - // Check iBar is Inside jZone ... - bool isIBarInside = - iBar.GetUp() < jZone.high && - iBar.GetDown() > jZone.low; - // iBar.low < jZone.high || - // iBar.high > jZone.low; - if (isIBarInside) - { - jZone.volume += iVolume; - } - } - } - - // - // Calculate Volume Percent ... - for (int i = 0; i < Levels(); i++) - { - // - XCTickZone *iZone = mZones.At(i); - - // - if (mVolumes > 0) - { - iZone.volumePercent = (double)(iZone.volume * 100 / mVolumes); - } - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Retrieve Zones Count ... - * - * @return ( int ) - */ - int Count() - { - return mZones.Total(); - } - - /** - * Retrieve Specified Sorted Zones ... - * - * @param index: Integer ... - * - * @return ( XCTickZone * ) - */ - XCTickZone *GetZone(int index) - { - // - if (!IsValidIndex(index)) - { - return NULL; - } - - // - return mZones.At(index); - } - - /** - * Calculate Liquidity Percent for Specified Direction ... - * - * @param forDirection: ENUM_X_DIRECTION member, Specified Liquidity ... - * @param price: Double, Specified Price ... - * - * @return ( double ) - */ - double CalculateLiquidityPercent( - ENUM_X_DIRECTION forDirection, - double price // - ) - { - // - double result = 0; - - // - int count = Count(); - if (price <= 0 || - !IsValid() || - !IsValidSize(count) || - forDirection == X_DIRECTION_ALL || - forDirection == X_DIRECTION_NONE) - { - return result; - } - - // - bool isBullish = forDirection == X_DIRECTION_BULLISH; - - // - for (int i = 0; i < count; i++) - { - // - XCTickZone *iZone = GetZone(i); - - // - if (iZone.IsValid()) - { - // - result += !isBullish && - price > iZone.high - ? iZone.percent - : isBullish && - price < iZone.low - ? iZone.percent - : 0; - } - } - - // - return result; - } - - // - // Overrides ... - bool IsValid() override - { - // - bool result = false; - - // - result = - IsValidFrom() && - IsValidTwoBarZone() && - Levels() > 0 && - mZones.Total() == Levels() && - mRangeHigh > 0 && - mRangeLow > 0; - - // - return result; - } - - // - bool GetMaxTickZone(XCTickZone *&zone) - { - // - bool result = false; - - // - zone = NULL; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int count = Count(); - for (int i = 0; i < count; i++) - { - // - XCTickZone *iZone = GetZone(i); - - // - bool canSet = - zone == NULL - ? true - : zone.ticks < iZone.ticks - ? true - : false; - if (canSet) - { - zone = iZone; - } - - // - ZeroMemory(iZone); - } - - // - result = zone != NULL && - zone.IsValid(); - - // - return result; - } - - // - bool GetMinTickZone(XCTickZone *&zone) - { - // - bool result = false; - - // - zone = NULL; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int count = Count(); - for (int i = 0; i < count; i++) - { - // - XCTickZone *iZone = GetZone(i); - - // - bool canSet = - zone == NULL - ? true - : zone.ticks > iZone.ticks - ? true - : false; - if (canSet) - { - zone = iZone; - } - - // - ZeroMemory(iZone); - } - - // - result = zone != NULL && - zone.IsValid(); - - // - return result; - } - - // - bool GetMaxVolumeZone(XCTickZone *&zone) - { - // - bool result = false; - - // - zone = NULL; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int count = Count(); - for (int i = 0; i < count; i++) - { - // - XCTickZone *iZone = GetZone(i); - - // - bool canSet = - zone == NULL - ? true - : zone.volume < iZone.volume - ? true - : false; - if (canSet) - { - zone = iZone; - } - - // - ZeroMemory(iZone); - } - - // - result = zone != NULL && - zone.IsValid(); - - // - return result; - } - - // - bool GetMinVolumeZone(XCTickZone *&zone) - { - // - bool result = false; - - // - zone = NULL; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int count = Count(); - for (int i = 0; i < count; i++) - { - // - XCTickZone *iZone = GetZone(i); - - // - bool canSet = - zone == NULL - ? true - : zone.volume > iZone.volume - ? true - : false; - if (canSet) - { - zone = iZone; - } - - // - ZeroMemory(iZone); - } - - // - result = zone != NULL && - zone.IsValid(); - - // - return result; - } - - // - protected: - // - - // - private: - // - // Props ... - - // - MqlTick mTicks[]; - double mHighs[]; - double mLows[]; - ulong mVolumes; - ulong mTickVolumes[]; - double mRangeHigh; - datetime mRangeHighTime; - double mRangeLow; - datetime mRangeLowTime; - - // - int mLevels; // Number of Ticks Levels ... - - // - CArrayObj mZones; - - /** - * Check a Tick is in a Zone rage or not ... - * - * @param tick: MqlTick instance ... - * @param zone: XCTickZone instance ... - * - * @return ( bool ) - */ - bool IsTickInZoneRange( - MqlTick &tick, - XCTickZone *zone // - ) - { - // - bool result = false; - - // - result = - // - tick.bid >= zone.low && - tick.bid <= zone.high - // - ; - - // - return result; - } - - /** - * Calculate Zone Tick Percent ... - * - * @param zone: XCTickZone instance ... - * @param normalizationDigits: Integer ... - * - * @return ( double ) - */ - double CalculateZoneTickPercent( - XCTickZone *zone, - int normalizationDigits = 2 // - ) - { - // - double result = 0; - - // - if (normalizationDigits < 2 || normalizationDigits > 5) - { - normalizationDigits = 2; - } - - // - int ticksCount = ArraySize(mTicks); - if (ticksCount <= 0) - { - return result; - } - - // - result = (double)zone.ticks / ticksCount * 100; - result = NormalizeDouble(result, normalizationDigits); - - // - return result; - } - - // -}; - -// -// Trading Day ... -class XCDay : public XCFromToZone -{ - // - public: - // - - // - // Constructor ... - void XCDay() - { - } - - // - // Deconstructor ... - void ~XCDay() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @return ( bool ) - */ - bool Init() - { - // - bool result = false; - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - // - protected: - // - - // - private: - // - - // -}; - -// -// Trading Session ... -class XCSession : public XCFromToZone -{ - // - public: - // - - // - // Constructor ... - void XCSession() - { - } - - // - // Deconstructor ... - void ~XCSession() - { - } - - // - // Tools ... - - /** - * Initialize POI ... - * - * @return ( bool ) - */ - bool Init() - { - // - bool result = false; - - // - result = IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - // Overrides ... - - // - protected: - // - - // - private: - // - - // -}; - -// - -template -bool ToBox( - T *&source[], - XBoxZone &dest[] // -) -{ - // - bool result = false; - - // - Clean(dest); - - // - int count = ArraySize(source); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T *item = source[i]; - - // - if (item != NULL) - { - // - XBoxZone iBox; - bool hasBox = ToBox( - iBox, - item // - ); - - // - if (hasBox) - { - // - AddRef( - iBox, - dest // - ); - } - } - } - - // - int destCount = ArraySize(dest); - result = IsValidSize(destCount); - - // - return result; -} - -template -int GetOldest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetOldest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetYoungest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetYoungest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetLowest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetLowest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetHighest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetHighest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -bool IsSame( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = sourceBox.IsSameAs(destBox); - - // - return result; -} - -template -bool IsBelow( - T *source, - T *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxBelow( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsAbove( - T *source, - T *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxAbove( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsInside( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInside( - sourceBox, - destBox // - ); - - // - return result; -} - -template -bool IsInsideOr( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInsideOr( - sourceBox, - destBox // - ); - - // - return result; -} - -template -bool FindIndex( - int &index, - T *item, - T *&items[] // -) -{ - // - bool result = false; - - // - index = -1; - - // - XBoxZone itemBox; - result = ToBox( - itemBox, - item // - ); - if (!result) - { - return result; - } - - // - XBoxZone itemsBox[]; - result = ToBox( - items, - itemsBox // - ); - if (!result) - { - return result; - } - - // - result = FindBoxIndex( - index, - itemBox, - itemsBox // - ); - - // - return result; -} - -template -bool IsInside( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsInsideBox( - value, - sourceBox // - ); - - // - return result; -} - -template -bool IsAbove( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsAboveBox( - value, - sourceBox // - ); - - // - return result; -} - -template -bool IsBelow( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsBelowBox( - value, - sourceBox // - ); - - // - return result; -} - -// -// -// - -// -template -void SortZones( - T *&source[], - ENUM_X_DIRECTION forDir, - bool ignoreInside = true // -) -{ - // - int idx = -1; - int count = 0; - bool has = false; - - // - has = HasDirection(forDir); - if (!has) - { - return; - } - - // - bool isBullish = IsBullish(forDir); - - // - count = ArraySize(source); - has = IsValidSize(count); - if (!has) - { - return; - } - - // - T *tmpItems[]; - T *last = NULL; - bool hasLast = false; - while (HasChild(source)) - { - // - if (!hasLast) - { - // - idx = GetOldest(source); - hasLast = IsValidIndex(idx); - if (hasLast) - { - // - last = source[idx]; - ArrayRemove( - source, - idx, - 1 // - ); - - // - Add( - last, - tmpItems // - ); - } - - // - count = ArraySize(source); - has = IsValidSize(count); - if (!has) - { - // - ZeroMemory(last); - break; - } - } - if (!hasLast) - { - // - ZeroMemory(last); - break; - } - - // - T *item = NULL; - idx = GetOldest(source); - has = IsValidIndex(idx); - if (!has) - { - // - ZeroMemory(last); - ZeroMemory(item); - break; - } - item = source[idx]; - ArrayRemove( - source, - idx, - 1 // - ); - - // - bool isAbove = IsAbove( - item, - last, - ignoreInside // - ); - - // - bool isBelow = IsBelow( - item, - last, - ignoreInside // - ); - - // - has = - isBullish - ? isAbove - : isBelow; - if (has) - { - // - Add( - item, - tmpItems // - ); - - // - last = item; - hasLast = item != NULL; - } - } - - // - Clean(source); - Copy( - tmpItems, - source // - ); - - // - Clean(tmpItems); -} - -/** - * Extract all Zones Which provided bar is Inside it ... - * - * @return ( int ) - */ -template -int ExtractInsideZones( - XOHCL &bar, // Bar ... - T *&zones[], // Source of Zones ... - T *&dest[] // Dest (all inside Zones) ... -) -{ - // - int result = 0; - - // - Clean(dest); - - // - int count = ArraySize(zones); - bool isValid = bar.IsValid() && - IsValidSize(count); - if (!isValid) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T *iZone = zones[i]; - - // - bool isHighInside = IsInside( - bar.high, - iZone // - ); - - // - bool isLowInside = IsInside( - bar.low, - iZone // - ); - - // - bool isInside = - isLowInside && - isHighInside; - - // - if (isInside) - { - // - Add( - iZone, - dest // - ); - } - - // - ZeroMemory(iZone); - } - - // - result = ArraySize(dest); - - // - return result; -} - -/** - * Add Specific Item into a Collection Reference only if it's not Exists ... - * - * @return ( bool ) - */ -template -bool AddIfNotExists( - T *item, - T *&items[] // -) -{ - // - bool result = false; - - // - result = item != NULL; - if (!result) - { - return result; - } - - // - int before = ArraySize(items); - - // - int idx = FindIndex( - item, - items // - ); - bool has = IsValidIndex(idx); - result = !has; - if (!result) - { - return result; - } - - // - Add( - item, - items // - ); - - // - int after = ArraySize(items); - - // - result = after > before; - - // - return result; -} - -/** - * Add items Collection reference Members into source Collection only if it's not Exists ...alignas - * @return ( int ) - */ -template -int AddIfNotExists( - T *&items[], - T *&sources[] // -) -{ - // - int result = 0; - - // - bool has = HasChild(items); - if (!has) - { - return result; - } - - // - int before = ArraySize(sources); - - // - int count = ArraySize(items); - for (int i = 0; i < count; i++) - { - // - has = AddIfNotExists( - items[i], - sources // - ); - } - - // - int after = ArraySize(sources); - - // - result = after > before; - - // - return result; -} - -/** - * Update to Time of Specifiex Collection ... - * - * @param items: XOBFVG instance Collection ... - * @param value: datetime ... - */ -template -void SpecifiedUpdateTo( - T *&items[], - datetime value = NULL // -) -{ - // - value = NormalizeTime(value); - - // - int count = ArraySize(items); - bool has = HasChild(items); - if (!has) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - items[i].To(value); - } -} - -/** - * Check a Box is Used or not ... - * - * @param box: XBoxZone instance Reference ... - * @param fromIndex: int ... - * @param toIndex: int - * @param forPeriod: Specified Period ... - * - * @return ( bool ) - */ -bool IsBoxUsed( - XBoxZone &box, - int fromIndex, - int toIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - if (toIndex < 0) - { - toIndex = 0; - } - - // - result = - // - box.IsValid() && - fromIndex > 0 && - fromIndex > toIndex - // - ; - if (!result) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - ENUM_X_DIRECTION forDir = box.dir; - bool isBullish = IsBullish(forDir); - - // - bool isTouched = false; - for (int i = fromIndex; i >= toIndex; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - box.symbol, - forPeriod, - i // - ); - - // - isTouched = - isInited && - (isBullish - ? iBar.low > box.upper - : iBar.high < box.lower); - if (!isTouched) - { - continue; - } - - // - iBar.Clean(); - break; - } - - // - result = isTouched; - - // - return result; -} - -/** - * Validate Box ... - * - * @param box: XBoxZone instance ... - * @param barIndex: int, Current Bar Index ... - * @param forPeriod: Testing Period ... - * - * @return ( bool ) - */ -bool IsBoxValid( - XBoxZone &box, - int barIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - int toIndex = iBarShift( - box.symbol, - forPeriod, - box.to // - ); - result = IsValidIndex(toIndex); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool isBullish = box.IsBullish(); - for (int i = barIndex; i < toIndex; i++) - { - // - result = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!result) - { - break; - } - - // - result = - isBullish - ? iBar.low > box.upper - : iBar.high < box.lower; - if (!result) - { - break; - } - - // - iBar.Clean(); - } - - // - iBar.Clean(); - - // - return result; -} - -/** - * Check Box Breaked ... - * - * @param box: XBoxZone instance ... - * @param barIndex: int, Current Bar Index ... - * @param forPeriod: Testing Period ... - * - * @return ( bool ) - */ -bool IsBoxBreaked( - XBoxZone &box, - int barIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - int toIndex = iBarShift( - box.symbol, - forPeriod, - box.to // - ); - result = IsValidIndex(toIndex); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool isBullish = box.IsBullish(); - for (int i = barIndex; i < toIndex; i++) - { - // - result = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!result) - { - break; - } - - // - result = - isBullish - ? iBar.high < box.lower - : iBar.low > box.upper; - if (!result) - { - break; - } - - // - iBar.Clean(); - } - - // - iBar.Clean(); - - // - return result; -} - -/** - * Check a Box is Breaked or not ... - * - * @param box: XBoxZone instance Reference ... - * @param fromIndex: int ... - * @param toIndex: int - * @param forPeriod: Specified Period ... - * - * @return ( bool ) - */ -bool IsBoxBreaked( - XBoxZone &box, - int fromIndex, - int toIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - if (toIndex < 0) - { - toIndex = 0; - } - - // - result = - // - box.IsValid() && - fromIndex > 0 && - fromIndex > toIndex - // - ; - if (!result) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - ENUM_X_DIRECTION forDir = box.dir; - bool isBullish = IsBullish(forDir); - - // - bool isBreaked = false; - for (int i = fromIndex; i >= toIndex; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - box.symbol, - forPeriod, - i // - ); - - // - isBreaked = - isInited && - (isBullish - ? iBar.high <= box.lower - : iBar.low >= box.upper); - if (!isBreaked) - { - continue; - } - - // - iBar.Clean(); - break; - } - - // - result = isBreaked; - - // - return result; -} - -/** - * Check a BaxHas Valid Place for Specified Bar ... - * - * @param bar: XOHCL instance reference, Specified Bar ... - * #param box: XBoxZone instance reference, Specified Box ... - * - * @return ( bool ) - */ -bool IsBoxPlaceValidForBar( - XOHCL &bar, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = bar.IsValid() && - box.IsValid(); - if (!result) - { - return result; - } - - // - result = - box.IsBullish() - ? bar.low > box.upper - : bar.high < box.upper; - - // - return result; -} - -/** - * Check Source Box is Below Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param ignoreInside: bool ... - * - * @return ( bool ) - */ -bool IsBoxBelow( - XBoxZone &source, - XBoxZone &dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - if (!ignoreInside) - { - result = source.upper < dest.lower; - } - else - { - result = (source.upper < dest.lower || - source.upper >= dest.upper) && - source.lower < dest.lower; - } - - // - return result; -} - -/** - * Check Source Box is Above Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param ignoreInside: bool ... - * - * @return ( bool ) - */ -bool IsBoxAbove( - XBoxZone &source, - XBoxZone &dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - if (!ignoreInside) - { - result = source.lower > dest.upper; - } - else - { - result = (source.lower > dest.upper || - source.lower <= dest.upper) && - source.upper > dest.upper; - } - - // - return result; -} - -/** - * Check Source Box is Inside Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param forceSideOut: bool, force check Box has One Side Out ... - * @param ignoreSideOut: bool, Accept if source Box one Side is out of Dest Box ... - * - * @return ( bool ) - */ -bool IsBoxInside( - XBoxZone &source, - XBoxZone &dest, - bool forceSideOut = false, // - bool ignoreSideOut = true // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(dest.dir); - - // - if (!forceSideOut) - { - // - if (ignoreSideOut) - { - // - result = source.lower >= dest.lower && - source.upper <= dest.upper; - } - else - { - result = source.lower >= dest.lower || - source.upper <= dest.upper; - } - } - else - { - // - bool hasSideIn = - isBullish - ? source.lower >= dest.lower - : source.upper <= dest.upper; - bool hasSideOut = - isBullish - ? source.upper >= dest.upper - : source.lower <= dest.lower; - result = - hasSideIn && - hasSideOut; - } - - // - return result; -} - -/** - * Detect source BoX is Inside Dest Box or Have a Side Out on it ... - * - * @param source: XBoxZone instance, source box which checks by dest ... - * @param dest: XBoxZone instance, dest Box which compares source with it ... - * - * @return ( bool ) - */ -bool IsBoxInsideOr( - XBoxZone &source, - XBoxZone &dest, - bool forceInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - bool isInside = - source.upper <= dest.upper && - source.upper >= dest.lower && - source.lower >= dest.lower && - source.lower <= dest.upper; - bool isUpperInside = - source.upper <= dest.upper && - source.upper >= dest.lower; - bool isLowerInside = - source.lower >= dest.lower && - source.lower <= dest.upper; - - // - result = - forceInside - ? isInside - : (isInside || - isLowerInside || - isUpperInside); - - // - return result; -} - -/** - * Check Value is Inside Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsInsideBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value <= box.upper && - value >= box.lower; - - // - return result; -} - -/** - * Check Bar is Inside Specified Box ... - * - * @param bar: XOHCL instance reference, Specified Bar ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsInsideBox( - XOHCL &bar, - XBoxZone &box // -) -{ - // - bool result = false; - - // - // Validate Args ... - result = bar.IsValid() && - box.IsValid(); - if (!result) - { - return result; - } - - // - result = - bar.close <= box.upper && - bar.close >= box.lower; - - // - return result; -} - -/** - * Check Value is Above Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsAboveBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value > box.upper; - - // - return result; -} - -/** - * Check Value is Below Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsBelowBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value < box.lower; - - // - return result; -} - -/** - * Find an Inside Box of source in a Collection ... - * - * @param index: int, Founded Index ... - * @param source: XBoxZone instance ... - * @param dest: XBoxZone instance Collection ... - * - * @return ( bool ) - */ -bool HasInsideBox( - int &index, - XBoxZone &source, - XBoxZone &dest[] // -) -{ - // - bool result = false; - - // - index = -1; - - // - result = source.IsValid() && - HasChild(dest); - - // - int count = ArraySize(dest); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = dest[i]; - - // - bool isInside = !iBox.IsSameAs(source) && - IsBoxInsideOr( - iBox, - source // - ); - if (isInside) - { - // - index = i; - iBox.Clean(); - - // - break; - } - - // - iBox.Clean(); - } - - // - result = IsValidIndex(index); - - // - return result; -} - -///////////////////////////////////////////// - -// -// Analyse Bar Patterns ... -if (result && config.analyseBarPatterns) -{ - // - // Try to Detect Bars Analysis ... - int fromIndex = -1; - if (!IsXValid(fromTime)) - { - fromIndex = barIndex + config.loopback; - } - else - { - fromIndex = GetBarIndex( - symbol, - period, - fromTime // - ); - } - result = IsValidIndex(fromIndex); - if (result) - { - // - fromIndex = MathMin(fromIndex, barIndex + config.requiredPivots); - - // - for (int i = barIndex; i < fromIndex; i++) - { - // - tmpBar.Clean(); - tmpBarAnalysis.Clean(); - result = structure.bar.BarAt(i, tmpBar); - result = result && - AnalyseBarPatterns( - tmpBar, - tmpBarAnalysis, - config.barsAnalysisConfig // - ); - if (!result) - { - break; - } - - // - AddRef( - tmpBarAnalysis, - structure.barsAnalysis // - ); - } - } -} - -//////////////////////////////////////////////// - -/** - * Draw Specified Market Structure Based on Given Configs ... - * - * @param structure: XFIMAMarketStructure, reference to Provide Specifid Market Structure ... - * @param config: XFIMAMarketStructureDrawerConfig, reference to Provide Drawing Configurations ... - */ -void DrawMarketStructure( - XFIMAMarketStructure &structure, - XFIMAMarketStructureDrawerConfig &config // -) -{ - // - // Validate ... - bool has = structure.IsValid(); - if (!has) - { - return; - } - - // - // PV Analysis ... - if (config.drawPVAnalysis) - { - // - has = structure.pvAnalysis.IsValid(); - if (has) - { - // - DrawPivotAnalysis( - structure.pvAnalysis, - config.pivotAnalysisDrawConfig // - ); - } - } - - // - // ZG Analysis ... - if (config.drawZGAnalysis) - { - // - has = structure.zgAnalysis.IsValid(); - if (has) - { - // - DrawPivotAnalysis( - structure.zgAnalysis, - config.pivotAnalysisDrawConfig // - ); - } - } - - // - // Bars Analysis ... - if (config.drawBarsAnalysis) - { - // - int count = ArraySize(structure.barsAnalysis); - has = IsValidSize(count); - if (has) - { - // - for (int i = 0; i < count; i++) - { - // - DrawPatternAnalysis( - structure.barsAnalysis[i], - config.barAnalysisDrawConfig // - ); - } - } - } -} diff --git a/Documents/BKP/x-fima.pattern.detection.bkp.mq5 b/Documents/BKP/x-fima.pattern.detection.bkp.mq5 deleted file mode 100644 index d673406c..00000000 --- a/Documents/BKP/x-fima.pattern.detection.bkp.mq5 +++ /dev/null @@ -1,699 +0,0 @@ - -/** - * Check Market Conditions for Pattern Detection ... - */ -void DetectPatterns() -{ - // - if (!eaIsNewBar) - { - return; - } - - // - // Initialize 1 Indexed Bar ... - XOHCL cBar; - bool has = cBar.Init( - _Symbol, - _Period, - 1 // - ); - if (!has) - { - return; - } - - // - // Do Analysis ... - - // - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Define Detection Flags ... - - // - bool detectPinned = false; - bool detectMomentum = false; - bool detectEngulfed = false; - bool detectTrueGaped = false; - - // - bool detectStarPattern = false; - bool detectFlagPattern = false; - bool detectRisingPattern = false; - bool detectPiercingPattern = false; - bool detectSignalKeyBarPattern = false; - - // - bool detectSwingTrend = false; - bool detectSwingTrendBreakes = false; - - // - bool detectSupports = false; - bool detectResistance = false; - - // - // XFIMA Patetrns ... - bool detectFIMAPatterns = true; - // - bool detectFIMAPVPatterns = false; - bool detectFIMAMAPatterns = false; - bool detectFIMASARPatterns = false; - bool detectFIMAZigZagPatterns = false; - // - bool analyseFIMAPVPivots = true; - bool analyseFIMAMAPivots = true; - bool analyseFIMASARPivots = true; - bool analyseFIMAZigZagPivots = true; - - // - // Required Pivots ... - int numberOfRequiredPivots = 15; - - // - // Checking Momentum Bar ... - if (detectMomentum) - { - // - bool isMomentum = fima2Signaller.poiDetector.IsMomentumBar( - cBar, - iDir // - ); - bool isBullishMomentum = isMomentum && - IsSpecifiedBullish(iDir); - bool isBearishMomentum = isMomentum && - IsSpecifiedBearish(iDir); - if (isMomentum) - { - Print(ToXString(iDir), " Momentum Bar: ", cBar.time); - } - } - - // - // Checking Engulfed Bar ... - if (detectEngulfed) - { - // - bool isEngulfed = fima2Signaller.poiDetector.IsEngulfedBar( - cBar, - iDir // - ); - bool isBullishEngulfed = isEngulfed && - IsSpecifiedBullish(iDir); - bool isBearishEngulfed = isEngulfed && - IsSpecifiedBearish(iDir); - if (isEngulfed) - { - Print(ToXString(iDir), " Engulfed Bar: ", cBar.time); - } - } - - // - // Checking TruGaped Bar ... - if (detectTrueGaped) - { - // - bool isTrueGaped = fima2Signaller.poiDetector.IsTrueGapedBar( - cBar, - iDir // - ); - bool isBullishTrueGaped = isTrueGaped && - IsSpecifiedBullish(iDir); - bool isBearishTrueGaped = isTrueGaped && - IsSpecifiedBearish(iDir); - if (isTrueGaped) - { - Print(ToXString(iDir), " TrueGapped Bar: ", cBar.time); - } - } - - // - // Checking Pinned Bar ... - if (detectPinned) - { - bool isPinned = fima2Signaller.poiDetector.IsPinnedBar( - cBar, - iDir // - ); - bool isBullishPinned = isPinned && - IsSpecifiedBullish(iDir); - bool isBearishPinned = isPinned && - IsSpecifiedBearish(iDir); - if (isPinned) - { - Print(ToXString(iDir), " Pinned Bar: ", cBar.time); - } - } - - // - // Checking Star Pattern ... - if (detectStarPattern) - { - bool isStarPattern = fima2Signaller.poiDetector.IsStartPattern( - cBar, - iDir // - ); - bool isBullishStarPattern = isStarPattern && - IsSpecifiedBullish(iDir); - bool isBearishStarPattern = isStarPattern && - IsSpecifiedBearish(iDir); - if (isStarPattern) - { - Print(ToXString(iDir), " Star Pattern: ", cBar.time); - } - } - - // - // Checking Piercing Pattern ... - if (detectPiercingPattern) - { - // - bool isPiercingPattern = fima2Signaller.poiDetector.IsPiercingPattern( - cBar, - iDir // - ); - bool isBullishPiercingPattern = isPiercingPattern && - IsSpecifiedBullish(iDir); - bool isBearishPiercingPattern = isPiercingPattern && - IsSpecifiedBearish(iDir); - if (isPiercingPattern) - { - Print(ToXString(iDir), " Piercing Pattern: ", cBar.time); - } - } - - // - // Checking Rising Pattern ... - if (detectRisingPattern) - { - // - bool isRisingPattern = fima2Signaller.poiDetector.IsRisingPattern( - cBar, - iDir // - ); - bool isBullishRisingPattern = isRisingPattern && - IsSpecifiedBullish(iDir); - bool isBearishRisingPattern = isRisingPattern && - IsSpecifiedBearish(iDir); - if (isRisingPattern) - { - Print(ToXString(iDir), " Rising Pattern: ", cBar.time); - } - } - - // - // Checking Flag Pattern ... - if (detectFlagPattern) - { - // - XOHCL swingBar; - bool isFlagPattern = fima2Signaller.poiDetector.IsFlagPattern( - cBar, - iDir, - swingBar // - ); - bool isBullishFlagPattern = isFlagPattern && - IsSpecifiedBullish(iDir); - bool isBearishFlagPattern = isFlagPattern && - IsSpecifiedBearish(iDir); - if (isFlagPattern) - { - Print(ToXString(iDir), " Flag Pattern: ", cBar.time, ", Swing: ", swingBar.time); - } - swingBar.Clean(); - } - - // - // Detect SignalKey Bar Pattern ... - if (detectSignalKeyBarPattern) - { - // - bool isSignalKeyBar = fima2Signaller.poiDetector.IsSignalKeyBarPattern( - cBar, - iDir // - ); - bool isBullishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBullish(iDir); - bool isBearishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBearish(iDir); - if (isSignalKeyBar) - { - Print(ToXString(iDir), " SignalKey Bar Pattern: ", cBar.time); - } - } - - // - // Detect Swing Trend ... - if (detectSwingTrend) - { - // - XOHCL swings[]; - bool hasSwingTrend = fima2Signaller.poiDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - Print(ToXString(iDir), " Swing Trend: ", cBar.time); - - // - CChartObjectTrend *iObj; - has = fima2Signaller.poiDrawer.DrawSwingTrend( - swings, - iDir, - iObj, - true // Ray Right ... - ); - if (has) - { - eaDraws.Add(iObj); - } - } - SpecifiedClean(swings); - } - - // - // Swing Trend Breakes ... - if (detectSwingTrendBreakes) - { - // - XOHCL swings[]; - bool hasSwingTrend = fima2Signaller.poiDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - if (!HasDirection(trendDir)) - { - trendDir = iDir; - } - } - - // - // Breaked Detection ... - if (trendDir != iDir) - { - // - Print("Trend Dir Breaked to: ", ToXString(iDir)); - trendDir = iDir; - } - - // - SpecifiedClean(swings); - } - - // - // Detect Supports ... - if (detectSupports) - { - // - XOHCL support; - bool hasSupport = fima2Signaller.poiDetector.HasSupport( - cBar, - support // - ); - if (hasSupport) - { - // - XBoxZone supportBox; - has = ToSupportBox(support, supportBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = fima2Signaller.poiDrawer.DrawBox( - supportBox, - iObj // - ); - if (has) - { - eaDraws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - supportBox.Clean(); - } - support.Clean(); - } - - // - // Detect Resistance ... - if (detectResistance) - { - // - XOHCL resistance; - bool hasResistance = fima2Signaller.poiDetector.HasResistance( - cBar, - resistance // - ); - if (hasResistance) - { - // - XBoxZone resistanceBox; - has = ToResistanceBox(resistance, resistanceBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = fima2Signaller.poiDrawer.DrawBox( - resistanceBox, - iObj // - ); - if (has) - { - eaDraws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - resistanceBox.Clean(); - } - resistance.Clean(); - } - - // - // Detecting FIMA Patterns ... - if (detectFIMAPatterns) - { - // - // Check For PV Pivots ... - if (detectFIMAPVPatterns) - { - // - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractPVPivots( - pivots, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500, // Max Allowed Loopback ... - 10 // Validation Length ... - ); - has = IsValidSize(pivotsCount); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - int drawnPivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - has = IsValidSize(drawnPivotsCount); - if (has) - { - // - AddObjects( - drawnPivots, - eaDraws // - ); - - // - // Print("Pivots Extracted ..."); - } - - // - ZeroMemory(drawnPivots); - } - } - - // - // Check for MA Patterns ... - if (detectFIMAMAPatterns) - { - // - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractMAPivots( - pivots, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500, // Max Allowed Loopback ... - 0 // Validation Length ... - ); - has = IsValidSize(pivotsCount); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - int drawnPivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - has = IsValidSize(drawnPivotsCount); - if (has) - { - // - AddObjects( - drawnPivots, - eaDraws // - ); - - // - // Print("Pivots Extracted ..."); - } - - // - ZeroMemory(drawnPivots); - } - } - - // - // Check for SAR Pivots ... - if (detectFIMASARPatterns) - { - // - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractSARPivots( - pivots, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500 // Max Allowed Loopback ... - ); - has = IsValidSize(pivotsCount); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - int drawnPivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - has = IsValidSize(drawnPivotsCount); - if (has) - { - // - AddObjects( - drawnPivots, - eaDraws // - ); - - // - // Print("Pivots Extracted ..."); - } - - // - ZeroMemory(drawnPivots); - } - } - - // - // Check for ZigZag Pivots ... - if (detectFIMAZigZagPatterns) - { - // - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractZigZagPivots( - pivots, - cBar.Index(), - numberOfRequiredPivots, - 1500 // - ); - has = IsValidSize(pivotsCount); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - int drawnPivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - has = IsValidSize(drawnPivotsCount); - if (has) - { - // - AddObjects( - drawnPivots, - eaDraws // - ); - - // - // Print("Pivots Extracted ..."); - } - - // - ZeroMemory(drawnPivots); - } - } - - // - // Analysers ... - - // - // Analyse Based on PV ... - if (analyseFIMAPVPivots) - { - // - XPivotAnalysis analysis; - has = fima2Signaller.poiDetector.AnalysePVPivots( - analysis, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500, // Max Allowed Loopback ... - 10 // Validation Length ... - ); - if (has) - { - // - // Draw Analysis ... - DestroyObject(pvAnalysisObject); - has = fima2Signaller.poiDrawer.DrawPivotAnalysis( - analysis, - pvAnalysisObject, - true // Draw Pivots ... - ); - if (has) - { - // - // eaDraws.Add(iObj); - - // - // Print("FIMA PV Pivots Analysed ..."); - } - } - } - - // - // Analyse Based on MA ... - if (analyseFIMAMAPivots) - { - // - XPivotAnalysis analysis; - has = fima2Signaller.poiDetector.AnalyseMAPivots( - analysis, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500, // Max Allowed Loopback ... - 0 // Validation Length ... - ); - if (has) - { - // - // Draw Analysis ... - DestroyObject(maAnalysisObject); - has = fima2Signaller.poiDrawer.DrawPivotAnalysis( - analysis, - maAnalysisObject, - true // Draw Pivots ... - ); - if (has) - { - // - // eaDraws.Add(iObj); - - // - // Print("FIMA MA Pivots Analysed ..."); - } - } - } - - // - // Analyse Based on SAR ... - if (analyseFIMASARPivots) - { - // - XPivotAnalysis analysis; - has = fima2Signaller.poiDetector.AnalyseSARPivots( - analysis, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500 // Max Allowed Loopback ... - ); - if (has) - { - // - // Draw Analysis ... - DestroyObject(sarAnalysisObject); - has = fima2Signaller.poiDrawer.DrawPivotAnalysis( - analysis, - sarAnalysisObject, - true // Draw Pivots ... - ); - if (has) - { - // - // eaDraws.Add(iObj); - - // - // Print("FIMA Sar Pivots Analysed ..."); - } - } - } - - // - // Analyse Based on ZigZag ... - if (analyseFIMAZigZagPivots) - { - // - XPivotAnalysis analysis; - has = fima2Signaller.poiDetector.AnalyseZigZagPivots( - analysis, // Result ... - cBar.Index(), // Bar Index ... - numberOfRequiredPivots, // Required Number of Pivots ... - 1500 // Max Allowed Loopback ... - ); - if (has) - { - // - // Draw Analysis ... - DestroyObject(zigzagAnalysisObject); - has = fima2Signaller.poiDrawer.DrawPivotAnalysis( - analysis, - zigzagAnalysisObject, - true // Draw Pivots ... - ); - if (has) - { - // - // eaDraws.Add(iObj); - - // - // Print("FIMA ZigZag Pivots Analysed ..."); - } - } - } - } - - // - cBar.Clean(); -} diff --git a/Documents/BKP/x-saherelm.x-cobject.class copy.mq5 b/Documents/BKP/x-saherelm.x-cobject.class copy.mq5 deleted file mode 100644 index e2e7bc1b..00000000 --- a/Documents/BKP/x-saherelm.x-cobject.class copy.mq5 +++ /dev/null @@ -1,3787 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XChartObjects -// Description: provides all require Chart Objects ... -// -// -// 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 "../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" -#include "../Libraries/x-saherelm.x-trade.lib.mq5" - -// -#include -#include -#include -#include -#include -#include - -// -// Definitions ... - -enum ENUM_XCHARTOBJECTS -{ - // - // Global ... - X_EMPTY_OBJ = 7860, // Empty - X_BOX_OBJ = 7861, // XBox - X_BAR_ARROW_OBJ = 7862, // XBarArrow - X_SIGNAL_OBJ = 8860, // XSignal - X_OHCL_OBJ = 8863, // XBar - X_RR_OBJ = 8864, // XRR - X_PIVOT_OBJ = 8865, // XPivot - X_POSITION_OBJ = 8866, // XPosition - // - // 9860 Custom Object ... -}; - -enum ENUM_X_CHART_IDS -{ - X_AT, // AT - X_TO, // TO - X_FROM, // FROM - X_UPPER, // UPPER - X_LOWER, // LOWER - X_ENTRY, // ENTRY - X_TARGET, // TARGET - X_SL, // SL - X_TP, // TP - X_BAR_H_SHW, // HSHW - X_BAR_BDY, // BODY - X_BAR_L_SHW, // LSHW -}; - -string ToString(ENUM_X_CHART_IDS value) -{ - // - string result = NULL; - - // - result = EnumToString(value); - - // - return result; -} - -string ToXString(ENUM_XCHARTOBJECTS value) -{ - // - return EnumToString(value); -} - -struct XPOIStyle -{ - // - // Properties ... - int width; // Width ... - color clr; // Color ... - bool fill; // Fill, Use in Rectangles ... - ENUM_LINE_STYLE style; // Line Style ... - - // - // Constructor ... - XPOIStyle() - { - Default(); - } - - // - // Tools ... - - // - // Cleanup Model ... - void Clean() - { - // - width = 1; - fill = false; - clr = CLR_NONE; - style = STYLE_SOLID; - - // - ZeroMemory(this); - } - - // - // Default Props ... - void Default() - { - // - width = 1; - fill = false; - clr = CLR_NONE; - style = STYLE_SOLID; - } -}; - -// -// Extensions ... - -/** - * Converts a XBoxZone struct to XSignal instance ... - * - * @param box: XBoxZone instance reference, provide source info ... - * @param signal: XSignal instance reference, holds prepared converted signal ... - * - * @return ( bool ) - */ -bool ToXSignal( - XBoxZone &box, - XSignal &signal, - double &rewardRatios[], - double additionalSL = 0 // -) -{ - // - bool result = false; - - // - signal.Clean(); - - // - result = box.IsValid() && - HasChild(rewardRatios); - if (!result) - { - return result; - } - - // - XOHCL entryBar; - int entryIDX = box.ToIndex(); - if (entryIDX > 0) - { - entryIDX--; - } - result = entryBar.Init( - box.symbol, - box.period, - entryIDX // - ); - if (!result) - { - // - entryBar.Clean(); - - // - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - ENUM_POSITION_TYPE iType = - isBullish - ? POSITION_TYPE_BUY - : POSITION_TYPE_SELL; - ENUM_X_POSITION_TYPES iXType = - isBullish - ? X_POSITION_TYPE_LONG - : X_POSITION_TYPE_SHORT; - - // - double points = GetPoints(box.symbol); - - // - double entry = - isBullish - ? box.upper - : box.lower; - entry = entryBar.open; - - // - double sl = - isBullish - ? box.lower - : box.upper; - if (additionalSL > 0) - { - // - sl = - isBullish - ? sl - additionalSL - : sl + additionalSL; - } - - // - double risk = MathAbs(entry - sl); - - // - double tp = 0; - - // - // Calculate Target ... - XTarget targets[]; - - // - double tmp[]; - int idx = -1; - XTarget iTarget; - bool has = false; - double iRatio = 0; - double iReward = 0; - double iRewardPrice = 0; - Copy( - rewardRatios, - tmp // - ); - while (HasChild(tmp)) - { - // - idx = -1; - iRatio = GetMaxWidthIndex( - tmp, - idx // - ); - - // - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - has = iRatio > 0; - - // - ArrayRemove( - tmp, - idx, - 1 // - ); - - // - bool canSetTP = tp <= 0; - - // - iReward = iRatio * risk; - - // - iRewardPrice = - isBullish - ? entry + iReward - : entry - iReward; - if (canSetTP) - { - tp = iRewardPrice; - } - else - { - // - iTarget.target = iRewardPrice; - AddRef( - iTarget, - targets // - ); - - // - iTarget.Clean(); - } - } - Clean(tmp); - - // - // Filling Signal ... - signal.tp = tp; - signal.sl = sl; - signal.type = iType; - signal.comment = ""; - signal.entry = entry; - signal.time = box.to; - signal.volume = 0.01; - signal.provider = box.type; - signal.symbol = box.symbol; - signal.period = box.period; - signal.mode = X_ORDER_MODE_MARKET; - - // - if (HasChild(targets)) - { - // - Copy( - targets, - signal.targets // - ); - } - - // - result = signal.IsValid(); - - // - // Cleanup Resources ... - - // - if (!result) - { - signal.Clean(); - } - - // - Clean(tmp); - Clean(targets); - iTarget.Clean(); - entryBar.Clean(); - - // - return result; -} - -/** - * Converts a Signal to Position ... - * - * @param signal: XSignal, reference to Specified Signal ... - * @param position: XPosition, reference to Generated Position ... - * @param magic: ulong, Specified Magic Number ... - * @param ticket: ulong, Specified Position Ticket ... - * - * @return ( bool ) - */ -bool ToXPosition( - XSignal &signal, - XPosition &position, - ulong magic = 0, - ulong ticket = 0 // -) -{ - // - bool result = false; - - // - // Prepare ... - position.Clean(); - - // - // Validate ... - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - // Normalize ... - - // - if (ticket <= 0) - { - // - if (signal.positionId > 0) - { - ticket = signal.positionId; - } - else - { - // - ticket = MathRand(); - signal.positionId = ticket; - } - } - signal.positionId = ticket; - - // - if (magic <= 0) - { - magic = MathRand(); - } - - // - // Filling Position ... - position.swap = 0; - position.profit = 0; - position.magic = magic; - position.commission = 0; - position.tp = signal.tp; - position.sl = signal.sl; - position.ticket = ticket; - position.type = signal.type; - position.price = signal.entry; - position.entry = signal.entry; - position.openAt = signal.time; - position.volume = signal.volume; - position.symbol = signal.symbol; - position.period = signal.period; - position.comment = signal.comment; - position.provider = signal.provider; - - // - result = position.IsValid(); - - // - // Cleanup Resources ... - if (!result) - { - position.Clean(); - } - - // - return result; -} - -/** - * Update Specified Position by Bar ... - * - * @param position: XPosition, reference to Specified Position ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ -bool XUpdatePosition( - XPosition &position, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = position.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL bar; - result = bar.Init( - position.symbol, - position.period, - barIndex // - ); - if (!result) - { - return result; - } - - // - double entryDiff = MathAbs(position.entry - position.price); - bool isLong = IsLong(position.type); - bool isInProfit = isLong - ? position.price > position.entry - : position.price < position.entry; - bool isTargeted = - isLong - ? position.price >= position.tp - : position.price <= position.tp; - bool isStoped = - isLong - ? position.price <= position.sl - : position.price >= position.sl; - result = !isTargeted && !isStoped; - if (!result) - { - return result; - } - - // - double spread = GetSpread(position.symbol); - position.price = bar.close + - (isLong - ? spread - : (-1 * spread)); - entryDiff = MathAbs(position.entry - position.price); - isInProfit = isLong - ? position.price > position.entry - : position.price < position.entry; - result = position.IsValid(); - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; -} - -// -// Implementation ... - -// -// Global Chart Objects ... - -/** - * Base Chart Object ... - **/ -class XCBaseObject : public CChartObject -{ - // - public: - // - - // - // Getter(s) / Setter(s) ... - - /** - * Get Object Specified Name ... - * - * @return ( string ) - */ - string ObjName() - { - return mObjName; - } - - /** - * Set Object Specified Name ... - * - * @param value: String ... - */ - void ObjName(string value) - { - // - Name(value); - mObjName = value; - } - - virtual string TypeString() - { - return ToXString(X_EMPTY_OBJ); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) const - { - return ((int)X_EMPTY_OBJ); - } - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - Detach(); - Delete(); - } - - // - private: - // - - // - // Props ... - string mObjName; // Object Specified Name ... - - // -}; - -/** - * Bar Arrow Object ... - **/ -class XCBarArrowObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param name: String, Specified Object ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param swing: XCSwing instance ... - * - * @return ( bool ) - */ - bool CreateByBar( - long chart_id, - string name, - int window, - int arrow, - XOHCL &bar, - ENUM_X_PRICE priceType, - double threshold = 5 // - ) - { - // - bool result = false; - - // - result = - // - bar.IsValid() && - IsValid(name) - // - ; - if (!result) - { - return result; - } - - // - datetime time = bar.time; - double price = bar.GetPrice(priceType); - - // - if (threshold > 0) - { - // - double thresholdPrice = threshold * GetPoints(bar.symbol); - if (priceType == X_PRICE_HIGH) - { - price += thresholdPrice; - } - else if (priceType == X_PRICE_LOW) - { - price -= thresholdPrice; - } - } - - // - result = mArrow.Create( - chart_id, - name, - window, - time, - price, - (char)arrow // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - mArrow.Detach(); - mArrow.Delete(); - - // - Detach(); - Delete(); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_BAR_ARROW_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_BAR_ARROW_OBJ); - } - - // - // Setter(s) ... - - /** - * Set Arrow Anchor ... - * - * @param value: ENUM_ARROW_ANCHOR member ... - */ - void ArrowAnchor(ENUM_ARROW_ANCHOR value) - { - mArrow.Anchor(value); - } - - /** - * Set Arrow Color ... - * - * @param value: Color ... - */ - void ArrowColor(color value) - { - mArrow.Color(value); - } - - /** - * Set Arrow Width ... - * - * @param value: Integer ... - */ - void ArrowWidth(int value) - { - mArrow.Width(value); - } - - // - private: - // - CChartObjectArrow mArrow; - - // -}; - -/** - * Signal Object ... - **/ -class XCSignalObject : public XCBaseObject -{ - // - public: - // - - // - // Constructor ... - void XCSignalObject() - { - } - - // - // Deconstructor ... - void ~XCSignalObject() - { - } - - /** - * Create a Signal Object on Chart ... - * - * @param chart_id: Long ... - * @param name: String ... - * @param window: Integer ... - * @param signal: XSignal instance ... - * @param length: int, Specified Length of Signal ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - const int window, - XSignal &signal, - int length = 3, - string prefix = NULL // - ) - { - // - bool result = false; - - // - length = NormalizeInt(length, 3); - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - string name = signal.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - int delay = (PeriodSeconds(signal.period) * length); - datetime time1 = (datetime)((int)signal.time - delay); - datetime time2 = (datetime)((int)signal.time + delay); - - // - // TP ... - string tpName = ToString(X_TP) + "_" + nameMD5; - result = mTPTrend.Create( - chart_id, - tpName, - window, - time1, - signal.tp, - time2, - signal.tp // - ); - if (!result) - { - return result; - } - - // - // SL ... - string slName = ToString(X_SL) + "_" + nameMD5; - result = mSLTrend.Create( - chart_id, - slName, - window, - time1, - signal.sl, - time2, - signal.sl // - ); - if (!result) - { - // - mTPTrend.Delete(); - return result; - } - - // - // TARGET ... - bool hasTargets = HasChild(signal.targets); - if (hasTargets) - { - // - int targetsCount = ArraySize(signal.targets); - for (int i = 0; i < targetsCount; i++) - { - // - string targetName = ToString(X_TARGET) + "_" + ToXString(i) + "_" + nameMD5; - CChartObjectTrend *mTargetTrend; - mTargetTrend = new CChartObjectTrend(); - result = mTargetTrend.Create( - chart_id, - targetName, - window, - time1, - signal.targets[i].target, - time2, - signal.targets[i].target // - ); - if (!result) - { - // - mTPTrend.Delete(); - mSLTrend.Delete(); - break; - } - - // - mTargetTrends.Add(mTargetTrend); - } - } - - // - // ENTRY ... - string entrName = ToString(X_ENTRY) + "_" + nameMD5; - result = mEntryTrend.Create( - chart_id, - entrName, - window, - time1, - signal.entry, - time2, - signal.entry // - ); - if (!result) - { - // - mTPTrend.Delete(); - mSLTrend.Delete(); - mTargetTrends.Clear(); - return result; - } - - // - // Set Object Name ... - ObjName(name); - - // - return result; - } - - // - // Virtual ... - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - mTPTrend.Detach(); - mTPTrend.Delete(); - mSLTrend.Detach(); - mSLTrend.Delete(); - mEntryTrend.Detach(); - mEntryTrend.Delete(); - - // - mTargetTrends.Clear(); - - // - Detach(); - Delete(); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_SIGNAL_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_SIGNAL_OBJ); - } - - // - // Setter(s) ... - - // - // TP ... - - /** - * Set TP Width ... - * - * @param value: Integer ... - */ - void TPWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mTPTrend.Width(value); - } - - /** - * Set TP Color ... - * - * @param value: Color ... - */ - void TPColor(color value) - { - mTPTrend.Color(value); - } - - /** - * Set TP Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void TPStyle(ENUM_LINE_STYLE value) - { - mTPTrend.Style(value); - } - - // - // SL ... - - /** - * Set SL Width ... - * - * @param value: Integer ... - */ - void SLWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSLTrend.Width(value); - } - - /** - * Set SL Color ... - * - * @param value: Color ... - */ - void SLColor(color value) - { - mSLTrend.Color(value); - } - - /** - * Set SL Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void SLStyle(ENUM_LINE_STYLE value) - { - mSLTrend.Style(value); - } - - // - // TARGET ... - - /** - * Set Target Width ... - * - * @param value: Integer ... - */ - void TargetWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Width(value); - } - } - - /** - * Set Target Color ... - * - * @param value: Color ... - */ - void TargetColor(color value) - { - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Color(value); - } - } - - /** - * Set Target Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void TargetStyle(ENUM_LINE_STYLE value) - { - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Style(value); - } - } - - // - // ENTRY ... - - /** - * Set Entry Width ... - * - * @param value: Integer ... - */ - void EntryWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mEntryTrend.Width(value); - } - - /** - * Set Entry Color ... - * - * @param value: Color ... - */ - void EntryColor(color value) - { - mEntryTrend.Color(value); - } - - /** - * Set Entry Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void EntryStyle(ENUM_LINE_STYLE value) - { - mEntryTrend.Style(value); - } - - // - private: - // - - // - CChartObjectTrend mTPTrend; - CChartObjectTrend mSLTrend; - CChartObjectTrend mEntryTrend; - CArrayObj mTargetTrends; -}; - -/** - * XRR Object ... - **/ -class XCRRObject : public XCSignalObject -{ - // - // Public ... - public: - // - // Constructor ... - bool CreateBoxRR( - long chart_id, - const int window, - XBoxZone &box, - double &rewardRatios[], - int length = 3, - string prefix = NULL // - ) - { - // - bool result = false; - - // - length = NormalizeInt(length, 3); - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - XSignal signal; - result = ToXSignal( - box, - signal, - rewardRatios // - ); - if (!result) - { - // - signal.Clean(); - - // - return result; - } - - // - result = Create( - chart_id, - window, - signal, - length, - prefix // - ); - - // - signal.Clean(); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_RR_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_RR_OBJ); - } -}; - -/** - * XOHCL Object ... - **/ -class XCOHCLObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param pivot: XPVPivot instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XOHCL &bar, - datetime to, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - IsValid(to); - if (!result) - { - return result; - } - - // - string name = bar.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - // High Shadow ... - string hShadowName = ToString(X_BAR_H_SHW) + "_" + nameMD5; - - // - result = mHighShadowRect.Create( - chart_id, - hShadowName, - window, - bar.time, - bar.high, - to, - bar.GetUp() // - ); - if (!result) - { - return result; - } - - // - // Body ... - string bodyName = ToString(X_BAR_BDY) + "_" + nameMD5; - - // - result = mBodyRect.Create( - chart_id, - bodyName, - window, - bar.time, - bar.GetUp(), - to, - bar.GetDown() // - ); - if (!result) - { - // - mHighShadowRect.Delete(); - mHighShadowRect.Detach(); - return result; - } - - // - // Low Shadow ... - string lShadowName = ToString(X_BAR_L_SHW) + "_" + nameMD5; - - // - result = mLowShadowRect.Create( - chart_id, - lShadowName, - window, - bar.time, - bar.GetDown(), - to, - bar.low // - ); - if (!result) - { - // - mBodyRect.Delete(); - mBodyRect.Detach(); - mHighShadowRect.Delete(); - mHighShadowRect.Detach(); - return result; - } - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - mBodyRect.Detach(); - mBodyRect.Delete(); - - // - mLowShadowRect.Detach(); - mLowShadowRect.Delete(); - - // - mHighShadowRect.Detach(); - mHighShadowRect.Delete(); - - // - Detach(); - Delete(); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_OHCL_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_OHCL_OBJ); - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set High Shadow Width ... - * - * @param value: Integer ... - */ - void HighShadowWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mHighShadowRect.Width(value); - } - - /** - * Set High Shadow Color ... - * - * @param value: Color ... - */ - void HighShadowColor(color value) - { - mHighShadowRect.Color(value); - } - - /** - * Set High Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void HighShadowStyle(ENUM_LINE_STYLE value) - { - mHighShadowRect.Style(value); - } - - /** - * Set High Shadow Fill ... - * - * @param value: Boolean ... - */ - void HighShadowFill(bool value) - { - mHighShadowRect.Fill(value); - } - - /** - * Set Body Width ... - * - * @param value: Integer ... - */ - void BodyWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBodyRect.Width(value); - } - - /** - * Set Body Color ... - * - * @param value: Color ... - */ - void BodyColor(color value) - { - mBodyRect.Color(value); - } - - /** - * Set Body Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BodyStyle(ENUM_LINE_STYLE value) - { - mBodyRect.Style(value); - } - - /** - * Set Body Fill ... - * - * @param value: Boolean ... - */ - void BodyFill(bool value) - { - mBodyRect.Fill(value); - } - - /** - * Set Low Shadow Width ... - * - * @param value: Integer ... - */ - void LowShadowWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mLowShadowRect.Width(value); - } - - /** - * Set Low Shadow Color ... - * - * @param value: Color ... - */ - void LowShadowColor(color value) - { - mLowShadowRect.Color(value); - } - - /** - * Set Low Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void LowShadowStyle(ENUM_LINE_STYLE value) - { - mLowShadowRect.Style(value); - } - - /** - * Set Low Shadow Fill ... - * - * @param value: Boolean ... - */ - void LowShadowFill(bool value) - { - mLowShadowRect.Fill(value); - } - - void BarSpes( - int width = 1, - color clr = clrNONE, - ENUM_LINE_STYLE style = STYLE_SOLID, - bool fill = false // - ) - { - // - BodyWidth(width); - LowShadowWidth(width); - HighShadowWidth(width); - - // - BodyColor(clr); - LowShadowColor(clr); - HighShadowColor(clr); - - // - BodyStyle(style); - LowShadowStyle(style); - HighShadowStyle(style); - - // - BodyFill(fill); - LowShadowFill(fill); - HighShadowFill(fill); - } - - // - private: - // - - // - // Props ... - CChartObjectRectangle mHighShadowRect; - CChartObjectRectangle mBodyRect; - CChartObjectRectangle mLowShadowRect; -}; - -/** - * Box Object ... - **/ -class XCBoxObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param pivot: XPVPivot instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - string name, - double upper, - double lower, - datetime from, - datetime to, - datetime at = NULL, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - upper > 0 && - lower > 0 && - to > from && - IsValid(to) && - IsValid(name) && - IsValid(from) && - upper > lower; - if (!result) - { - return result; - } - - // - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - result = mRect.Create( - chart_id, - name, - window, - from, - upper, - to, - lower // - ); - if (!result) - { - return result; - } - - // - if (result) - { - // - if (IsValid(at)) - { - // - result = mAt.Create( - chart_id, - name + ToString(X_AT), - window, - at // - ); - } - - // - if (!result) - { - // - mAt.Detach(); - mAt.Delete(); - - // - mRect.Detach(); - mRect.Delete(); - } - } - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - mAt.Detach(); - mAt.Delete(); - - // - mRect.Detach(); - mRect.Delete(); - - // - Detach(); - Delete(); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_BOX_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_BOX_OBJ); - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void BoxWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mAt.Width(value); - mRect.Width(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void BoxColor(color value) - { - // - mAt.Color(value); - mRect.Color(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BoxStyle(ENUM_LINE_STYLE value) - { - // - mAt.Style(value); - mRect.Style(value); - } - - /** - * Set Fill ... - * - * @param value: Boolean ... - */ - void BoxFill(bool value) - { - mRect.Fill(value); - } - - // - private: - // - - // - // Props ... - CChartObjectVLine mAt; - CChartObjectRectangle mRect; -}; - -/** - * Position Object ... - **/ -class XCPositionObject : public XCBaseObject -{ - // - // Public ... - public: - // - XPOIStyle riskStyle; // Risk Box Style ... - color inProfitColor; // In Profit Price Box Color ... - color inDrawdownColor; // In Drawdown Price Box Color ... - XPOIStyle rewardStyle; // Reward Box Style ... - ENUM_LINE_STYLE priceStyle; // Price Box Style ... - - // - // Creators ... - - /** - * Create a Position Object by Signal reference ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param signal: XSignal, reference to Provided Signal ... - * @param magic: ulong, Specified Position Magic Number ... - * @param ticket: ulong, Specified Position Ticket ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XSignal &signal, - ulong magic = 0, - ulong ticket = 0 // - ) - { - // - bool result = false; - - // - // Converts Signal to Test Position ... - XPosition _position; - result = ToXPosition( - signal, - _position, - magic, - ticket // - ); - - // - // Validate ... - result = chart_id >= 0 && - window >= 0 && - _position.IsValid(); - if (!result) - { - return result; - } - - // - result = Create( - chart_id, - window, - _position // - ); - - // - return result; - } - - /** - * Create a Position Object ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param position: XPosition, reference to Specified Position ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XPosition &position // - ) - { - // - bool result = false; - - // - // Validate ... - result = chart_id >= 0 && - window >= 0 && - position.IsValid(); - if (!result) - { - return result; - } - - // - result = Update(position); - if (!result) - { - // - Destroy(); - return result; - } - - // - return result; - } - - /** - * Update Position if Belongs to ... - * - * @param position: XPosition, reference to Specified Position ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool Update( - XPosition &position, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = - mChartID >= 0 && - mWindowID >= 0 && - position.IsValid() && - (!HasPosition() - ? true - : IsBelong(position)); - if (!result) - { - return result; - } - - // - datetime _toTime = GetBarTime( - position.symbol, - position.period, - barIndex // - ); - - // - // Validate Chart Info ... - result = UpdatePosition( - position, - _toTime // - ); - - // - return result; - } - - /** - * Update Position if Belongs to ... - * - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool Update(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = HasPosition(); - if (!result) - { - return result; - } - - // - // Update mPosition ... - result = XUpdatePosition(mPosition, barIndex); - if (!result) - { - return result; - } - - // - result = Update( - mPosition, - barIndex // - ); - - // - return result; - } - - // - // Retrievers ... - - bool GetPosition(XPosition &_position) - { - // - bool result = false; - - // - // Prepare ... - _position.Clean(); - - // - // Validate ... - result = HasPosition(); - if (!result) - { - return result; - } - - // - _position = mPosition; - - // - return result; - } - - // - // Checkers ... - - /** - * Check Object is Belongs to Specified Position or not ... - * - * @param position: XPosition, reference to Specified Position ... - * - * @return ( bool ) - */ - bool IsBelong(XPosition &position) - { - // - bool result = false; - - // - // Validate ... - result = - HasPosition() && - position.IsValid(); - - // - // Check ... - result = - result && - mPosition.ticket == position.ticket; - - // - return result; - } - - // - // Overrides ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - string TypeString() override - { - return ToXString(X_POSITION_OBJ); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - int Type(void) const override - { - return ((int)X_POSITION_OBJ); - } - - /** - * Destroy Object ... - **/ - void Destroy() override - { - // - ObjName(NULL); - - // - mRiskBox.Clean(); - mPosition.Clean(); - mPriceBox.Clean(); - mRewardBox.Clean(); - - // - mRiskBoxObj.Detach(); - mRiskBoxObj.Delete(); - - // - mPriceBoxObj.Detach(); - mPriceBoxObj.Delete(); - - // - mRewardBoxObj.Detach(); - mRewardBoxObj.Delete(); - } - - // - // Stylers ... - - /** - * Apply Styles based on Current Style Configurations ... - */ - void ApplyStyle() - { - // - // Validate ... - bool has = HasPosition(); - if (!has) - { - return; - } - - // - // Check Position in Profit ... - bool isLong = IsLong(mPosition.type); - bool isRiskFreed = - isLong - ? mPosition.sl > mPosition.entry - : mPosition.sl < mPosition.entry; - bool isInProfit = mPosition.profit > 0; - XPOIStyle _priceStyle; - if (isInProfit) - { - // - _priceStyle = rewardStyle; - _priceStyle.clr = inProfitColor; - } - else - { - // - _priceStyle = riskStyle; - _priceStyle.clr = inDrawdownColor; - } - - // - // Apply Profit Based Styles ... - _priceStyle.fill = true; - _priceStyle.style = priceStyle; - - // - // Change Risk Style if Risk Freed Position ... - if (isRiskFreed) { - // - riskStyle.fill = true; - riskStyle.clr = rewardStyle.clr; - } - - // - // Risk Style ... - mRiskBoxObj.BoxColor(riskStyle.clr); - mRiskBoxObj.BoxFill(riskStyle.fill); - mRiskBoxObj.BoxStyle(riskStyle.style); - mRiskBoxObj.BoxWidth(riskStyle.width); - - // - // Reward Style ... - mRewardBoxObj.BoxColor(rewardStyle.clr); - mRewardBoxObj.BoxFill(rewardStyle.fill); - mRewardBoxObj.BoxStyle(rewardStyle.style); - mRewardBoxObj.BoxWidth(rewardStyle.width); - - // - // Price Style .. - mPriceBoxObj.BoxColor(_priceStyle.clr); - mPriceBoxObj.BoxFill(_priceStyle.fill); - mPriceBoxObj.BoxStyle(_priceStyle.style); - mPriceBoxObj.BoxWidth(_priceStyle.width); - - // - // Cleanup Resources ... - _priceStyle.Clean(); - } - - // - void ApplyStyle( - XPOIStyle &bullishStyle, - XPOIStyle &bearishStyle // - ) - { - // - // Validate ... - if (!HasPosition()) - { - return; - } - - // - // Risk Box ... - if (mRiskBox.IsValid()) - { - // - mRiskBoxObj.BoxColor(bearishStyle.clr); - mRiskBoxObj.BoxFill(bearishStyle.fill); - mRiskBoxObj.BoxStyle(bearishStyle.style); - mRiskBoxObj.BoxWidth(bearishStyle.width); - } - - // - // Reward Box ... - if (mRewardBox.IsValid()) - { - // - mRewardBoxObj.BoxColor(bullishStyle.clr); - mRewardBoxObj.BoxFill(bullishStyle.fill); - mRewardBoxObj.BoxStyle(bullishStyle.style); - mRewardBoxObj.BoxWidth(bullishStyle.width); - } - - // - // Price Box ... - if (mPriceBox.IsValid()) - { - // - XPOIStyle _priceStyle; - if (mPriceBox.IsBullish()) - { - _priceStyle = bullishStyle; - } - else - { - _priceStyle = bearishStyle; - } - - // - mPriceBoxObj.BoxColor(_priceStyle.clr); - mPriceBoxObj.BoxFill(_priceStyle.fill); - mPriceBoxObj.BoxStyle(_priceStyle.style); - mPriceBoxObj.BoxWidth(_priceStyle.width); - - // - _priceStyle.Clean(); - } - } - - // - // Protected ... - protected: - // - - // - bool HasPosition() - { - return mPosition.IsValid(); - } - - // - bool UpdatePosition( - XPosition &_position, - datetime _toTime = NULL // - ) - { - // - bool result = false; - - // - // Normalize ... - _toTime = NormalizeTime(_toTime); - - // - // Validate ... - result = _position.IsValid() && - (!HasPosition() - ? true - : _position.ticket == mPosition.ticket // - ); - if (!result) - { - return result; - } - - // - mPosition = _position; - result = UpdateZones(_toTime); - - // - return result; - } - - // - bool UpdateZones(datetime _toTime = NULL) - { - // - bool result = false; - - // - // Normalize ... - _toTime = NormalizeTime(_toTime); - - // - // Validate ... - result = HasPosition(); - if (!result) - { - return result; - } - - // - string iSymbol = mPosition.symbol; - ENUM_TIMEFRAMES iPeriod = mPosition.period; - - // - datetime iAt = mPosition.openAt; - datetime iFrom = mPosition.openAt; - - // - datetime _defaultToTime = iFrom + (PeriodSeconds(iPeriod) * 3); - datetime iTo = _toTime <= _defaultToTime - ? _defaultToTime - : _toTime; - - // - double iTP = mPosition.tp; - double iSL = mPosition.sl; - double iEntry = mPosition.entry; - double iPrice = mPosition.price; - - // - bool isLong = IsLong(mPosition.type); - ENUM_X_DIRECTION iRiskDir = isLong - ? X_DIRECTION_BEARISH - : X_DIRECTION_BULLISH; - ENUM_X_DIRECTION iRewardDir = isLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - bool isInProfit = mPosition.profit > 0; - bool isRiskFreed = - isLong - ? mPosition.sl > mPosition.entry - : mPosition.sl < mPosition.entry; - ENUM_X_DIRECTION iPriceDir = isInProfit - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Try to Update Zones ... - string iSuffix = ToXString(mPosition.type) + "_" + ToXString(mPosition.ticket); - string iPrefix = ToXString(TimeToSeconds(mPosition.openAt)); - string iName = iSuffix + "_" + iPrefix; - string iRiskName = iSuffix + "_" + "RISK" + "_" + iPrefix; - string iPriceName = iSuffix + "_" + "PRICE" + "_" + iPrefix; - string iRewardName = iSuffix + "_" + "REWARD" + "_" + iPrefix; - - // - // Risk Box ... - mRiskBox.to = iTo; - mRiskBox.at = iAt; - mRiskBox.lower = - isLong - ? isRiskFreed - ? iEntry - : iSL - : isRiskFreed - ? iSL - : iEntry; - mRiskBox.upper = - isLong - ? isRiskFreed - ? iSL - : iEntry - : isRiskFreed - ? iEntry - : iSL; - mRiskBox.from = iFrom; - mRiskBox.symbol = iSymbol; - mRiskBox.period = iPeriod; - mRiskBox.type = iRiskName; - mRiskBox.dir = isRiskFreed - ? X_DIRECTION_BEARISH - : X_DIRECTION_BULLISH; - - // - // Reward Box ... - mRewardBox.to = iTo; - mRewardBox.at = iAt; - mRewardBox.lower = - isLong - ? iEntry - : iTP; - mRewardBox.upper = - isLong - ? iTP - : iEntry; - mRewardBox.from = iFrom; - mRewardBox.symbol = iSymbol; - mRewardBox.period = iPeriod; - mRewardBox.type = iRewardName; - mRewardBox.dir = X_DIRECTION_BULLISH; - - // - // Price Box ... - mPriceBox.to = iTo; - mPriceBox.at = iAt; - mPriceBox.lower = - isLong - ? isInProfit - ? isRiskFreed - ? iSL - : iEntry - : iPrice - : isInProfit - ? isRiskFreed - ? iSL - : iPrice - : iEntry; - mPriceBox.upper = - isLong - ? isInProfit - ? iPrice - : iEntry - : isInProfit - ? iEntry - : iPrice; - mPriceBox.from = iFrom; - mPriceBox.symbol = iSymbol; - mPriceBox.period = iPeriod; - mPriceBox.type = iPriceName; - mPriceBox.dir = isInProfit - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = mRiskBox.IsValid() && - mPriceBox.IsValid() && - mRewardBox.IsValid(); - if (!result) - { - return result; - } - - // - mRiskBoxObj.Detach(); - mRiskBoxObj.Delete(); - bool isRiskCreated = - mRiskBoxObj.Create( - mChartID, - mWindowID, - mRiskBox.type, - mRiskBox.upper, - mRiskBox.lower, - mRiskBox.from, - mRiskBox.to, - NULL, // At ... - NULL // Prefix ... - ); - - // - mRewardBoxObj.Detach(); - mRewardBoxObj.Delete(); - bool isRewardCreated = - mRewardBoxObj.Create( - mChartID, - mWindowID, - mRewardBox.type, - mRewardBox.upper, - mRewardBox.lower, - mRewardBox.from, - mRewardBox.to, - NULL, // At ... - NULL // Prefix ... - ); - - // - mPriceBoxObj.Detach(); - mPriceBoxObj.Delete(); - bool isPriceCreated = - mPriceBoxObj.Create( - mChartID, - mWindowID, - mPriceBox.type, - mPriceBox.upper, - mPriceBox.lower, - mPriceBox.from, - mPriceBox.to, - NULL, // At ... - NULL // Prefix ... - ); - - // - result = - isRiskCreated && - isPriceCreated && - isRewardCreated; - if (result) - { - // - ObjName(iName); - - // - // Apply Styles ... - ApplyStyle(); - } - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - int mWindowID; - long mChartID; - - // - XBoxZone mRiskBox; - XBoxZone mPriceBox; - XPosition mPosition; - XBoxZone mRewardBox; - - // - XCBoxObject mRiskBoxObj; - XCBoxObject mPriceBoxObj; - XCBoxObject mRewardBoxObj; - - // -}; - -/** - * XPivotAnalysis Chart Object ... - **/ -class XCPivotAnalysisObject : public XCBaseObject -{ - // - public: - // - - /** - * Create Object ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param model: XPivotAnalysis, reference model ... - * @param drawTrends: Specified to Draw Trends or not ... - * @param drawZones: Specified to Draw Support and Resistance Zones or not ... - * @param drawPivots: Specified to Draw Pivots or not ... - * @param peakArrow: int, Specified Arrow Code for Peak Pivots ... - * @param valeArrow: int, Specified Arrow Code for Vale Pivots ... - * @param threshold: int, distance between price and arrow in Point ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XPivotAnalysis &model, - bool drawTrends = true, - bool drawZones = true, - bool drawPivots = true, - int peakArrow = 159, - int valeArrow = 159, - int threshold = 5 // - ) - { - // - bool result = false; - - // - bool has = false; - - // - // Validate ... - result = model.IsValid(); - if (!result) - { - return result; - } - - // - // Generate Object ID ... - string objID = model.GetObjectID(); - - // - // Draw Trend Lines ... - mUpper = NULL; - mLower = NULL; - if (drawTrends) - { - // - string upperName = model.GetUpperObjectID(); - string lowerName = model.GetLowerObjectID(); - - // - RemoveObjects(upperName, chart_id, window); - RemoveObjects(lowerName, chart_id, window); - - // - // Creating Upper ... - mUpper = new CChartObjectTrend(); - result = mUpper.Create( - chart_id, - upperName, - window, - model.fromTime, - model.peakFrom, - model.toTime, - model.peakTo // - ); - if (!result) - { - // - // Destroy Trending Objects ... - DestroyObject(mUpper); - DestroyObject(mLower); - - // - return result; - } - - // - // Create Lower ... - mLower = new CChartObjectTrend(); - result = mLower.Create( - chart_id, - lowerName, - window, - model.fromTime, - model.valeFrom, - model.toTime, - model.valeTo // - ); - if (!result) - { - // - // Destroy Trending Objects ... - DestroyObject(mUpper); - DestroyObject(mLower); - - // - return result; - } - } - - // - // Draw Zones ... - mSupportBox = NULL; - mResistanceBox = NULL; - if (drawZones) - { - // - // Support ... - XBoxZone tmpBox; - has = model.HasSupportBox(tmpBox); - if (has) - { - // - datetime to = TimeCurrent(); - string name = model.GetSupportBoxObjectID(); - RemoveObjects(name, chart_id, window); - mSupportBox = new XCBoxObject(); - result = mSupportBox.Create( - chart_id, - window, - name, - tmpBox.upper, - tmpBox.lower, - tmpBox.from, - to // - ); - if (!result) - { - // - DestroyObject(mUpper); - DestroyObject(mLower); - DestroyObject(mSupportBox); - - // - return result; - } - } - - // - // Resistance ... - tmpBox.Clean(); - has = model.HasResistanceBox(tmpBox); - if (has) - { - // - datetime to = TimeCurrent(); - string name = model.GetResistanceBoxObjectID(); - RemoveObjects(name, chart_id, window); - mResistanceBox = new XCBoxObject(); - result = mResistanceBox.Create( - chart_id, - window, - name, - tmpBox.upper, - tmpBox.lower, - tmpBox.from, - to // - ); - if (!result) - { - // - DestroyObject(mUpper); - DestroyObject(mLower); - DestroyObject(mSupportBox); - DestroyObject(mResistanceBox); - - // - return result; - } - } - } - - // - // Draw Pivots ... - if (drawPivots && - model.HasPivots()) - { - // - XOHCL iBar; - int arrow = 0; - string name = NULL; - XCBarArrowObject *iObj; - ENUM_X_PRICE type = X_PRICE_NONE; - int pivotsCount = ArraySize(model.pivots); - for (int i = 0; i < pivotsCount; i++) - { - // - has = model.pivots[i].GetBar(iBar); - if (!has) - { - continue; - } - - // - arrow = model.pivots[i].IsPeak() - ? peakArrow - : valeArrow; - name = model.pivots[i].GetObjectID(); - RemoveObjects(name, chart_id, window); - type = model.pivots[i].IsPeak() - ? X_PRICE_HIGH - : X_PRICE_LOW; - iObj = new XCBarArrowObject(); - has = iObj.CreateByBar( - chart_id, - name, - window, - arrow, - iBar, - type, - threshold // - ); - if (has) - { - // - if (model.pivots[i].IsPeak()) - { - // - if (mPeaks == NULL) - { - mPeaks = new CArrayObj(); - } - - // - mPeaks.Add(iObj); - } - else - { - // - if (mVales == NULL) - { - mVales = new CArrayObj(); - } - - // - mVales.Add(iObj); - } - } - - // - iBar.Clean(); - ZeroMemory(iObj); - } - - // - // Cleanup Resources ... - iBar.Clean(); - ZeroMemory(iObj); - } - - // - // Setting Object Name ... - if (result) - { - ObjName(objID); - } - - // - return result; - } - - // - // Virtuals ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual int Type(void) - { - return (int)X_PIVOT_OBJ; - } - - /** - * Type as String ... - **/ - string TypeString() override - { - return ToXString(X_PIVOT_OBJ); - } - - /** - * Destroy ... - */ - void virtual Destroy() - { - // - DestroyObjects(mPeaks); - DestroyObjects(mVales); - - // - DestroyObject(mUpper); - DestroyObject(mLower); - DestroyObject(mSupportBox); - DestroyObject(mResistanceBox); - - // - delete mPeaks; - delete mVales; - delete mUpper; - delete mLower; - delete mSupportBox; - delete mResistanceBox; - - // - ZeroMemory(mPeaks); - ZeroMemory(mVales); - ZeroMemory(mUpper); - ZeroMemory(mLower); - ZeroMemory(mSupportBox); - ZeroMemory(mResistanceBox); - - // - Detach(); - Delete(); - } - - // - // Styling ... - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void UpperWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - if (mUpper == NULL) - { - return; - } - - // - mUpper.Width(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void UpperColor(color value) - { - // - if (mUpper == NULL) - { - return; - } - - // - mUpper.Color(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void UpperStyle(ENUM_LINE_STYLE value) - { - // - if (mUpper == NULL) - { - return; - } - - // - mUpper.Style(value); - } - - /** - * Specified Upper Ray to Left or not ... - * - * @param value: bool - */ - void UpperRayLeft(bool value) - { - // - if (mUpper == NULL) - { - return; - } - - // - mUpper.RayLeft(value); - } - - /** - * Specified Upper Ray to Right or not ... - * - * @param value: bool - */ - void UpperRayRight(bool value) - { - // - if (mUpper == NULL) - { - return; - } - - // - mUpper.RayRight(value); - } - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void LowerWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - if (mLower == NULL) - { - return; - } - - // - mLower.Width(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void LowerColor(color value) - { - // - if (mLower == NULL) - { - return; - } - - // - mLower.Color(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void LowerStyle(ENUM_LINE_STYLE value) - { - // - if (mLower == NULL) - { - return; - } - - // - mLower.Style(value); - } - - /** - * Specified Lower Ray to Left or not ... - * - * @param value: bool - */ - void LowerRayLeft(bool value) - { - // - if (mLower == NULL) - { - return; - } - - // - mLower.RayLeft(value); - } - - /** - * Specified Lower Ray to Right or not ... - * - * @param value: bool - */ - void LowerRayRight(bool value) - { - // - if (mLower == NULL) - { - return; - } - - // - mLower.RayRight(value); - } - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void SupportWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - if (mSupportBox == NULL) - { - return; - } - - // - mSupportBox.BoxWidth(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void SupportColor(color value) - { - // - if (mSupportBox == NULL) - { - return; - } - - // - mSupportBox.BoxColor(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void SupportStyle(ENUM_LINE_STYLE value) - { - // - if (mSupportBox == NULL) - { - return; - } - - // - mSupportBox.BoxStyle(value); - } - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void ResistanceWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - if (mResistanceBox == NULL) - { - return; - } - - // - mResistanceBox.BoxWidth(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void ResistanceColor(color value) - { - // - if (mResistanceBox == NULL) - { - return; - } - - // - mResistanceBox.BoxColor(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void ResistanceStyle(ENUM_LINE_STYLE value) - { - // - if (mResistanceBox == NULL) - { - return; - } - - // - mResistanceBox.BoxStyle(value); - } - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void PeaksWidth(int value) - { - // - if (mPeaks == NULL) - { - return; - } - - // - // Normalize ... - value = NormalizeInt(value, 1); - - // - // Validate ... - int count = mPeaks.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iPeak; - for (int i = 0; i < count; i++) - { - // - iPeak = (XCBarArrowObject *)mPeaks.At(i); - iPeak.ArrowWidth(value); - ZeroMemory(iPeak); - } - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void PeaksColor(color value) - { - // - if (mPeaks == NULL) - { - return; - } - - // - // Validate ... - int count = mPeaks.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iPeak; - for (int i = 0; i < count; i++) - { - // - iPeak = (XCBarArrowObject *)mPeaks.At(i); - iPeak.ArrowColor(value); - ZeroMemory(iPeak); - } - } - - /** - * Set Arrow Anchor ... - * - * @param value: ENUM_ARROW_ANCHOR member ... - */ - void PeaksAnchor(ENUM_ARROW_ANCHOR value) - { - // - if (mPeaks == NULL) - { - return; - } - - // - // Validate ... - int count = mPeaks.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iPeak; - for (int i = 0; i < count; i++) - { - // - iPeak = (XCBarArrowObject *)mPeaks.At(i); - iPeak.ArrowAnchor(value); - ZeroMemory(iPeak); - } - } - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void ValesWidth(int value) - { - // - if (mVales == NULL) - { - return; - } - - // - // Normalize ... - value = NormalizeInt(value, 1); - - // - // Validate ... - int count = mVales.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iVale; - for (int i = 0; i < count; i++) - { - // - iVale = (XCBarArrowObject *)mVales.At(i); - iVale.ArrowWidth(value); - ZeroMemory(iVale); - } - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void ValesColor(color value) - { - // - if (mVales == NULL) - { - return; - } - - // - // Validate ... - int count = mVales.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iVale; - for (int i = 0; i < count; i++) - { - // - iVale = (XCBarArrowObject *)mVales.At(i); - iVale.ArrowColor(value); - ZeroMemory(iVale); - } - } - - /** - * Set Arrow Anchor ... - * - * @param value: ENUM_ARROW_ANCHOR member ... - */ - void ValesAnchor(ENUM_ARROW_ANCHOR value) - { - // - if (mVales == NULL) - { - return; - } - - // - // Validate ... - int count = mVales.Total(); - bool has = IsValidSize(count); - if (!has) - { - return; - } - - // - XCBarArrowObject *iVale; - for (int i = 0; i < count; i++) - { - // - iVale = (XCBarArrowObject *)mVales.At(i); - iVale.ArrowAnchor(value); - ZeroMemory(iVale); - } - } - - // - private: - // - CArrayObj *mPeaks; - CArrayObj *mVales; - CChartObjectTrend *mUpper; - CChartObjectTrend *mLower; - XCBoxObject *mSupportBox; - XCBoxObject *mResistanceBox; -}; - -// -// Extensions ... - -/** - * Add all Items of Specified CArrayObj into another ... - * - * @param source: CArrayObj, pointer refrence Specified Data Source ... - * @param dest: CArrayObj, pointer refrence Specified Destination of Adding ... - */ -void AddObjects( - CArrayObj *&source, - CArrayObj &dest // -) -{ - // - bool has = source != NULL && - source.Total() > 0; - if (!has) - { - return; - } - - // - for (int i = 0; i < source.Total(); i++) - { - dest.Add(source.At(i)); - } -} - -/** - * Destroy Object if Exists ... - * - * @param object: pointer refrence to Destroy ... - */ -void DestroyObject(XCBoxObject *&object) -{ - // - // Validate ... - bool has = object != NULL; - if (!has) - { - return; - } - - // - object.Destroy(); - - // - object.Detach(); - object.Delete(); - - // - delete object; - ZeroMemory(object); -} - -/** - * Destroy Object if Exists ... - * - * @param object: pointer refrence to Destroy ... - */ -void DestroyObject(XCPivotAnalysisObject *&object) -{ - // - // Validate ... - bool has = object != NULL; - if (!has) - { - return; - } - - // - object.Destroy(); - - // - object.Detach(); - object.Delete(); - - // - delete object; - ZeroMemory(object); -} - -/** - * Destroy Object if Exists ... - * - * @param object: pointer refrence to Destroy ... - */ -void DestroyObject(CChartObjectTrend *&object) -{ - // - // Validate ... - bool has = object != NULL; - if (!has) - { - return; - } - - // - object.Detach(); - object.Delete(); - - // - delete object; - ZeroMemory(object); -} - -/** - * Completely Destroy all Chart Objects ... - * - * @param objects: CArrayObj, pointer refrence Specified Data Source ... - */ -void DestroyObjects(CArrayObj *&objects) -{ - // - // Validate Exists ... - if (objects == NULL) - { - return; - } - - // - // Count Childs ... - int count = objects.Total(); - if (!IsValidSize(count)) - { - return; - } - - // - // Destroy all Childs ... - for (int i = 0; i < count; i++) - { - // - // Checking Types ... - int iType = ((CChartObject *)objects.At(i)).Type(); - - // - string iTypeStr = NULL; - if (iType == X_EMPTY_OBJ) - { - // - XCBaseObject *iObj = (XCBaseObject *)objects.At(i); - iTypeStr = iObj.TypeString(); - - // - if (iTypeStr == ToXString(X_BOX_OBJ)) - { - iType = X_BOX_OBJ; - } - else if (iTypeStr == ToXString(X_BAR_ARROW_OBJ)) - { - iType = X_BAR_ARROW_OBJ; - } - else if (iTypeStr == ToXString(X_SIGNAL_OBJ)) - { - iType = X_SIGNAL_OBJ; - } - else if (iTypeStr == ToXString(X_OHCL_OBJ)) - { - iType = X_OHCL_OBJ; - } - else if (iTypeStr == ToXString(X_RR_OBJ)) - { - iType = X_RR_OBJ; - } - else if (iTypeStr == ToXString(X_PIVOT_OBJ)) - { - iType = X_PIVOT_OBJ; - } - } - - // - string iName = ((CChartObject *)objects.At(i)).Name(); - if (!IsSpecifiedValid(iName)) - { - iName = ((XCBaseObject *)objects.At(i)).ObjName(); - } - - // - switch (iType) - { - // - case X_RR_OBJ: { - // - XCRRObject *iObj = (XCRRObject *)objects.At(i); - iObj.Destroy(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - case X_BOX_OBJ: { - // - XCBoxObject *iObj = (XCBoxObject *)objects.At(i); - iObj.Destroy(); - iObj.Detach(); - iObj.Delete(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - case X_OHCL_OBJ: { - // - XCOHCLObject *iObj = (XCOHCLObject *)objects.At(i); - iObj.Destroy(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - case X_PIVOT_OBJ: { - // - XCPivotAnalysisObject *iObj = (XCPivotAnalysisObject *)objects.At(i); - iObj.Destroy(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - case X_SIGNAL_OBJ: { - // - XCSignalObject *iObj = (XCSignalObject *)objects.At(i); - iObj.Destroy(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - case X_BAR_ARROW_OBJ: { - // - XCBarArrowObject *iObj = (XCBarArrowObject *)objects.At(i); - iObj.Destroy(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - // - // Default Object Types ... - case OBJ_VLINE: - case OBJ_HLINE: - case OBJ_TREND: - case OBJ_TRENDBYANGLE: - case OBJ_CYCLES: - case OBJ_ARROWED_LINE: - case OBJ_CHANNEL: - case OBJ_STDDEVCHANNEL: - case OBJ_REGRESSION: - case OBJ_PITCHFORK: - case OBJ_GANNLINE: - case OBJ_GANNFAN: - case OBJ_GANNGRID: - case OBJ_FIBO: - case OBJ_FIBOTIMES: - case OBJ_FIBOFAN: - case OBJ_FIBOARC: - case OBJ_FIBOCHANNEL: - case OBJ_EXPANSION: - case OBJ_ELLIOTWAVE5: - case OBJ_ELLIOTWAVE3: - case OBJ_RECTANGLE: - case OBJ_TRIANGLE: - case OBJ_ELLIPSE: - case OBJ_ARROW_THUMB_UP: - case OBJ_ARROW_THUMB_DOWN: - case OBJ_ARROW_UP: - case OBJ_ARROW_DOWN: - case OBJ_ARROW_STOP: - case OBJ_ARROW_CHECK: - case OBJ_ARROW_LEFT_PRICE: - case OBJ_ARROW_RIGHT_PRICE: - case OBJ_ARROW_BUY: - case OBJ_ARROW_SELL: - case OBJ_ARROW: - case OBJ_TEXT: - case OBJ_LABEL: - case OBJ_BUTTON: - case OBJ_CHART: - case OBJ_BITMAP: - case OBJ_BITMAP_LABEL: - case OBJ_EDIT: - case OBJ_EVENT: - case OBJ_RECTANGLE_LABEL: { - // - CChartObject *iObj = (CChartObject *)objects.At(i); - - // - iObj.Detach(); - iObj.Delete(); - - // - delete iObj; - ZeroMemory(iObj); - } - break; - } - - // - RemoveObjects(iName); - } - - // - // Destroy itSelf ... - objects.Clear(); - delete objects; - ZeroMemory(objects); -} - -/** - * Remove Drawn Objects from Chart ... - * - * @param tag: Specified Object Name, if NULL remove all Objects ... - * @param chartId: long, Specified Chart ... - * @param subWindow: int Specified Sub Window ... - */ -void RemoveObjects( - string tag = NULL, - long chartId = -1, - int subWindow = -1 // -) -{ - // - // Normalize Args ... - - // - if (chartId == -1) - { - chartId = 0; - } - - // - if (subWindow == -1) - { - subWindow = 0; - } - - // - bool has = false; - string iName = NULL; - for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) - { - // - // Retrieve Object Name ... - iName = ObjectName(chartId, iObj, subWindow); - - // - // Check Can Delete Object or not ... - has = - !IsSpecifiedValid(tag) - ? true - : StringFind(iName, tag) >= 0; - if (has) - { - ObjectDelete(chartId, iName); - } - } - - // - // Redraw Chart ... - ChartRedraw(); -} - -// -// Color Manipulation Functions ... - -/** - * Apply Alph to Color ... - * - * @param _clr: Specified Color ... - * @param _alpha: Specified Alpha to Apply ... - * - * @return ( color ) - */ -color ApplyAlpha( - color _clr, - uchar _alpha = 255 // -) -{ - // - color result = _clr; - - // - // Normalize ... - _alpha = (uchar)NormalizeInt(_alpha, 0, 255); - - // - uchar alpha = _alpha / 255; - - // - uint uintColor = ColorToARGB(_clr, alpha); - result = (color)uintColor; - - // - return result; -} -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-cobject.class.mq5 b/Documents/BKP/x-saherelm.x-cobject.class.mq5 deleted file mode 100644 index 91cc37c0..00000000 --- a/Documents/BKP/x-saherelm.x-cobject.class.mq5 +++ /dev/null @@ -1,3478 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XChartObjects -// Description: provides all require Chart Objects ... -// -// -// 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 "../Libraries/x-saherelm.x-poi.lib.mq5" -#include "../Libraries/x-saherelm.x-trade.lib.mq5" - -// -#include -#include -#include -#include -#include -#include - -// -// Definitions ... - -enum ENUM_XCHARTOBJECTS -{ - // - // Global ... - X_ZONE_OBJ = 7860, - X_BOX_OBJ = 7861, - X_BAR_ARROW_OBJ = 7862, - // - X_SIGNAL_OBJ = 8860, - X_TREND_OBJ = 8861, - X_XPVPIVOT_OBJ = 8862, - X_OHCL_OBJ = 8863, - X_RR_OBJ = 8864, - // - // Structured ... - X_TRADE_DAY_OBJ = 9860, - X_MARKET_SESSION_OBJ = 9861, - X_SWING_HIGH_OBJ = 9862, - X_SWING_LOW_OBJ = 9863, - X_BULLISH_MOMENTUM_BAR_OBJ = 9864, - X_BEARISH_MOMENTUM_BAR_OBJ = 9865, - X_BULLISH_REJECTION_BAR_OBJ = 9866, - X_BEARISH_REJECTION_BAR_OBJ = 9867, - X_SUPPORT_ZONE_OBJ = 9868, - X_RESISTANCE_ZONE_OBJ = 9869, - X_SUPPLY_ZONE_OBJ = 9870, - X_DEMAND_ZONE_OBJ = 9871, - X_BULLISH_ORDERBLOCK_OBJ = 9872, - X_BEARISH_ORDERBLOCK_OBJ = 9873, - X_BULLISH_FVG_OBJ = 9874, - X_BEARISH_FVG_OBJ = 9875, - X_TICK_ZONE_OBJ = 9876, - X_TICKS_ZONE_OBJ = 9877, - X_CONSOLIDATION_ZONE_OBJ = 9878, -}; - -enum ENUM_X_CHART_IDS -{ - X_TO, - X_FROM, - X_UPPER, - X_LOWER, - X_ENTRY, - X_TARGET, - X_SL, - X_TP, - X_BAR_H_SHW, - X_BAR_BDY, - X_BAR_L_SHW, -}; - -string ToString(ENUM_X_CHART_IDS value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_TO: - result = "TO"; - break; - - // - case X_FROM: - result = "FROM"; - break; - - // - case X_UPPER: - result = "UPPER"; - break; - - // - case X_LOWER: - result = "LOWER"; - break; - - // - case X_ENTRY: - result = "ENTRY"; - break; - - // - case X_TARGET: - result = "TARGET"; - break; - - // - case X_SL: - result = "SL"; - break; - - // - case X_TP: - result = "TP"; - break; - - // - case X_BAR_H_SHW: - result = "HSHW"; - break; - - // - case X_BAR_BDY: - result = "BODY"; - break; - - // - case X_BAR_L_SHW: - result = "LSHW"; - break; - - // - } - - // - return result; -} - -// -// Extensions ... - -/** - * Converts a XBoxZone struct to XSignal instance ... - * - * @param box: XBoxZone instance reference, provide source info ... - * @param signal: XSignal instance reference, holds prepared converted signal ... - * - * @return ( bool ) - */ -bool ToSignal( - XBoxZone &box, - XSignal &signal, - double &rewardRatios[], - double additionalSL = 0 // -) -{ - // - bool result = false; - - // - signal.Clean(); - - // - result = box.IsValid() && - HasChild(rewardRatios); - if (!result) - { - return result; - } - - // - XOHCL entryBar; - int entryIDX = box.ToIndex(); - if (entryIDX > 0) - { - entryIDX--; - } - result = entryBar.Init( - box.symbol, - box.period, - entryIDX // - ); - if (!result) - { - // - entryBar.Clean(); - - // - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - ENUM_POSITION_TYPE iType = - isBullish - ? POSITION_TYPE_BUY - : POSITION_TYPE_SELL; - ENUM_X_POSITION_TYPES iXType = - isBullish - ? X_POSITION_TYPE_LONG - : X_POSITION_TYPE_SHORT; - - // - double points = GetPoints(box.symbol); - - // - double entry = - isBullish - ? box.upper - : box.lower; - entry = entryBar.open; - - // - double sl = - isBullish - ? box.lower - : box.upper; - if (additionalSL > 0) - { - // - sl = - isBullish - ? sl - additionalSL - : sl + additionalSL; - } - - // - double risk = MathAbs(entry - sl); - - // - double tp = 0; - - // - // Calculate Target ... - XTarget targets[]; - - // - double tmp[]; - int idx = -1; - XTarget iTarget; - bool has = false; - double iRatio = 0; - double iReward = 0; - double iRewardPrice = 0; - Copy( - rewardRatios, - tmp // - ); - while (HasChild(tmp)) - { - // - idx = -1; - iRatio = GetMaxWidthIndex( - tmp, - idx // - ); - - // - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - has = iRatio > 0; - - // - ArrayRemove( - tmp, - idx, - 1 // - ); - - // - bool canSetTP = tp <= 0; - - // - iReward = iRatio * risk; - - // - iRewardPrice = - isBullish - ? entry + iReward - : entry - iReward; - if (canSetTP) - { - tp = iRewardPrice; - } - else - { - // - iTarget.target = iRewardPrice; - AddRef( - iTarget, - targets // - ); - - // - iTarget.Clean(); - } - } - Clean(tmp); - - // - // Filling Signal ... - signal.tp = tp; - signal.sl = sl; - signal.type = iType; - signal.comment = ""; - signal.entry = entry; - signal.time = box.to; - signal.volume = 0.01; - signal.provider = box.type; - signal.symbol = box.symbol; - signal.period = box.period; - signal.mode = X_ORDER_MODE_MARKET; - - // - if (HasChild(targets)) - { - // - Copy( - targets, - signal.targets // - ); - } - - // - result = signal.IsValid(); - - // - // Cleanup Resources ... - - // - if (!result) - { - signal.Clean(); - } - - // - Clean(tmp); - Clean(targets); - iTarget.Clean(); - entryBar.Clean(); - - // - return result; -} - -// -// Implementation ... - -// -// Global Chart Objects ... - -// -// Bas Chart Object ... -class XCBaseObject : public CChartObject -{ - // - public: - // - - // - // Getter(s) / Setter(s) ... - - /** - * Get Object Specified Name ... - * - * @return ( string ) - */ - string ObjName() - { - return mObjName; - } - - /** - * Set Object Specified Name ... - * - * @param value: String ... - */ - void ObjName(string value) - { - mObjName = value; - } - - // - private: - // - - // - // Props ... - string mObjName; // Object Specified Name ... - - // -}; - -class XCBarArrowObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param name: String, Specified Object ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param swing: XCSwing instance ... - * - * @return ( bool ) - */ - bool CreateByBar( - long chart_id, - string name, - int window, - int arrow, - XOHCL &bar, - ENUM_X_PRICE priceType, - double threshold = 5 // - ) - { - // - bool result = false; - - // - result = - // - bar.IsValid() && - IsValid(name) - // - ; - if (!result) - { - return result; - } - - // - datetime time = bar.time; - double price = bar.GetPrice(priceType); - - // - if (threshold > 0) - { - // - double thresholdPrice = threshold * GetPoints(bar.symbol); - if (priceType == X_PRICE_HIGH) - { - price += thresholdPrice; - } - else if (priceType == X_PRICE_LOW) - { - price -= thresholdPrice; - } - } - - // - result = mArrow.Create( - chart_id, - name, - window, - time, - price, - (char)arrow // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - // - // Setter(s) ... - - /** - * Set Arrow Anchor ... - * - * @param value: ENUM_ARROW_ANCHOR member ... - */ - void ArrowAnchor(ENUM_ARROW_ANCHOR value) - { - mArrow.Anchor(value); - } - - /** - * Set Arrow Color ... - * - * @param value: Color ... - */ - void ArrowColor(color value) - { - mArrow.Color(value); - } - - /** - * Set Arrow Width ... - * - * @param value: Integer ... - */ - void ArrowWidth(int value) - { - mArrow.Width(value); - } - - // - private: - // - CChartObjectArrow mArrow; - - // -}; - -// -// Swing ... -class XCSwingObject : public XCBarArrowObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param swing: XCSwing instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool CreateBySwing( - long chart_id, - int window, - int arrow, - XCSwing &swing, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - // - swing.IsValid() - // - ; - if (!result) - { - return result; - } - - // - string name = swing.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - XOHCL bar; - result = swing.FillBar(bar); - if (!result) - { - return result; - } - - // - ENUM_X_PRICE price = swing.IsSwingHigh() - ? X_PRICE_HIGH - : X_PRICE_LOW; - - // - result = CreateByBar( - chart_id, - name, - window, - arrow, - bar, - price // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } -}; - -// -// Swing High ... -class XCSwingHighObject : public XCSwingObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param swing: XCSwing instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCSwing &swing, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = swing.IsValid() && - swing.IsSwingHigh(); - if (!result) - { - return result; - } - - // - result = CreateBySwing( - chart_id, - window, - arrow, - swing, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_SWING_HIGH_OBJ; - } - - // -}; - -// -// Swing Low ... -class XCSwingLowObject : public XCSwingObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param swing: XCSwing instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCSwing &swing, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = swing.IsValid() && - swing.IsSwingLow(); - if (!result) - { - return result; - } - - // - result = CreateBySwing( - chart_id, - window, - arrow, - swing, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_SWING_LOW_OBJ; - } - - // -}; - -// -// Momentum ... -class XCMomentumBarObject : public XCBarArrowObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param momentumBar: XCMomentumBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool CreateByMomentum( - long chart_id, - int window, - int arrow, - XCMomentumBar &momentumBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - // - momentumBar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - string name = momentumBar.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - XOHCL bar; - result = momentumBar.FillBar(bar); - if (!result) - { - return result; - } - - // - ENUM_X_PRICE price = momentumBar.IsBullish() - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - result = CreateByBar( - chart_id, - name, - window, - arrow, - bar, - price // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } -}; - -// -// Bullish Momentum Bar ... -class XCBullishMomentumBarObject : public XCMomentumBarObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param momentumBar: XCMomentumBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCMomentumBar &momentumBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = momentumBar.IsValid() && - momentumBar.IsBullish(); - if (!result) - { - return result; - } - - // - result = CreateByMomentum( - chart_id, - window, - arrow, - momentumBar, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BULLISH_MOMENTUM_BAR_OBJ; - } - - // -}; - -// -// Bearish Momentum Bar ... -class XCBearishMomentumBarObject : public XCMomentumBarObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param momentumBar: XCMomentumBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCMomentumBar &momentumBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = momentumBar.IsValid() && - momentumBar.IsBearish(); - if (!result) - { - return result; - } - - // - result = CreateByMomentum( - chart_id, - window, - arrow, - momentumBar, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BEARISH_MOMENTUM_BAR_OBJ; - } - - // -}; - -// -// Rejection ... -class XCRejectionBarObject : public XCBarArrowObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param rejectionBar: XCRejectionBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool CreateByRejection( - long chart_id, - int window, - int arrow, - XCRejectionBar &rejectionBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - // - rejectionBar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - string name = rejectionBar.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - XOHCL bar; - result = rejectionBar.FillBar(bar); - if (!result) - { - return result; - } - - // - ENUM_X_PRICE price = rejectionBar.IsBullish() - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - result = CreateByBar( - chart_id, - name, - window, - arrow, - bar, - price // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } -}; - -// -// Bullish Rejection Bar ... -class XCBullishRejectionBarObject : public XCRejectionBarObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param rejectionBar: XCRejectionBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCRejectionBar &rejectionBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = rejectionBar.IsValid() && - rejectionBar.IsBullish(); - if (!result) - { - return result; - } - - // - result = CreateByRejection( - chart_id, - window, - arrow, - rejectionBar, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BULLISH_REJECTION_BAR_OBJ; - } - - // -}; - -// -// Bearish Rejection Bar ... -class XCBearishRejectionBarObject : public XCRejectionBarObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param arrow: Integer, Specified Arrow Code ... - * @param rejectionBar: XCRejectionBar instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - int arrow, - XCRejectionBar &rejectionBar, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = rejectionBar.IsValid() && - rejectionBar.IsBearish(); - if (!result) - { - return result; - } - - // - result = CreateByRejection( - chart_id, - window, - arrow, - rejectionBar, - prefix // - ); - - // - return result; - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BEARISH_REJECTION_BAR_OBJ; - } - - // -}; - -// -// XCZoneObject ... -class XCZoneObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param name: String, Specified Object Identifier on Chart ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool CreateByZone( - long chart_id, - string name, - int window, - XCZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - bool isValidFrom = zone.IsValidFrom(); - bool isValidBoundary = zone.IsValidBoundary(); - - // - result = - // - IsValid(name) && - isValidFrom && - isValidBoundary - // - ; - if (!result) - { - return result; - } - - // - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - datetime from = zone.From(); - datetime to = NormalizeTime(zone.To()); - - // - double upper = zone.Upper(); - double lower = zone.Lower(); - - // - result = mRect.Create( - chart_id, - name, - window, - from, - upper, - to, - lower // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_ZONE_OBJ; - } - - // - // Setter(s) ... - - /** - * Set Zone Width ... - * - * @param value: Integer ... - */ - void ZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mRect.Width(value); - } - - /** - * Set Zone Color ... - * - * @param value: Color ... - */ - void ZoneColor(color value) - { - mRect.Color(value); - } - - /** - * Set Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void ZoneStyle(ENUM_LINE_STYLE value) - { - mRect.Style(value); - } - - /** - * Set Zone Fill ... - * - * @param value: Boolean ... - */ - void ZoneFill(bool value) - { - mRect.Fill(value); - } - - // - private: - // - CChartObjectRectangle mRect; - - // -}; - -// -// Support Zone ... -class XCSupportZoneObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCSupportZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCSupportZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_SUPPORT_ZONE_OBJ; - } -}; - -// -// Resistance Zone ... -class XCResistanceZoneObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCResistanceZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCResistanceZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_RESISTANCE_ZONE_OBJ; - } -}; - -// -// Supply Zone ... -class XCSupplyZoneObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCSupplyZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCSupplyZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_SUPPLY_ZONE_OBJ; - } -}; - -// -// Demand Zone ... -class XCDemandZoneObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCDemandZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCDemandZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_DEMAND_ZONE_OBJ; - } -}; - -// -// Bullish Order Block ... -class XCBullishOrderBlockObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCOrderBlock instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCOrderBlock &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBullish(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BULLISH_ORDERBLOCK_OBJ; - } -}; - -// -// Bearish Order Block ... -class XCBearishOrderBlockObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCOrderBlock instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCOrderBlock &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBearish(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BULLISH_ORDERBLOCK_OBJ; - } -}; - -// -// Bullish Fair Value Gaps ... -class XCBullishFairValueGapObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCOrderBlock instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCFVG &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBullish(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BULLISH_FVG_OBJ; - } -}; - -class XCConsolidationZoneObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XConsolidationZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XConsolidationZone &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - result = mRect.Create( - chart_id, - name, - window, - zone.from, - zone.upper, - zone.to, - zone.lower // - ); - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_CONSOLIDATION_ZONE_OBJ; - } - - // - // Setter(s) ... - - /** - * Set Zone Width ... - * - * @param value: Integer ... - */ - void ZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mRect.Width(value); - } - - /** - * Set Zone Color ... - * - * @param value: Color ... - */ - void ZoneColor(color value) - { - mRect.Color(value); - } - - /** - * Set Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void ZoneStyle(ENUM_LINE_STYLE value) - { - mRect.Style(value); - } - - /** - * Set Zone Fill ... - * - * @param value: Boolean ... - */ - void ZoneFill(bool value) - { - mRect.Fill(value); - } - - // - private: - // - CChartObjectRectangle mRect; - - // -}; - -// -// Bearish Fair Value Gaps ... -class XCBearishFairValueGapObject : public XCZoneObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCOrderBlock instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCFVG &zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBearish(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - - // - result = CreateByZone( - chart_id, - name, - window, - zone, - prefix // - ); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BEARISH_FVG_OBJ; - } -}; - -// -// Signal ... -class XCSignalObject : public XCBaseObject -{ - // - public: - // - - // - // Constructor ... - void XCSignalObject() - { - } - - // - // Deconstructor ... - void ~XCSignalObject() - { - } - - /** - * Create a Signal Object on Chart ... - * - * @param chart_id: Long ... - * @param name: String ... - * @param window: Integer ... - * @param signal: XSignal instance ... - * @param length: int, Specified Length of Signal ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - const int window, - XSignal &signal, - int length = 3, - string prefix = NULL // - ) - { - // - bool result = false; - - // - length = NormalizeInt(length, 3); - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - string name = signal.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - int delay = (PeriodSeconds(signal.period) * length); - datetime time1 = (datetime)((int)signal.time - delay); - datetime time2 = (datetime)((int)signal.time + delay); - - // - // TP ... - string tpName = ToString(X_TP) + "_" + nameMD5; - result = mTPTrend.Create( - chart_id, - tpName, - window, - time1, - signal.tp, - time2, - signal.tp // - ); - if (!result) - { - return result; - } - - // - // SL ... - string slName = ToString(X_SL) + "_" + nameMD5; - result = mSLTrend.Create( - chart_id, - slName, - window, - time1, - signal.sl, - time2, - signal.sl // - ); - if (!result) - { - // - mTPTrend.Delete(); - return result; - } - - // - // TARGET ... - bool hasTargets = HasChild(signal.targets); - if (hasTargets) - { - // - int targetsCount = ArraySize(signal.targets); - for (int i = 0; i < targetsCount; i++) - { - // - string targetName = ToString(X_TARGET) + "_" + ToString(i) + "_" + nameMD5; - CChartObjectTrend *mTargetTrend; - mTargetTrend = new CChartObjectTrend(); - result = mTargetTrend.Create( - chart_id, - targetName, - window, - time1, - signal.targets[i].target, - time2, - signal.targets[i].target // - ); - if (!result) - { - // - mTPTrend.Delete(); - mSLTrend.Delete(); - break; - } - - // - mTargetTrends.Add(mTargetTrend); - } - } - - // - // ENTRY ... - string entrName = ToString(X_ENTRY) + "_" + nameMD5; - result = mEntryTrend.Create( - chart_id, - entrName, - window, - time1, - signal.entry, - time2, - signal.entry // - ); - if (!result) - { - // - mTPTrend.Delete(); - mSLTrend.Delete(); - mTargetTrends.Clear(); - return result; - } - - // - // Set Object Name ... - ObjName(name); - - // - return result; - } - - // - // Setter(s) ... - - // - // TP ... - - /** - * Set TP Width ... - * - * @param value: Integer ... - */ - void TPWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mTPTrend.Width(value); - } - - /** - * Set TP Color ... - * - * @param value: Color ... - */ - void TPColor(color value) - { - mTPTrend.Color(value); - } - - /** - * Set TP Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void TPStyle(ENUM_LINE_STYLE value) - { - mTPTrend.Style(value); - } - - // - // SL ... - - /** - * Set SL Width ... - * - * @param value: Integer ... - */ - void SLWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSLTrend.Width(value); - } - - /** - * Set SL Color ... - * - * @param value: Color ... - */ - void SLColor(color value) - { - mSLTrend.Color(value); - } - - /** - * Set SL Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void SLStyle(ENUM_LINE_STYLE value) - { - mSLTrend.Style(value); - } - - // - // TARGET ... - - /** - * Set Target Width ... - * - * @param value: Integer ... - */ - void TargetWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Width(value); - } - } - - /** - * Set Target Color ... - * - * @param value: Color ... - */ - void TargetColor(color value) - { - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Color(value); - } - } - - /** - * Set Target Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void TargetStyle(ENUM_LINE_STYLE value) - { - // - for (int i = 0; i < mTargetTrends.Total(); i++) - { - // - CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); - iTrend.Style(value); - } - } - - // - // ENTRY ... - - /** - * Set Entry Width ... - * - * @param value: Integer ... - */ - void EntryWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mEntryTrend.Width(value); - } - - /** - * Set Entry Color ... - * - * @param value: Color ... - */ - void EntryColor(color value) - { - mEntryTrend.Color(value); - } - - /** - * Set Entry Style ... - * - * @param value: ENUM_LINE_STYLE ... - */ - void EntryStyle(ENUM_LINE_STYLE value) - { - mEntryTrend.Style(value); - } - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_SIGNAL_OBJ; - } - - // - private: - // - - // - CChartObjectTrend mTPTrend; - CChartObjectTrend mSLTrend; - CChartObjectTrend mEntryTrend; - CArrayObj mTargetTrends; -}; - -// -// XRR Object ... -class XCRRObject : public XCSignalObject -{ - // - // Public ... - public: - // - // Constructor ... - bool CreateBoxRR( - long chart_id, - const int window, - XBoxZone &box, - double &rewardRatios[], - int length = 3, - string prefix = NULL // - ) - { - // - bool result = false; - - // - length = NormalizeInt(length, 3); - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - XSignal signal; - result = ToSignal( - box, - signal, - rewardRatios // - ); - if (!result) - { - // - signal.Clean(); - - // - return result; - } - - // - result = Create( - chart_id, - window, - signal, - length, - prefix // - ); - - // - signal.Clean(); - - // - return result; - } -}; - -class XCOHCLObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param pivot: XPVPivot instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XOHCL &bar, - datetime to, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - IsValid(to); - if (!result) - { - return result; - } - - // - string name = bar.GetTag(); - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - // High Shadow ... - string hShadowName = ToString(X_BAR_H_SHW) + "_" + nameMD5; - - // - result = mHighShadowRect.Create( - chart_id, - hShadowName, - window, - bar.time, - bar.high, - to, - bar.GetUp() // - ); - if (!result) - { - return result; - } - - // - // Body ... - string bodyName = ToString(X_BAR_BDY) + "_" + nameMD5; - - // - result = mBodyRect.Create( - chart_id, - bodyName, - window, - bar.time, - bar.GetUp(), - to, - bar.GetDown() // - ); - if (!result) - { - // - mHighShadowRect.Delete(); - mHighShadowRect.Detach(); - return result; - } - - // - // Low Shadow ... - string lShadowName = ToString(X_BAR_L_SHW) + "_" + nameMD5; - - // - result = mLowShadowRect.Create( - chart_id, - lShadowName, - window, - bar.time, - bar.GetDown(), - to, - bar.low // - ); - if (!result) - { - // - mBodyRect.Delete(); - mBodyRect.Detach(); - mHighShadowRect.Delete(); - mHighShadowRect.Detach(); - return result; - } - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set High Shadow Width ... - * - * @param value: Integer ... - */ - void HighShadowWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mHighShadowRect.Width(value); - } - - /** - * Set High Shadow Color ... - * - * @param value: Color ... - */ - void HighShadowColor(color value) - { - mHighShadowRect.Color(value); - } - - /** - * Set High Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void HighShadowStyle(ENUM_LINE_STYLE value) - { - mHighShadowRect.Style(value); - } - - /** - * Set High Shadow Fill ... - * - * @param value: Boolean ... - */ - void HighShadowFill(bool value) - { - mHighShadowRect.Fill(value); - } - - /** - * Set Body Width ... - * - * @param value: Integer ... - */ - void BodyWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBodyRect.Width(value); - } - - /** - * Set Body Color ... - * - * @param value: Color ... - */ - void BodyColor(color value) - { - mBodyRect.Color(value); - } - - /** - * Set Body Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BodyStyle(ENUM_LINE_STYLE value) - { - mBodyRect.Style(value); - } - - /** - * Set Body Fill ... - * - * @param value: Boolean ... - */ - void BodyFill(bool value) - { - mBodyRect.Fill(value); - } - - /** - * Set Low Shadow Width ... - * - * @param value: Integer ... - */ - void LowShadowWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mLowShadowRect.Width(value); - } - - /** - * Set Low Shadow Color ... - * - * @param value: Color ... - */ - void LowShadowColor(color value) - { - mLowShadowRect.Color(value); - } - - /** - * Set Low Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void LowShadowStyle(ENUM_LINE_STYLE value) - { - mLowShadowRect.Style(value); - } - - /** - * Set Low Shadow Fill ... - * - * @param value: Boolean ... - */ - void LowShadowFill(bool value) - { - mLowShadowRect.Fill(value); - } - - void BarSpes( - int width = 1, - color clr = clrNONE, - ENUM_LINE_STYLE style = STYLE_SOLID, - bool fill = false // - ) - { - // - BodyWidth(width); - LowShadowWidth(width); - HighShadowWidth(width); - - // - BodyColor(clr); - LowShadowColor(clr); - HighShadowColor(clr); - - // - BodyStyle(style); - LowShadowStyle(style); - HighShadowStyle(style); - - // - BodyFill(fill); - LowShadowFill(fill); - HighShadowFill(fill); - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_OHCL_OBJ; - } - - // - private: - // - - // - // Props ... - CChartObjectRectangle mHighShadowRect; - CChartObjectRectangle mBodyRect; - CChartObjectRectangle mLowShadowRect; -}; - -class XCBoxObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param pivot: XPVPivot instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - string name, - double upper, - double lower, - datetime from, - datetime to, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - upper > 0 && - lower > 0 && - to > from && - IsValid(to) && - IsValid(name) && - IsValid(from) && - upper > lower; - if (!result) - { - return result; - } - - // - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - string nameMD5 = ToMD5(name); - - // - result = mRect.Create( - chart_id, - name, - window, - from, - upper, - to, - lower // - ); - if (!result) - { - return result; - } - - // - if (result) - { - ObjName(name); - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set Width ... - * - * @param value: Integer ... - */ - void BoxWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mRect.Width(value); - } - - /** - * Set Color ... - * - * @param value: Color ... - */ - void BoxColor(color value) - { - mRect.Color(value); - } - - /** - * Set Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BoxStyle(ENUM_LINE_STYLE value) - { - mRect.Style(value); - } - - /** - * Set Fill ... - * - * @param value: Boolean ... - */ - void BoxFill(bool value) - { - mRect.Fill(value); - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_BOX_OBJ; - } - - // - private: - // - - // - // Props ... - CChartObjectRectangle mRect; -}; - -// -// Zone Ticks ... - -// -// Specify How to Draws Specified Levels ... -struct XTickZoneLevelSpecs -{ - // - double percent; // Max Allowed Percent of Tick Zone ... - - // - // Label Info ... - color labelColor; - string labelFont; - int labelFontSize; - double labelAngel; - - // - // Zone Info ... - bool zoneFill; - int zoneWidth; - color zoneColor; - ENUM_LINE_STYLE zoneStyle; - - // - // Constructor ... - XTickZoneLevelSpecs() - { - Default(); - } - - // - // Tools ... - - /** - * Initialize Drawing Specs ... - * - * @param _percent: Double, Max Allowed Percent ... - * @param _labelColor: Color, Specified Label Color ... - * @param _zoneColoe: Color, Specified Zone Color ... - * @param _zoneFill: Boolean, Specified Fill Zone or not ... - * @param _zoneStyle: ENUM_LINE_STYLE member, Specified Zone Style ... - * @param _labelFontSize: Integer, Specified Label Font Size ... - * @param _labelFont: String, Specified Label Font Name ... - * @param _labelAngel: Double, Specified Label Angel ... - * - * @return ( bool ) - */ - bool Init( - double _percent, - color _labelColor = clrWhite, - color _zoneColor = clrWhite, - bool _zoneFill = false, - ENUM_LINE_STYLE _zoneStyle = STYLE_DOT, - int _zoneWidth = 1, - int _labelFontSize = 12, - string _labelFont = "Arial", - double _labelAngel = 0 // - ) - { - // - bool result = false; - - // - Default(); - - // - result = _percent > 0; - if (!result) - { - return result; - } - - // - percent = _percent; - labelColor = _labelColor; - zoneColor = _zoneColor; - zoneFill = _zoneFill; - zoneStyle = _zoneStyle; - - // - if (_zoneWidth > 0) - { - zoneWidth = _zoneWidth; - } - - // - if (_labelFontSize > 0) - { - labelFontSize = _labelFontSize; - } - - // - if (IsSpecifiedValid(_labelFont)) - { - labelFont = _labelFont; - } - - // - if (_labelAngel >= 0) - { - labelAngel = _labelAngel; - } - - // - result = IsValid(); - - // - return result; - } - - /** - * Set Default Properties ... - */ - void Default() - { - // - percent = 0; - - // - // Label ... - labelAngel = 0; - labelFontSize = 13; - labelFont = "Arial"; - labelColor = clrWhite; - - // - // Zone ... - zoneWidth = 1; - zoneFill = false; - zoneColor = clrWhite; - zoneStyle = STYLE_DOT; - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - // - percent > 0 && - // - // Zone ... - zoneWidth > 0 && - // - // Label ... - labelFontSize > 0 && - IsSpecifiedValid(labelFont) - // - ; - - // - return result; - } - - // -}; - -class XCTickZoneObject : public XCBaseObject -{ - // - public: - // - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param name: String, Specify Chart Object Identifier ... - * @param from: Datetime ... - * @param to: Datetime ... - * @param zone: XCTickZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - string name, - datetime from, - datetime to, - XCTickZone *zone, - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = - IsValid(name) && - zone.IsValid() && - IsValid(to) && - IsValid(from); - if (!result) - { - return result; - } - - // - double points = GetPoints(zone.symbol); - if (points <= 0) - { - points = 1; - } - double distance = 1 * points; - - // - if (IsValid(prefix)) - { - name = prefix + "_" + name; - } - - // - string rectName = "TKZ_" + name; - result = mRect.Create( - chart_id, - rectName, - window, - from, - zone.high, - to, - zone.low // - ); - if (!result) - { - return result; - } - - // - int fromToDiff = ((int)to - (int)from); - datetime labelsDate = (datetime)((int)to - (fromToDiff / 5)); - - // - string lblName = "LBLT_" + name; - result = mTLabel.Create( - chart_id, - lblName, - window, - labelsDate, - zone.high - distance // - ); - if (!result) - { - return result; - } - - // - mTLabel.Description("T: " + ToString(zone.percent) + "%"); - - // - string lblVName = "LBLV_" + name; - result = mVLabel.Create( - chart_id, - lblVName, - window, - labelsDate, - zone.low + (2.5 * distance) // - ); - if (!result) - { - return result; - } - - // - mVLabel.Description("V: " + ToString(zone.volumePercent) + "%"); - - // - ObjName(name); - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_TICK_ZONE_OBJ; - } - - // - // Getter(s) / Setter(s) ... - - /** - * Set Zone Width ... - * - * @param value: Integer ... - */ - void ZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mRect.Width(value); - } - - /** - * Set Zone Color ... - * - * @param value: Color ... - */ - void ZoneColor(color value) - { - mRect.Color(value); - } - - /** - * Set Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void ZoneStyle(ENUM_LINE_STYLE value) - { - mRect.Style(value); - } - - /** - * Set Zone Fill ... - * - * @param value: Boolean ... - */ - void ZoneFill(bool value) - { - mRect.Fill(value); - } - - /** - * Set Label Color ... - * - * @param value: Color ... - */ - void LabelColor(color value) - { - // - mTLabel.Color(value); - mVLabel.Color(value); - } - - /** - * Set Label Size ... - * - * @param value: Integer ... - */ - void LabelSize(int value) - { - // - mTLabel.FontSize(value); - mVLabel.FontSize(value); - } - - /** - * Set Label Font ... - * - * @param value: String ... - */ - void LabelFont(string value) - { - // - mTLabel.Font(value); - mVLabel.Font(value); - } - - /** - * Set Label Angle ... - * - * @param value: double ... - */ - void LabelAngle(double value) - { - // - mTLabel.Angle(value); - mVLabel.Angle(value); - } - - // - private: - // - // Props ... - CChartObjectRectangle mRect; - CChartObjectLabel mTLabel; - CChartObjectLabel mVLabel; - - // -}; -class XCTicksZoneObject : public XCBaseObject -{ - // - public: - // - - // - void ~XCTicksZoneObject() - { - mZones.Clear(); - } - - /** - * Creator ... - * - * @param chart_id: Long, Specified Chart ID ... - * @param window: Integer, Specified Chart Window ID ... - * @param zone: XCTicksZone instance ... - * @param prefix: String ... - * - * @return ( bool ) - */ - bool Create( - long chart_id, - int window, - XCTicksZone &zone, - XTickZoneLevelSpecs &specs[], - string prefix = NULL // - ) - { - // - bool result = false; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string name = zone.GetTag(); - int levels = zone.Levels(); - result = levels > 0; - if (!result) - { - return result; - } - - // - for (int i = 0; i < levels; i++) - { - // - XCTickZone *iZone = zone.GetZone(i); - XCTickZoneObject *iObj; - iObj = new XCTickZoneObject(); - bool isCreated = iObj.Create( - chart_id, - window, - ToString(i) + "_" + name, - zone.From(), - zone.To(), - iZone, - prefix // - ); - if (!isCreated) - { - break; - } - - // - XTickZoneLevelSpecs iSpec; - bool hasSpecs = FindSpecs( - iZone, - iSpec, - specs // - ); - if (hasSpecs) - { - // - // Label ... - iObj.LabelFont(iSpec.labelFont); - iObj.LabelAngle(iSpec.labelAngel); - iObj.LabelColor(iSpec.labelColor); - iObj.LabelSize(iSpec.labelFontSize); - - // - // Zone ... - iObj.ZoneFill(iSpec.zoneFill); - iObj.ZoneColor(iSpec.zoneColor); - iObj.ZoneWidth(iSpec.zoneWidth); - iObj.ZoneStyle(iSpec.zoneStyle); - } - - // - mZones.Add(iObj); - } - - // - if (result) - { - ObjName(name); - } - else - { - mZones.Clear(); - } - - // - return result; - } - - // - // Virtual ... - - /** - * Retrieve Object Type ... - * - * @return ( ENUM_XCHARTOBJECTS ) - */ - virtual ENUM_XCHARTOBJECTS Type() - { - return X_TICKS_ZONE_OBJ; - } - - // - // Getter(s) / Setter(s) ... - - // - // Actions ... - - /** - * Destroy Object ... - */ - void Destroy() - { - mZones.Clear(); - } - - /** - * Find Specified TickZone Drawing Specs ... - * - * @param zone: XCTickZone instance, reference to Search For it ... - * @param spec: XTickZoneLevelSpecs instance, reference to Result ... - * @param specs: XTickZoneLevelSpecs instance Collection for Search ... - * - * @return ( bool ) - */ - bool FindSpecs( - XCTickZone *zone, - XTickZoneLevelSpecs &spec, - XTickZoneLevelSpecs &specs[] // - ) - { - // - bool result = false; - - // - int count = ArraySize(specs); - result = - zone.IsValid() && - IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XTickZoneLevelSpecs iSpecs = specs[i]; - - // - bool isSpecValidForZone = - !spec.IsValid() - ? zone.percent <= iSpecs.percent - : zone.percent <= iSpecs.percent && - spec.percent > iSpecs.percent; - if (isSpecValidForZone) - { - spec = iSpecs; - } - } - - // - result = spec.IsValid(); - - // - return result; - } - - // - private: - // - // Props ... - CArrayObj mZones; - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-market.pattern.class.mq5 b/Documents/BKP/x-saherelm.x-market.pattern.class.mq5 deleted file mode 100644 index 560cb436..00000000 --- a/Documents/BKP/x-saherelm.x-market.pattern.class.mq5 +++ /dev/null @@ -1,4780 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XCMarketPatternDetector -// Description: provides all Alerts requirements ... -// -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Definitions ... - -// -// Implementation ... -class XCMarketPatternDetector : public XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - XBoxZone zones[]; - XBoxZone majorSupport; - XBoxZone minorSupport; - XBoxZone majorResistance; - XBoxZone minorResistance; - - // - // Constructor ... - XCMarketPatternDetector() - { - barAnalyser = new XCBarAnalyser(); - } - - // - // Deconstructor ... - ~XCMarketPatternDetector() - { - // - delete barAnalyser; - ZeroMemory(barAnalyser); - } - - // - // Actions / Helpers ... - - // - double CalculateQuarter() - { - // - double result = -1; - - // - // Validate ... - bool has = majorSupport.IsValid() && - majorResistance.IsValid(); - if (!has) - { - return result; - } - - // - result = majorSupport.upper + ((majorResistance.lower - majorSupport.upper) / 2); - - // - return result; - } - - // - // Analysers ... - - /** - * Check for Price Touch Support Level ... - * - * @param bar: XOHCL, Specified Bar ... - * @param supportBar: XOHCL, reference to holds Zone Bar ... - * @param supportBox: XBoxZone, reference to holds Zone Box ... - * @param validationLength: int, Validation Length ... - * @param maxAllowedLoopback: int, Max Allowed Loopback to Detection ... - * - * @return ( bool ) - */ - bool IsSupportTouched( - XOHCL &bar, - XOHCL &supportBar, - XBoxZone &supportBox, - int validationLength = 21, - int maxAllowedLoopback = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - supportBar.Clean(); - supportBox.Clean(); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Support Exists ... - result = HasSupport( - bar, - supportBar, - validationLength, - maxAllowedLoopback // - ); - if (!result) - { - // - supportBar.Clean(); - return result; - } - - // - // Extract Support Box ... - result = ToSupportBox( - supportBar, - supportBox // - ); - - // - // Retrieve Previous Bar ... - XOHCL pBar; - result = - result && - bar.GetPreviousBar(pBar); - - // - // Chekc Price of Bar ... - result = - result && - pBar.low < supportBox.upper; - - // - // Cleanup Resources ... - if (!result) - { - // - supportBar.Clean(); - supportBox.Clean(); - } - pBar.Clean(); - - // - return result; - } - - /** - * Check for Price Touch Resistance Level ... - * - * @param bar: XOHCL, Specified Bar ... - * @param supportBar: XOHCL, reference to holds Zone Bar ... - * @param supportBox: XBoxZone, reference to holds Zone Box ... - * @param validationLength: int, Validation Length ... - * @param maxAllowedLoopback: int, Max Allowed Loopback to Detection ... - * - * @return ( bool ) - */ - bool IsResistanceTouched( - XOHCL &bar, - XOHCL &resistanceBar, - XBoxZone &resistanceBox, - int validationLength = 21, - int maxAllowedLoopback = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - resistanceBar.Clean(); - resistanceBox.Clean(); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Resistance Exists ... - result = HasResistance( - bar, - resistanceBar, - validationLength, - maxAllowedLoopback // - ); - if (!result) - { - // - resistanceBar.Clean(); - return result; - } - - // - // Extract Resistance Box ... - result = ToResistanceBox( - resistanceBar, - resistanceBox // - ); - - // - // Retrieve Previous Bar ... - XOHCL pBar; - result = - result && - bar.GetPreviousBar(pBar); - - // - // Chekc Price of Bar ... - result = - result && - pBar.high > resistanceBox.lower; - - // - // Cleanup Resources ... - if (!result) - { - // - resistanceBar.Clean(); - resistanceBox.Clean(); - } - pBar.Clean(); - - // - return result; - } - - // - // Detectors ... - - /** - * Check Specified Bar is Peak or Vale ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param validationLength: int, Validation Length ... - * - * @return ( bool ) - */ - bool IsPV( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - int validationLength = 7, - ENUM_X_PRICE peakPriceType = X_PRICE_HIGH, // - ENUM_X_PRICE valePriceType = X_PRICE_LOW // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Normalize ... - validationLength = NormalizeInt(validationLength, 2); - - // - // Validate ... - result = bar.IsValid() && - IsXValid(peakPriceType) && - IsXValid(valePriceType); - if (!result) - { - return result; - } - - // - int valeIndex = -1; - double vale = bar.FindLowest( - valeIndex, - validationLength, - valePriceType // - ); - double barVale = bar.GetPrice(valePriceType); - bool isVale = - NotEmptyZero(vale) && - NotEmptyZero(barVale) && - IsValidIndex(valeIndex) && - vale >= barVale; - - // - int peakIndex = -1; - double peak = bar.FindHighest( - peakIndex, - validationLength, - peakPriceType // - ); - double barPeak = bar.GetPrice(peakPriceType); - bool isPeak = - NotEmptyZero(peak) && - NotEmptyZero(barPeak) && - IsValidIndex(peakIndex) && - peak <= barPeak; - - // - result = (isVale && !isPeak) || - (isPeak && !isVale); - if (result) - { - // - dir = - isVale - ? X_DIRECTION_BULLISH - : isPeak - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - - // - return result; - } - - /** - * Check Specified Bar is Momentum Bar or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param requiredBars: int, bar range for approve Momentum ... - * @param approvedMultiplier: double, a Multipler for approve Momentum ... - * - * @return ( bool ) - */ - bool IsMomentumBar( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - int requiredBars = 3, - double approvedMultiplier = 2 // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Normalizing ... - requiredBars = NormalizeInt(requiredBars, 3, 10); - approvedMultiplier = NormalizeDouble(approvedMultiplier, 2, 5); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Calculate Requirements ... - - // - XOHCL iBar; - bool has = false; - double rangeBody = 0; - int start = bar.Index() + 1; - int end = start + requiredBars; - for (int i = start; i < end; i++) - { - // - // Initialized Bar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - - // - // Summarize Body Sizes ... - if (has) - { - rangeBody += iBar.GetBody(); - } - - // - iBar.Clean(); - } - - // - // Calculate Body Approvement ... - result = bar.GetBody() >= (approvedMultiplier * rangeBody); - if (!result) - { - return result; - } - - // - // Check Direction ... - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar is Engulfed Bar or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * - * @return ( bool ) - */ - bool IsEngulfedBar( - XOHCL &bar, - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Calculate Requirements ... - - // - XOHCL iBar; - result = bar.GetPreviousBar(iBar); - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - // Check Prev Bar Must Inside Bar ... - result = bar.GetUp() > iBar.GetUp() && - bar.GetDown() < iBar.GetDown(); - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - // Check Directions ... - bool isBullish = - iBar.IsBearish() && - bar.IsBullish(); - bool isBearish = - iBar.IsBullish() && - bar.IsBearish(); - result = isBullish || isBearish; - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar is True Gapped Bar or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param approvedPointMultiplier: double, Gap Validation Multiplier in Point ... - * - * @return ( bool ) - */ - bool IsTrueGapedBar( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - double approvedPointMultiplier = 1 // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Normalizing ... - approvedPointMultiplier = NormalizeDouble(approvedPointMultiplier, 1, 100); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Calculate Requirements ... - - // - XOHCL iBar; - result = bar.GetPreviousBar(iBar); - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - // Check Directions ... - bool isBullish = - iBar.IsBullish() && - bar.IsBullish(); - bool isBearish = - iBar.IsBearish() && - bar.IsBearish(); - result = isBullish || isBearish; - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - double point = GetPoints(bar.symbol); - double approvedGapSize = approvedPointMultiplier * point; - - // - // Check Gap Exists ... - result = - isBullish - ? bar.low > iBar.high - : iBar.low > bar.high; - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - // Validate Gap Size ... - double gapSize = isBullish - ? bar.low - iBar.high - : iBar.low - bar.high; - result = gapSize >= approvedGapSize; - if (!result) - { - // - iBar.Clean(); - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar is Pinned Bar or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param shadowApprovedMultiplier: double, Shadow Size Approve Multiplier ... - * @param minimumPinBarRangeMultiplier: doubble, Range Size Approve Multiplier in Point ... - * @param forceDirection: bool, Apply Force Bar Type ... - * - * @return ( bool ) - */ - bool IsPinnedBar( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - double shadowApprovedMultiplier = 3, - double minimumPinBarRangeMultiplier = 4, - bool forceDirection = false // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Normalizing ... - shadowApprovedMultiplier = NormalizeDouble(shadowApprovedMultiplier, 2, 5); - minimumPinBarRangeMultiplier = NormalizeDouble(minimumPinBarRangeMultiplier, 2, 100); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Calculate Requirements ... - double body = bar.GetBody(); - double lowShadow = bar.GetLowShadow(); - double highShadow = bar.GetHighShadow(); - - // - // Check Directions ... - bool isBullish = - lowShadow > body && - lowShadow > highShadow && - lowShadow >= (body * shadowApprovedMultiplier); - bool isBearish = - highShadow > body && - highShadow > lowShadow && - highShadow > (body * shadowApprovedMultiplier); - result = isBullish || isBearish; - if (!result) - { - return result; - } - - // - // Checking Force Bar Type ... - if (forceDirection) - { - // - result = - isBullish - ? bar.IsBullish() - : bar.IsBearish(); - } - if (!result) - { - return result; - } - - // - // Check Range Validation ... - double point = GetPoints(bar.symbol); - double approvedRange = minimumPinBarRangeMultiplier * point; - result = bar.GetRange() >= approvedRange; - if (!result) - { - return result; - } - - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - - // - return result; - } - - /** - * Check Specified Bar has Star Pattern or not ... - * Morning Star => Bullish - * Evening Star => Bearish - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * - * @return ( bool ) - */ - bool IsStarPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Get Requirements ... - XOHCL pBar, p2Bar; - result = bar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Check Directions ... - bool isBullish = - bar.IsBullish() && - p2Bar.IsBearish(); - bool isBearish = - bar.IsBearish() && - p2Bar.IsBullish(); - result = isBullish || isBearish; - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Checking Gap Exists Between Bars ... - result = - isBullish - ? p2Bar.GetDown() > pBar.GetUp() && - pBar.GetUp() < bar.GetDown() - : p2Bar.GetUp() < pBar.GetDown() && - pBar.GetDown() > bar.GetUp(); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Check Bar Close Validation ... - double barClosedApprovedPrice = p2Bar.GetDown() + ((p2Bar.GetUp() - p2Bar.GetDown()) / 2); - result = - isBullish - ? bar.close > barClosedApprovedPrice - : bar.close < barClosedApprovedPrice; - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Validating PBar Body and Shadow ... - double body = pBar.GetBody(); - double lowShadow = pBar.GetLowShadow(); - double highShadow = pBar.GetHighShadow(); - result = - body < bar.GetBody() && - body < p2Bar.GetBody() && - (isBullish - ? lowShadow > body && - lowShadow > highShadow - : highShadow > body && - highShadow > lowShadow); - if (!result) - { - // - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar has Pirecing Pattern or not ... - * Piercing => Bullish - * Dark Cloud Cover => Bearish - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * - * @return ( bool ) - */ - bool IsPiercingPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL pBar; - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Check Directions ... - bool isBullish = - bar.IsBullish() && - pBar.IsBearish(); - bool isBearish = - bar.IsBearish() && - pBar.IsBullish(); - result = isBullish || isBearish; - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Check Bar Close ... - double barCloseApprovedPrice = pBar.GetDown() + ((pBar.GetUp() - pBar.GetDown()) / 2); - result = - isBullish - ? bar.close > barCloseApprovedPrice - : bar.close < barCloseApprovedPrice; - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - pBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar has Rising Pattern or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * - * @return ( bool ) - */ - bool IsRisingPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Reading Required Bars ... - XOHCL iBar; - XOHCL bars[]; - bool has = false; - int start = bar.Index(); - int end = start + 5; - for (int i = start; i < end; i++) - { - // - // Initialized Bar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (has) - { - // - AddRef( - iBar, - bars // - ); - } - - // - iBar.Clean(); - } - result = ArraySize(bars) == 5; - if (!result) - { - // - iBar.Clean(); - SpecifiedClean(bars); - - // - return result; - } - - // - // Check Directions ... - bool isBullish = - bars[0].IsBullish() && - bars[4].IsBullish() && - bars[1].IsBearish() && - bars[2].IsBearish() && - bars[3].IsBearish(); - bool isBearish = - bars[0].IsBearish() && - bars[4].IsBearish() && - bars[1].IsBullish() && - bars[2].IsBullish() && - bars[3].IsBullish(); - result = isBullish || isBearish; - if (!result) - { - // - iBar.Clean(); - SpecifiedClean(bars); - - // - return result; - } - - // - // Check Range Validation ... - double upper = bars[4].GetUp(); - double lower = bars[4].GetDown(); - - // - double max = MathMax(bars[1].GetUp(), bars[2].GetUp()); - max = MathMax(max, bars[3].GetUp()); - - // - double min = MathMin(bars[1].GetDown(), bars[2].GetDown()); - min = MathMin(min, bars[3].GetDown()); - - // - result = - max < upper && - min > lower && - (isBullish - ? bars[0].close > bars[4].GetUp() - : bars[0].close < bars[4].GetDown()); - if (!result) - { - // - iBar.Clean(); - SpecifiedClean(bars); - - // - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - iBar.Clean(); - SpecifiedClean(bars); - - // - return result; - } - - /** - * Check Specified Bar has Flag Pattern or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param swingBar: XOHCL, Detected Swing Bar ... - * @param minimumPullbackBars: int, Minimum Shoulders of Swing Bar ... - * - * @return ( bool ) - */ - bool IsFlagPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XOHCL &swingBar, - int minimumPullbackBars = 3 // - ) - { - // - bool result = false; - - // - // Prepare ... - swingBar.Clean(); - CleanDirection(dir); - - // - // Normalizing ... - minimumPullbackBars = NormalizeInt(minimumPullbackBars, 3, 10); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Reading Previous Bar ... - XOHCL pBar; - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Check Directions ... - bool isBullish = - bar.IsBullish() && - bar.close > pBar.GetUp(); - bool isBearish = - bar.IsBearish() && - bar.close < pBar.GetDown(); - result = isBullish || isBearish; - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Detect Swing Bar ... - ENUM_X_SWING_TYPE swingType = - isBullish - ? X_SWING_HIGH - : X_SWING_LOW; - result = - result && - IsXValid(swingType) && - bar.FindNextSwingBar( - swingType, - swingBar, - minimumPullbackBars // - ) && - (isBullish - ? swingBar.IsBullish() && - swingBar.high > pBar.high - : swingBar.IsBearish() && - swingBar.low < pBar.low); - if (!result) - { - // - pBar.Clean(); - swingBar.Clean(); - - // - return result; - } - - // - dir = bar.GetDirection(); - - // - // Get Result ... - result = HasDirection(dir); - - // - // Cleanup Resources ... - pBar.Clean(); - if (!result) - { - swingBar.Clean(); - } - - // - return result; - } - - /** - * Check Specified Bar has SignalKey Bar Pattern or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param shadowApprovedMultiplier: double, Shadow Size Approve Multiplier ... - * @param minimumPinBarRangeMultiplier: doubble, Range Size Approve Multiplier in Point ... - * @param forceDirection: bool, Apply Force Bar Type ... - * - * @return ( bool ) - */ - bool IsSignalKeyBarPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - double shadowApprovedMultiplier = 3, - double minimumPinBarRangeMultiplier = 4, - bool forceDirection = false // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Get Requirements ... - XOHCL pBar; - result = bar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // Chck Previous Bar must Pinned ... - result = IsPinnedBar( - pBar, - dir, - shadowApprovedMultiplier, - minimumPinBarRangeMultiplier, - forceDirection // - ); - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - // Check Direction ... - bool isBullish = - bar.IsBullish() && - IsSpecifiedBullish(dir) && - bar.close > pBar.high; - bool isBearish = - bar.IsBearish() && - IsSpecifiedBearish(dir) && - bar.close < pBar.low; - result = isBullish || isBearish; - if (!result) - { - // - pBar.Clean(); - return result; - } - - // - dir = bar.GetDirection(); - - // - result = HasDirection(dir); - - // - // Cleanup Resources ... - pBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar has Pullback Bar Pattern or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param zone: XBoxZone, refrence to hold detected zone ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param pullbackLength: int, min required indirectional bars to confirm pullback ... - * @param forceBreak: bool, force pullback bar breaks peak or vale of Zone ... - * - * @return ( bool ) - */ - bool IsPullbackPattern( - XOHCL &bar, - XBoxZone &zone, - ENUM_X_DIRECTION &dir, - int pullbackLength = 2, - bool forceBreak = false // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - CleanDirection(dir); - - // - // Normalize ... - pullbackLength = NormalizeInt(pullbackLength, 2); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // First Bar Direction ... - dir = bar.GetDirection(); - result = HasDirection(dir); - if (!result) - { - return result; - } - - // - // Loop through Pullback Length ... - XOHCL iBar; - datetime from = NULL; - double max = EMPTY_VALUE; - double min = EMPTY_VALUE; - int start = bar.Index() + 1; - int end = start + pullbackLength; - for (int i = start; i < end; i++) - { - // - // Initialize Indexed Bar ... - iBar.Clean(); - result = bar.BarAt(i, iBar) && - iBar.GetDirection() == Opposit(dir); - if (!result) - { - break; - } - - // - // Calculate Max and Min ... - max = - !NotEmptyZero(max) - ? iBar.high - : MathMax(max, iBar.high); - min = - !NotEmptyZero(min) - ? iBar.low - : MathMin(min, iBar.low); - from = iBar.time; - } - - // - // Apply Force Break ... - if (result && - forceBreak) - { - // - result = - result && - NotEmptyZero(min) && - NotEmptyZero(max) && - (IsXBullish(dir) - ? bar.close > max - : bar.close < min); - } - - // - // Prepare Zone ... - if (result) - { - // - ToBox( - bar, - zone, - dir, - ToXString(X_BAR_PATTERN_PULLBACK) // - ); - zone.upper = max; - zone.lower = min; - zone.from = from; - zone.at = bar.time; - zone.to = bar.time; - - // - result = zone.IsValid(); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - CleanDirection(dir); - } - iBar.Clean(); - - // - return result; - } - - /** - * Check Market Has Consolidation Pattern or not ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param zone: XBoxZone, refrence to hold detected zone ... - * @param dir: ENUM_X_DIRECTION, reference to holds Detected Order Flow Direction ... - * @param validationLength: int, Validation Length ... - * @param breakPriceType: ENUM_X_PRICE, Specified Price Type to Breake Consolidation ... - * @param upperPriceType: ENUM_X_PRICE, Specified Price Type to Detected Upper of Consolidation ... - * @param lowerPriceType: ENUM_X_PRICE, Specified Price Type to Detected Lower of Consolidation ... - * - * @return ( bool ) - */ - bool IsConsolidationPattern( - XOHCL &bar, - XBoxZone &zone, - ENUM_X_DIRECTION &dir, - int validationLength = 5, - ENUM_X_PRICE breakPriceType = X_PRICE_CLOSE, - ENUM_X_PRICE upperPriceType = X_PRICE_HIGH, - ENUM_X_PRICE lowerPriceType = X_PRICE_LOW // - ) - { - // - // Descriptions: - // =============== - // Consolidation Zones Happens by Highest High and Lowest Low - // of Specified Range which Breakes From one Side ... - // - - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - CleanDirection(dir); - - // - // Normalize ... - validationLength = NormalizeInt(validationLength, 3); - - // - // Validate ... - result = bar.IsValid() && - IsXValid(lowerPriceType) && - IsXValid(upperPriceType) && - IsXValid(breakPriceType); - if (!result) - { - return result; - } - - // - // Define Requirements ... - XOHCL iBar; - bool has = false; - datetime to = NULL; - datetime from = NULL; - double iLow = EMPTY_VALUE; - bool hasLowShadow = false; - double lower = EMPTY_VALUE; - double upper = EMPTY_VALUE; - double iHigh = EMPTY_VALUE; - bool hasHighShadow = false; - double iPrice = EMPTY_VALUE; - bool isLowerBreaked = false; - bool isUpperBreaked = false; - - // - // Loop Through Bars ... - int barIndex = bar.Index(); - int idx = barIndex; - bool canLookup = IsValidIndex(idx); - while (canLookup) - { - // - // Initialize Indexed Bar ... - idx++; - iBar.Clean(); - result = bar.BarAt(idx, iBar); - if (!result) - { - break; - } - - // - // Update Time ... - if (idx == barIndex + 1) - { - to = iBar.time; - } - - // - // Extract Low and High Price ... - iLow = iBar.GetPrice(lowerPriceType); - iHigh = iBar.GetPrice(upperPriceType); - result = NotEmptyZero(iLow) && - NotEmptyZero(iHigh); - if (!result) - { - break; - } - - // - // Check Bar Has Low/High Shadow ... - hasLowShadow = iBar.GetLowShadow() > iBar.GetHighShadow(); - hasHighShadow = iBar.GetHighShadow() > iBar.GetLowShadow(); - - // - // Update Range Lower and Upper based on Shadows ... - - // - // Lower ... - if (hasLowShadow) - { - // - // Check Can Update ... - has = - !NotEmptyZero(lower) - ? true - : iLow < lower; - if (has) - { - lower = iLow; - } - } - - // - // Upper ... - if (hasHighShadow) - { - // - // Check Can Update ... - has = - !NotEmptyZero(upper) - ? true - : iHigh > upper; - if (has) - { - upper = iHigh; - } - } - - // - // Check Price Breakes ... - iPrice = iBar.GetPrice(breakPriceType); - result = NotEmptyZero(iPrice); - if (!result) - { - break; - } - - // - // Check Upper/Lower breakes ... - isLowerBreaked = iPrice < lower; - isUpperBreaked = iPrice > upper; - - // - canLookup = (!isLowerBreaked && !isUpperBreaked); - if (!canLookup) - { - break; - } - - // - from = iBar.time; - } - - // - // Validate Calculations ... - result = - // - IsXValid(to) && - IsXValid(from) && - from < to && - // - NotEmptyZero(lower) && - NotEmptyZero(upper) && - upper > lower - // - ; - - // - // Validate To Edge Breakes ... - if (result) - { - // - iPrice = bar.GetPrice(breakPriceType); - result = NotEmptyZero(iPrice); - - // - // Validate To Edge Breakes ... - if (result) - { - // - isUpperBreaked = iPrice > upper; - isLowerBreaked = iPrice < lower; - - // - // Validate To Break ... - result = isUpperBreaked || isLowerBreaked; - } - - // - // Prepare Direction ... - if (result) - { - // - dir = - isUpperBreaked - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Validate Direction ... - result = HasDirection(dir); - } - - // - // Prepare Zone ... - if (result) - { - // - zone.to = to; - zone.dir = dir; - zone.from = from; - zone.at = bar.time; - zone.upper = upper; - zone.lower = lower; - zone.symbol = bar.symbol; - zone.period = bar.period; - zone.type = ToXString(X_BAR_PATTERN_CONSOLIDATION); - - // - // Validate Zone ... - result = zone.IsValid(); - - // - // Validate Zone Length ... - if (result) - { - result = zone.FromIndex() - zone.ToIndex() >= validationLength; - } - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - CleanDirection(dir); - } - iBar.Clean(); - - // - return result; - } - - /** - * Detect Order Flow ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param dir: ENUM_X_DIRECTION, reference to holds Detected Order Flow Direction ... - * @param orderFlow: XBoxZone, collection reference to holds Detected Order Flow ... - * @param orderFlowValidation: int, number of sequential Zones for Validate Order Flow ... - * @param containsOBs: bool, Specified to Use Order Blocks in Order Flow Detection ... - * @param containsFVGs: bool, Specified to Use Fair Value Gaps in Order Flow Detection ... - * @param containsSupportResistances: bool, Specified to Use Support and Resistances in Order Flow Detection ... - * @param zonesLoopback: int, Zone Detection Loopback ... - * @param zonesValidationLength: int, Zone Validation Length ... - * @param loopback: int, Max Allowed Loopback Bars for Collecting ... - * - * @return ( bool ) - */ - bool HasOrderFlow( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XBoxZone &orderFlow[], - int orderFlowValidation = 2, - bool containsOBs = false, - bool containsFVGs = true, - bool containsSupportResistances = false, - int zonesLoopback = 5, - int zonesValidationLength = 21, - int loopback = 100 // - ) - { - // - bool result = false; - - // - // Prepare ... - XClean(orderFlow); - CleanDirection(dir); - int maxRequiredZone = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 10); - zonesLoopback = NormalizeInt(zonesLoopback, 3); - maxRequiredZone = NormalizeInt(maxRequiredZone, 0); - orderFlowValidation = NormalizeInt(orderFlowValidation, 1); - zonesValidationLength = NormalizeInt(zonesValidationLength, 3); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - // Collectiong Zones ... - XBoxZone tmp; - XBoxZone tmps[]; - XBoxZone _zones[]; - XBoxZone bullishZones[]; - XBoxZone bearishZones[]; - int bullishZonesCount = 0; - int bearishZonesCount = 0; - - // - // Order Blocks ... - if (containsOBs) - { - // - XClean(tmps); - CollectOBs(bar, tmps, zonesLoopback, maxRequiredZone, loopback); - FillNotExists(_zones, tmps); - } - - // - // Fair Value Gaps ... - if (containsFVGs) - { - // - XClean(tmps); - CollectFVGs(bar, tmps, zonesLoopback, maxRequiredZone, loopback); - FillNotExists(_zones, tmps); - } - - // - // Support and Resistances ... - if (containsSupportResistances) - { - // - XClean(tmps); - CollectZones(bar, tmps, zonesLoopback, maxRequiredZone, loopback); - FillNotExists(_zones, tmps); - } - - // - // Validate Zones ... - result = HasChild(_zones); - - // - // Extract Only Validated Zones ... - if (result) - { - // - ValidateBoxes( - _zones, - bar.Index() // - ); - - // - result = HasChild(_zones); - } - - // - // Separate Zones Direction ... - if (result) - { - // - bullishZonesCount = ExtractByDirection(bullishZones, _zones, X_DIRECTION_BULLISH); - bearishZonesCount = ExtractByDirection(bearishZones, _zones, X_DIRECTION_BEARISH); - - // - result = IsValidSize(bullishZonesCount) || - IsValidSize(bearishZonesCount); - } - - // - // Looking for Sequences of Zones ... - if (result) - { - // - int idx = -1; - bool has = false; - XBoxZone bullOrderFlow[]; - XBoxZone bearOrderFlow[]; - - // - // Bullish OrderFlow ... - - // - // Sorting ... - Copy(bullishZones, bullOrderFlow); - Sort( - bullOrderFlow, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH, - orderFlowValidation + 1 // - ); - bool hasBullishOrderFlow = ArraySize(bullOrderFlow) >= orderFlowValidation; - if (hasBullishOrderFlow) - { - // - // Validate Order Flow ... - Copy(bullOrderFlow, tmps); - XClean(bullOrderFlow); - while (HasChild(tmps)) - { - // - tmp.Clean(); - tmp = tmps[0]; - ArrayRemove(tmps, 0, 1); - - // - idx = GetHighest(tmps); - has = !IsValidIndex(idx) - ? true - : tmps[idx].lower < tmp.lower; - if (has) - { - AddIfNotExists(tmp, bullOrderFlow); - } - } - - // - hasBullishOrderFlow = ArraySize(bullOrderFlow) >= orderFlowValidation; - } - - // - // Bearish OrderFlow ... - - // - // Sorting ... - Copy(bearishZones, bearOrderFlow); - Sort( - bearOrderFlow, - X_SORT_BY_DATE, - X_DIRECTION_BULLISH, - orderFlowValidation + 1 // - ); - bool hasBearishOrderFlow = ArraySize(bearOrderFlow) >= orderFlowValidation; - if (hasBearishOrderFlow) - { - // - // Validate Order Flow ... - Copy(bearOrderFlow, tmps); - XClean(bearOrderFlow); - while (HasChild(tmps)) - { - // - tmp.Clean(); - tmp = tmps[0]; - ArrayRemove(tmps, 0, 1); - - // - idx = GetLowest(tmps); - has = !IsValidIndex(idx) - ? true - : tmps[idx].upper > tmp.upper; - if (has) - { - AddIfNotExists(tmp, bearOrderFlow); - } - } - - // - hasBearishOrderFlow = ArraySize(bearOrderFlow) >= orderFlowValidation; - } - - // - result = hasBullishOrderFlow || - hasBearishOrderFlow; - - // - // Validate Order Flows ... - if (result) - { - // - has = (hasBullishOrderFlow && !hasBearishOrderFlow) || - (hasBearishOrderFlow && !hasBullishOrderFlow); - - // - // When only Have One Direction ... - if (has) - { - // - if (hasBullishOrderFlow) - { - // - dir = X_DIRECTION_BULLISH; - Copy(bullOrderFlow, orderFlow); - } - else if (hasBearishOrderFlow) - { - // - dir = X_DIRECTION_BEARISH; - Copy(bearOrderFlow, orderFlow); - } - } - // - // When Two Direction Exists ... - else - { - // - // Retrieve Oldest Of Bullish / Bearish ... - int oldestBullIDX = GetOldest(bullOrderFlow); - int oldestBearIDX = GetOldest(bearOrderFlow); - result = IsValidIndex(oldestBullIDX) && - IsValidIndex(oldestBearIDX); - if (result) - { - // - dir = - bullOrderFlow[oldestBullIDX].from > bearOrderFlow[oldestBearIDX].from - ? X_DIRECTION_BULLISH - : bearOrderFlow[oldestBearIDX].from > bullOrderFlow[oldestBullIDX].from - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - result = HasDirection(dir); - if (result) - { - // - if (IsXBullish(dir)) - { - Copy(bullOrderFlow, orderFlow); - } - else if (IsXBearish(dir)) - { - Copy(bearOrderFlow, orderFlow); - } - } - } - } - - // - XClean(bullOrderFlow); - XClean(bearOrderFlow); - - // - result = HasChild(orderFlow) && - HasDirection(dir); - } - - // - // Validate Price ... - if (result) - { - // - int idx = -1; - if (IsXBullish(dir)) - { - // - idx = GetHighest(orderFlow); - result = IsValidIndex(idx) && - bar.low > orderFlow[idx].upper; - } - else - { - // - idx = GetLowest(orderFlow); - result = IsValidIndex(idx) && - bar.high < orderFlow[idx].lower; - } - } - - // - // Update To Time of Order Flow ... - if (result) - { - UpdateToTime(orderFlow, bar.time); - } - - // - // Cleanup ... - if (!result) - { - // - XClean(orderFlow); - CleanDirection(dir); - } - tmp.Clean(); - XClean(tmps); - XClean(_zones); - XClean(bullishZones); - XClean(bearishZones); - - // - return result; - } - - // - // FVG ... - - /** - * Check For FVG Exists in Specified Loopback Period ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param fvg: XBoxZone, reference for Holding FVG ... - * @param maxLoopback: int, Max Allowed Loopback to Lookup FVG ... - * - * @return ( bool ) - */ - bool HasFVG( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XBoxZone &fvg, - int maxLoopback = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - fvg.Clean(); - CleanDirection(dir); - - // - // Normalize ... - maxLoopback = NormalizeInt(maxLoopback, 3); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool has = false; - int start = bar.Index(); - int end = start + maxLoopback; - for (int i = start; i < end; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - continue; - } - - // - // Check iBar is FVG or not ... - has = barAnalyser.IsFVG( - iBar, - fvg, - true // Force Bar Type ... - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - CleanDirection(dir); - - // - continue; - } - - // - iBar.Clean(); - dir = fvg.dir; - - // - break; - } - - // - // Check FVG Exists ... - result = fvg.IsValid(); - - // - // Check Direction Exists ... - result = - result && - HasDirection(dir); - - // - // Cleanup Resources ... - if (!result) - { - // - fvg.Clean(); - CleanDirection(dir); - } - iBar.Clean(); - - // - return result; - } - - // - // OB ... - - /** - * Check For OB Exists in Specified Loopback Period ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param ob: XBoxZone, reference for Holding OB ... - * @param maxLoopback: int, Max Allowed Loopback to Lookup OB ... - * - * @return ( bool ) - */ - bool HasOB( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XBoxZone &ob, - int maxLoopback = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - ob.Clean(); - CleanDirection(dir); - - // - // Normalize ... - maxLoopback = NormalizeInt(maxLoopback, 3); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool has = false; - int start = bar.Index(); - int end = start + maxLoopback; - for (int i = start; i < end; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - continue; - } - - // - // Check iBar is OB or not ... - has = barAnalyser.IsOB( - iBar, - ob, - true, // Force FVG Bar Type ... - true // Force OB First Two Bar InDirection ... - ); - if (!has) - { - // - ob.Clean(); - iBar.Clean(); - CleanDirection(dir); - - // - continue; - } - - // - iBar.Clean(); - dir = ob.dir; - - // - break; - } - - // - // Check OB Exists ... - result = ob.IsValid(); - - // - // Check Direction Exists ... - result = - result && - HasDirection(dir); - - // - // Cleanup Resources ... - if (!result) - { - // - ob.Clean(); - CleanDirection(dir); - } - iBar.Clean(); - - // - return result; - } - - // - // Trending ... - - /** - * Check Trend Exists Based on Swings ... - * - * @param bar: XOHCL, Specified Bar ... - * @param dir: ENUM_X_DIRECTION a reference for Direction ... - * @param swings: XOHCL Array, Holds Swings ... - * @param numberOfSwings: int, Number of Swing Points for Detect Trend ... - * @param swingShoulders: int, Swing Shoulders Approvement Length ... - * - * @return ( bool ) - */ - bool HasSwingTrend( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XOHCL &swings[], - int numberOfSwings = 3, - int swingShoulders = 7 // - ) - { - // - bool result = false; - - // - // Prepare ... - CleanDirection(dir); - SpecifiedClean(swings); - - // - // Normalizing ... - numberOfSwings = NormalizeInt(numberOfSwings, 3, 10); - swingShoulders = NormalizeInt(swingShoulders, 3); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Trend Direction ... - XOHCL iSwing; - int idx = -1; - bool has = false; - XOHCL swingLows[]; - XOHCL swingHighs[]; - int lastSwingLowIndex = bar.Index(); - int lastSwingHighIndex = bar.Index(); - while (ArraySize(swingLows) < numberOfSwings || ArraySize(swingHighs) < numberOfSwings) - { - // - bool canLookupSwingLow = ArraySize(swingLows) < numberOfSwings; - bool canLookupSwingHigh = ArraySize(swingHighs) < numberOfSwings; - if (!canLookupSwingLow && !canLookupSwingHigh) - { - break; - } - - // - // Handle Swing Lows ... - if (canLookupSwingLow) - { - // - iSwing.Clean(); - idx = FindXSwing( - X_SWING_LOW, - bar.symbol, - bar.period, - lastSwingLowIndex + 1, - swingShoulders // - ); - has = IsValidIndex(idx); - if (has) - { - // - has = iSwing.Init( - bar.symbol, - bar.period, - idx // - ); - if (has) - { - // - AddRef( - iSwing, - swingLows // - ); - - // - lastSwingLowIndex = idx; - } - } - } - - // - // Handle Swing Highs ... - if (canLookupSwingHigh) - { - // - iSwing.Clean(); - idx = FindXSwing( - X_SWING_HIGH, - bar.symbol, - bar.period, - lastSwingHighIndex + 1, - swingShoulders // - ); - has = IsValidIndex(idx); - if (has) - { - // - has = iSwing.Init( - bar.symbol, - bar.period, - idx // - ); - if (has) - { - // - AddRef( - iSwing, - swingHighs // - ); - - // - lastSwingHighIndex = idx; - } - } - } - } - - // - // Check Trend Based On Swings ... - - // - // Check Directions ... - - // - bool isBullish = false; - bool isBearish = false; - - // - datetime oldestSwingLow = NULL; - datetime oldestSwingHigh = NULL; - - // - // Checking Bullish Trend based on Swing Lows ... - int count = ArraySize(swingLows); - for (int i = 0; i < count - 1; i++) - { - // - has = swingLows[i].low > swingLows[i + 1].low; - isBullish = - !isBullish - ? has - : isBullish && has; - if (!isBullish) - { - break; - } - - // - datetime oldeTime = MathMin(swingLows[i].time, swingLows[i + 1].time); - oldestSwingLow = - !IsSpecifiedValid(oldestSwingLow) - ? oldeTime - : MathMin(oldestSwingLow, oldeTime); - } - - // - // Checking Bearish Trend based on Swing Highs ... - count = ArraySize(swingHighs); - for (int i = 0; i < count - 1; i++) - { - // - has = swingHighs[i].high < swingHighs[i + 1].high; - isBearish = - !isBearish - ? has - : isBearish && has; - if (!isBearish) - { - break; - } - - // - datetime oldeTime = MathMin(swingHighs[i].time, swingHighs[i + 1].time); - oldestSwingHigh = - !IsSpecifiedValid(oldestSwingHigh) - ? oldeTime - : MathMin(oldestSwingHigh, oldeTime); - } - - // - result = isBullish || isBearish; - if (!result) - { - // - iSwing.Clean(); - SpecifiedClean(swingLows); - SpecifiedClean(swingHighs); - - // - return result; - } - - // - if (isBullish && - isBearish && - IsSpecifiedValid(oldestSwingLow) && - IsSpecifiedValid(oldestSwingHigh)) - { - // - // Here we Have to Detect Newest Trend or Oldest Trend ... - isBullish = oldestSwingLow < oldestSwingHigh; - isBearish = oldestSwingHigh < oldestSwingLow; - } - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (!result) - { - // - iSwing.Clean(); - SpecifiedClean(swingLows); - SpecifiedClean(swingHighs); - - // - return result; - } - - // - if (isBullish) - { - // - Copy( - swingLows, - swings // - ); - - // - dir = X_DIRECTION_BULLISH; - } - else - { - // - Copy( - swingHighs, - swings // - ); - - // - dir = X_DIRECTION_BEARISH; - } - - // - iSwing.Clean(); - SpecifiedClean(swingLows); - SpecifiedClean(swingHighs); - - // - return result; - } - - /** - * Check Specified Bar Has Support or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param support: XOHCL, Supported Bar ... - * @param validationLength: int, Validation Length ... - * @param maxAllowedLoopback: int, Max Allowed Loopback to Detection ... - * - * @return ( bool ) - */ - bool HasSupport( - XOHCL &bar, - XOHCL &support, - int validationLength = 21, - int maxAllowedLoopback = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - support.Clean(); - - // - // Normalizing ... - validationLength = NormalizeInt(validationLength, 7); - maxAllowedLoopback = NormalizeInt(maxAllowedLoopback, 21, 1500); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Find Support Swing ... - int idx = -1; - bool has = false; - int lookupIDX = bar.Index(); - while (!IsValidIndex(idx) && - lookupIDX < maxAllowedLoopback) - { - // - // Detect Swing ... - idx = FindXSwing( - X_SWING_LOW, - bar.symbol, - bar.period, - lookupIDX, - validationLength // - ); - has = IsValidIndex(idx); - if (!has) - { - // - lookupIDX++; - continue; - } - - // - // Retrieve Swing Bar ... - has = support.Init( - bar.symbol, - bar.period, - idx // - ); - if (!has) - { - // - idx = -1; - lookupIDX++; - support.Clean(); - continue; - } - - // - // Check Suppor Low Shadow ... - has = support.GetDown() < bar.low; - if (!has) - { - // - idx = -1; - lookupIDX++; - support.Clean(); - continue; - } - - // - if (IsValidIndex(idx)) - { - break; - } - } - - // - result = support.IsValid(); - - // - return result; - } - - /** - * Check Specified Bar Has Resistance or not ... - * - * @param bar: XOHCL, Specified Bar ... - * @param resistence: XOHCL, Resistanced Bar ... - * @param validationLength: int, Validation Length ... - * @param maxAllowedLoopback: int, Max Allowed Loopback to Detection ... - * - * @return ( bool ) - */ - bool HasResistance( - XOHCL &bar, - XOHCL &resistence, - int validationLength = 21, - int maxAllowedLoopback = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - resistence.Clean(); - - // - // Normalizing ... - validationLength = NormalizeInt(validationLength, 7); - maxAllowedLoopback = NormalizeInt(maxAllowedLoopback, 21, 1500); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Find Support Swing ... - int idx = -1; - bool has = false; - int lookupIDX = bar.Index(); - while (!IsValidIndex(idx) && - lookupIDX < maxAllowedLoopback) - { - // - // Detect Swing ... - idx = FindXSwing( - X_SWING_HIGH, - bar.symbol, - bar.period, - lookupIDX, - validationLength // - ); - has = IsValidIndex(idx); - if (!has) - { - // - lookupIDX++; - continue; - } - - // - // Retrieve Swing Bar ... - has = resistence.Init( - bar.symbol, - bar.period, - idx // - ); - if (!has) - { - // - idx = -1; - lookupIDX++; - resistence.Clean(); - continue; - } - - // - // Check Resistance High Shadow ... - has = resistence.GetUp() > bar.high; - if (!has) - { - // - idx = -1; - lookupIDX++; - resistence.Clean(); - continue; - } - - // - if (IsValidIndex(idx)) - { - break; - } - } - - // - result = resistence.IsValid(); - - // - return result; - } - - // - // Analysers ... - - /** - * Analyse Specified Bar ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param analysis: XPatternAnalysis, reference to holds Analysis result ... - * @param config: XPatternAnalysisConfig, reference to Provides Detector Configs ... - * - * @return ( bool ) - */ - bool AnalyseBarPatterns( - XOHCL &bar, - XPatternAnalysis &analysis, - XPatternAnalysisConfig &config // - ) - { - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - analysis.bar = bar; - analysis.time = TimeCurrent(); - - // - XOHCL iSwing; - XBoxZone iZone; - ENUM_X_DIRECTION iDir; - ENUM_X_BAR_PATTERN iPattern; - - // - bool has; - bool isBullish; - bool isBearish; - - // - bool canDetect; - bool canDetectBullish; - bool canDetectBearish; - - // - // Bars Detectors ... - - // - // XPV High Low Detection ... - canDetect = config.CanDetect(X_BAR_PATTERN_HIGH) || - config.CanDetect(X_BAR_PATTERN_LOW); - if (canDetect) - { - // - has = IsPV( - bar, - iDir, - config.pvValidationLength, - config.peakPriceType, - config.valePriceType // - ); - - // - canDetectBullish = config.CanDetect(X_BAR_PATTERN_LOW); - canDetectBearish = config.CanDetect(X_BAR_PATTERN_HIGH); - - // - isBullish = - has && - IsXBullish(iDir) && - canDetectBullish; - - // - isBearish = - has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - iPattern = - isBearish - ? X_BAR_PATTERN_HIGH - : X_BAR_PATTERN_LOW; - - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Momentum ... - iPattern = X_BAR_PATTERN_MOMENTUM; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsMomentumBar( - bar, - iDir, - config.momentumBarValidationLength, - config.momentumBarApprovedMultiplier // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Engulfed ... - iPattern = X_BAR_PATTERN_ENGULFED; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsEngulfedBar( - bar, - iDir // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // TrueGap ... - iPattern = X_BAR_PATTERN_TRUE_GAPED; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsTrueGapedBar( - bar, - iDir, - config.trueGapApprovedStrength // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Pinned ... - iPattern = X_BAR_PATTERN_PINNED; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsPinnedBar( - bar, - iDir, - config.pinBarShadowApprovedMultiplier, - config.pinBarRangeMultiplier, - config.pinBarForceDirection // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Pattern Detectors ... - - // - // Star ... - iPattern = X_BAR_PATTERN_STAR; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsStarPattern( - bar, - iDir // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Piercing ... - iPattern = X_BAR_PATTERN_PIERCING; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsPiercingPattern( - bar, - iDir // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Rising ... - iPattern = X_BAR_PATTERN_RISING; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsRisingPattern( - bar, - iDir // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Flag ... - iPattern = X_BAR_PATTERN_FLAG; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsFlagPattern( - bar, - iDir, - iSwing, - config.flagPatternPullbackLength // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - - // - analysis.flagSwing = iSwing; - } - } - - // - // SignalKey ... - iPattern = X_BAR_PATTERN_SIGNALKEY; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = IsSignalKeyBarPattern( - bar, - iDir, - config.pinBarShadowApprovedMultiplier, - config.pinBarRangeMultiplier, - config.pinBarForceDirection // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - IsXBullish(iDir) && - canDetectBullish; - isBearish = has && - IsXBearish(iDir) && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iDir // - ); - } - } - - // - // Zone Detectors ... - - // - // OB ... - iPattern = X_BAR_PATTERN_OB; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = barAnalyser.IsOB( - bar, - iZone, - config.fvgForceType, - config.obForceTwoBar // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - iZone.IsBullish() && - canDetectBullish; - isBearish = has && - iZone.IsBearish() && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iZone.dir // - ); - - // - analysis.ob = iZone; - } - } - - // - // FVG ... - iPattern = X_BAR_PATTERN_FVG; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = barAnalyser.IsFVG( - bar, - iZone, - config.fvgForceType // - ); - - // - canDetectBullish = config.CanDetect( - iPattern, - X_DIRECTION_BULLISH // - ); - canDetectBearish = config.CanDetect( - iPattern, - X_DIRECTION_BEARISH // - ); - - // - isBullish = has && - iZone.IsBullish() && - canDetectBullish; - isBearish = has && - iZone.IsBearish() && - canDetectBearish; - - // - canDetect = isBullish || - isBearish; - if (canDetect) - { - // - analysis.AddPattern( - iPattern, - iZone.dir // - ); - - // - analysis.fvg = iZone; - } - } - - // - // Support ... - iPattern = X_BAR_PATTERN_SUPPORT; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = HasSupport( - bar, - iSwing, - config.supportAndResistanceValidationLength, - config.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToSupportBox( - iSwing, - iZone, - bar.time, - config.supportAndResistanceValidationLength // - ); - if (has) - { - // - analysis.AddPattern( - iPattern, - iZone.dir // - ); - - // - analysis.support = iZone; - } - } - } - - // - // Resistance ... - iPattern = X_BAR_PATTERN_RESISTANCE; - canDetect = config.CanDetect(iPattern); - if (canDetect) - { - // - has = HasResistance( - bar, - iSwing, - config.supportAndResistanceValidationLength, - config.supportAndResistanceLoopbackLength // - ); - if (has) - { - // - has = ToResistanceBox( - iSwing, - iZone, - bar.time, - config.supportAndResistanceValidationLength // - ); - if (has) - { - // - analysis.AddPattern( - iPattern, - iZone.dir // - ); - - // - analysis.resistance = iZone; - } - } - } - - // - // Validate Analysis ... - result = analysis.IsValid(); - - // - // Update Quarter ... - if (result) - { - // - // Retrieve Previous Bar ... - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - // Update Quarter ... - UpdateZones( - bar, - analysis.quarterActions, - config.quarterZonesValidationLength, // Zones Validation Length ... - config.quarterZonesRequiredToStart, // Zones Count to Start Processing ... - config.quarterZoneDetectionLoopback // Zones Detection Loopback ... - ); - - // - // Fill Quarter Props ... - analysis.majorSupport = majorSupport; - analysis.minorSupport = minorSupport; - analysis.quarter = CalculateQuarter(); - analysis.majorResistance = majorResistance; - analysis.minorResistance = minorResistance; - - // - // Update To Times ... - if (analysis.majorSupport.IsValid()) - { - analysis.majorSupport.to = bar.time; - } - if (analysis.minorSupport.IsValid()) - { - analysis.minorSupport.to = bar.time; - } - if (analysis.majorResistance.IsValid()) - { - analysis.majorResistance.to = bar.time; - } - if (analysis.minorResistance.IsValid()) - { - analysis.minorResistance.to = bar.time; - } - } - } - - // - // Cleanup Resources ... - iZone.Clean(); - iSwing.Clean(); - CleanDirection(iDir); - - // - return result; - } - - /** - * Update and Manage Support and Resistance Zones ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param actions: ENUM_X_DETECTOR_ZONE_ACTION, refernce collection to Notify happens actions ... - * @param validationLength: int, Validation Length for Zones ... - * @param requiredZones: int, Number of required Zones to collecting ... - * @param loopback: int, Max Allowed Loopback Bars for Collecting ... - * - * @return ( int ) - */ - int UpdateZones( - XOHCL &bar, - ENUM_X_DETECTOR_ZONE_ACTION &actions[], - int validationLength = 3, - int requiredZones = 10, - int loopback = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(actions); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 100); - requiredZones = NormalizeInt(requiredZones, 5); - validationLength = NormalizeInt(validationLength, 2); - - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return result; - } - - // - int barIndex = bar.Index(); - - // - // Collect or Manage Zones ... - XOHCL zoneBar; - XBoxZone iZone; - bool hasZone = HasChild(zones); - int zonesCount = ArraySize(zones); - int zoneDetectionLoopback = (validationLength * 2); - if (!hasZone) - { - // - XOHCL iBar; - int start = barIndex; - int end = barIndex + loopback; - for (int i = start; i < end; i++) - { - // - // Extract Detected Zones ... - iBar.Clean(); - has = bar.BarAt(i, iBar); - if (!has) - { - continue; - } - - // - // Check Support ... - iZone.Clean(); - zoneBar.Clean(); - has = HasSupport( - iBar, - zoneBar, - validationLength, // Zone Validation Length ... - zoneDetectionLoopback // Zone Detection Loopback ... - ); - has = has && - ToSupportBox(zoneBar, iZone, bar.time); - if (has) - { - // - AddIfNotExists( - iZone, - zones // - ); - } - - // - // Check Resistance ... - iZone.Clean(); - zoneBar.Clean(); - has = HasResistance( - iBar, - zoneBar, - validationLength, // Zone Validation Length ... - zoneDetectionLoopback // Zone Detection Loopback ... - ); - has = has && - ToResistanceBox(zoneBar, iZone, bar.time); - if (has) - { - // - AddIfNotExists( - iZone, - zones // - ); - } - - // - // Validate Number of Zones ... - zonesCount = ArraySize(zones); - if (zonesCount >= requiredZones) - { - break; - } - } - - // - iBar.Clean(); - iZone.Clean(); - zoneBar.Clean(); - - // - // Update Has Zones ... - hasZone = HasChild(zones); - zonesCount = ArraySize(zones); - } - - // - // Manage Exists Zones ... - if (hasZone) - { - // - // Update Zones To Time ... - UpdateToTime(zones, bar.time); - - // - // Validate Zones ... - CheckZones(bar, zones); - - // - // Remove Breaked Zones ... - RemoveBreakedZones(zones); - - // - hasZone = HasChild(zones); - zonesCount = ArraySize(zones); - } - - // - // Minimum Exists Zones for Detecting majors ... - int minNumberOfZonesForMajors = 5; - bool canLookupMajor = hasZone && - zonesCount >= minNumberOfZonesForMajors; - - // - // Supports ... - - // - // Check Zones Existances ... - bool hasMajorSupport = majorSupport.IsValid(); - bool hasMinorSupport = minorSupport.IsValid(); - - // - // Check Major Support State ... - if (hasMajorSupport) - { - // - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - bool isBreaked = pBar.close < majorSupport.lower; - if (isBreaked) - { - // - int idx = -1; - has = FindIndex(idx, majorSupport, zones); - if (has) - { - zones[idx].breakAt = pBar.time; - } - majorSupport.Clean(); - minorSupport.Clean(); - hasMajorSupport = false; - hasMinorSupport = false; - Add( - X_DETECTOR_ZONE_ACTION_MAJOR_SUPPORT_BREAKED, - actions // - ); - } - } - - // - pBar.Clean(); - } - - // - // Look For Major Support ... - if (!hasMajorSupport) - { - // - minorSupport.Clean(); - hasMinorSupport = false; - - // - // Lookup Major ... - if (canLookupMajor) - { - // - int idx = GetLowestByDir(zones, X_DIRECTION_BULLISH); - hasMajorSupport = IsValidIndex(idx) && !IsXValid(zones[idx].breakAt); - if (hasMajorSupport) - { - // - majorSupport = zones[idx]; - Add( - X_DETECTOR_ZONE_ACTION_MAJOR_SUPPORT_DETECTED, - actions // - ); - } - } - } - - // - // Resistances ... - - // - // Check Zones Existances ... - bool hasMajorResistance = majorResistance.IsValid(); - bool hasMinorResistance = minorResistance.IsValid(); - - // - // Check Major Resistance State ... - if (hasMajorResistance) - { - // - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - bool isBreaked = pBar.close > majorResistance.upper; - if (isBreaked) - { - // - int idx = -1; - has = FindIndex(idx, majorResistance, zones); - if (has) - { - zones[idx].breakAt = pBar.time; - } - majorResistance.Clean(); - minorResistance.Clean(); - hasMajorResistance = false; - hasMinorResistance = false; - Add( - X_DETECTOR_ZONE_ACTION_MAJOR_RESISTANCE_BREAKED, - actions // - ); - } - } - - // - pBar.Clean(); - } - - // - // Look For Major Resistance ... - if (!hasMajorResistance) - { - // - minorResistance.Clean(); - hasMinorResistance = false; - - // - // Lookup Major ... - if (canLookupMajor) - { - // - int idx = GetHighestByDir(zones, X_DIRECTION_BEARISH); - hasMajorResistance = IsValidIndex(idx); - if (hasMajorResistance) - { - // - majorResistance = zones[idx]; - Add( - X_DETECTOR_ZONE_ACTION_MAJOR_RESISTANCE_DETECTED, - actions // - ); - } - } - } - - // - // Check Majors Exixsts ... - has = hasMajorSupport && - hasMajorResistance; - if (has) - { - // - double quarter = CalculateQuarter(); - - // - // For Looking up Minor Support, we - // have to Ensure Major Support Exists ... - if (hasMajorSupport) - { - // - majorSupport.to = bar.time; - - // - // Look for Minor Support ... - if (!hasMinorSupport) - { - // - XBoxZone _supports[]; - int _supportsCount = ExtractByDirection( - _supports, - zones, - X_DIRECTION_BULLISH // - ); - _supportsCount = RemoveBreakedZones(_supports); - has = IsValidSize(_supportsCount); - if (has) - { - // - // Remove Major ... - Remove( - majorSupport, - _supports // - ); - - // - // Count Remain Zones ... - _supportsCount = ArraySize(_supports); - has = IsValidSize(_supportsCount); - if (has) - { - // - // Minors Selected by Youngest ... - int idx = quarter > 0 - ? GetYoungestBelow(quarter, _supports) - : GetYoungest(_supports); - hasMinorSupport = IsValidIndex(idx) && !IsXValid(_supports[idx].breakAt); - if (hasMinorSupport) - { - // - minorSupport = _supports[idx]; - minorSupport.to = bar.time; - minorSupport.from = minorSupport.at; - Add( - X_DETECTOR_ZONE_ACTION_MINOR_SUPPORT_DETECTED, - actions // - ); - } - } - } - - // - XClean(_supports); - } - - // - // Validate Minor Support Place ... - if (quarter > 0 && - hasMinorSupport) - { - // - hasMinorSupport = minorSupport.upper < quarter; - if (!hasMinorSupport) - { - // - int idx = -1; - has = FindIndex( - idx, - minorSupport, - zones // - ); - if (has) - { - zones[idx].breakAt = bar.time; - } - minorSupport.Clean(); - } - } - - // - // Refine exists Minor Support ... - if (hasMinorSupport) - { - // - minorSupport.to = bar.time; - - // - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - // Check Break ... - bool isBreaked = pBar.close < minorSupport.lower; - if (isBreaked) - { - // - minorSupport.Clean(); - Add( - X_DETECTOR_ZONE_ACTION_MINOR_SUPPORT_BREAKED, - actions // - ); - } - - // - // Check Test ... - bool isTested = !isBreaked && - pBar.low < minorSupport.upper && - pBar.low > minorSupport.lower && - bar.close > minorSupport.lower && - bar.open > minorSupport.lower; - if (isTested) - { - // - Add( - X_DETECTOR_ZONE_ACTION_MINOR_SUPPORT_RETESTED, - actions // - ); - } - - // - // Check Refine ... - bool canRefine = !isBreaked && - pBar.low < minorSupport.lower && - pBar.close > minorSupport.lower; - if (canRefine) - { - // - minorSupport.upper = minorSupport.lower; - minorSupport.lower = pBar.low; - Add( - pBar.time, - minorSupport.refines // - ); - Add( - X_DETECTOR_ZONE_ACTION_MINOR_SUPPORT_REFINED, - actions // - ); - } - - // - // Check New Minor Support ... - has = !isTested && - !canRefine; - if (has) - { - // - // Check Above Minor Support has Support ... - XBoxZone _supports[]; - int _supportsCount = ExtractByDirection( - _supports, - zones, - X_DIRECTION_BULLISH // - ); - Remove(majorSupport, _supports); - Remove(minorSupport, _supports); - RemoveBreakedZones(_supports); - _supportsCount = ArraySize(_supports); - has = IsValidSize(_supportsCount); - if (has) - { - // - int idx = GetLowestAfter(minorSupport.from, _supports); - hasMinorSupport = IsValidIndex(idx) && - (quarter <= 0 - ? true - : _supports[idx].upper < quarter); - if (hasMinorSupport) - { - // - minorSupport = _supports[idx]; - minorSupport.to = bar.time; - minorSupport.from = minorSupport.at; - Add( - X_DETECTOR_ZONE_ACTION_MINOR_SUPPORT_DETECTED, - actions // - ); - } - } - } - } - - // - pBar.Clean(); - } - } - - // - // For Looking up Minor Resistance, we - // have to Ensure Major Resistance Exists ... - if (hasMajorResistance) - { - // - majorResistance.to = bar.time; - - // - // Look for Minor Resistance ... - if (!hasMinorResistance) - { - // - XBoxZone _resistances[]; - int _resistancesCount = ExtractByDirection( - _resistances, - zones, - X_DIRECTION_BEARISH // - ); - _resistancesCount = RemoveBreakedZones(_resistances); - has = IsValidSize(_resistancesCount); - if (has) - { - // - // Remove Major ... - Remove( - majorResistance, - _resistances // - ); - - // - // Count Remain Zones ... - _resistancesCount = ArraySize(_resistances); - has = IsValidSize(_resistancesCount); - if (has) - { - // - // Minors Selected Youngest ... - int idx = GetYoungestAbove(quarter, _resistances); - hasMinorResistance = IsValidIndex(idx); - if (hasMinorResistance) - { - // - minorResistance = _resistances[idx]; - minorResistance.to = bar.time; - minorResistance.from = minorResistance.at; - Add( - X_DETECTOR_ZONE_ACTION_MINOR_RESISTANCE_DETECTED, - actions // - ); - } - } - } - - // - XClean(_resistances); - } - - // - // Validate Minor Support Place ... - if (quarter > 0 && - hasMinorResistance) - { - // - hasMinorResistance = minorResistance.lower > quarter; - if (!hasMinorResistance) - { - // - int idx = -1; - has = FindIndex( - idx, - minorResistance, - zones // - ); - if (has) - { - zones[idx].breakAt = bar.time; - } - minorResistance.Clean(); - } - } - - // - // Refine exists Minor Resistance ... - if (hasMinorResistance) - { - // - minorResistance.to = bar.time; - - // - // Check Retesting ... - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - // Check Break ... - bool isBreaked = pBar.close > minorResistance.upper; - if (isBreaked) - { - // - minorResistance.Clean(); - Add( - X_DETECTOR_ZONE_ACTION_MINOR_RESISTANCE_BREAKED, - actions // - ); - } - - // - // Check Test ... - bool isTested = !isBreaked && - pBar.high > minorResistance.lower && - pBar.high < minorResistance.upper && - bar.close < minorResistance.upper && - bar.open < minorResistance.upper; - if (isTested) - { - // - Add( - X_DETECTOR_ZONE_ACTION_MINOR_RESISTANCE_RETESTED, - actions // - ); - } - - // - // Check Refine ... - bool canRefine = !isBreaked && - pBar.high > minorResistance.upper && - pBar.close < minorResistance.upper; - if (canRefine) - { - // - minorResistance.lower = minorResistance.upper; - minorResistance.upper = pBar.high; - Add( - pBar.time, - minorResistance.refines // - ); - Add( - X_DETECTOR_ZONE_ACTION_MINOR_RESISTANCE_REFINED, - actions // - ); - } - - // - // Check New Minor Resistace ... - has = !isTested && - !canRefine; - if (has) - { - // - // Check Above Minor Resistance has Resistance ... - XBoxZone _resistances[]; - int _resistancesCount = ExtractByDirection( - _resistances, - zones, - X_DIRECTION_BEARISH // - ); - Remove(majorResistance, _resistances); - Remove(minorResistance, _resistances); - RemoveBreakedZones(_resistances); - _resistancesCount = ArraySize(_resistances); - has = IsValidSize(_resistancesCount); - if (has) - { - // - int idx = GetHighestAfter(minorResistance.from, _resistances); - hasMinorResistance = IsValidIndex(idx) && - (quarter <= 0 - ? true - : _resistances[idx].lower > quarter); - if (hasMinorResistance) - { - // - minorResistance = _resistances[idx]; - minorResistance.to = bar.time; - minorResistance.from = minorResistance.at; - Add( - X_DETECTOR_ZONE_ACTION_MINOR_RESISTANCE_DETECTED, - actions // - ); - } - } - } - } - - // - pBar.Clean(); - } - } - } - else - { - // - int idx = -1; - - // - has = minorSupport.IsValid() && - FindIndex( - idx, - minorSupport, - zones // - ); - if (has) - { - zones[idx].breakAt = bar.time; - } - minorSupport.Clean(); - hasMinorSupport = false; - - // - has = minorResistance.IsValid() && - FindIndex( - idx, - minorResistance, - zones // - ); - if (has) - { - zones[idx].breakAt = bar.time; - } - minorResistance.Clean(); - hasMinorResistance = false; - } - - // - // Check Bar Zones to Update Zones ... - - // - // Check Support ... - iZone.Clean(); - zoneBar.Clean(); - has = HasSupport( - bar, - zoneBar, - validationLength, // Zone Validation Length ... - zoneDetectionLoopback // Zone Detection Loopback ... - ); - has = has && - ToSupportBox(zoneBar, iZone, bar.time); - if (has) - { - // - AddIfNotExists( - iZone, - zones // - ); - } - - // - // Check Resistance ... - iZone.Clean(); - zoneBar.Clean(); - has = HasResistance( - bar, - zoneBar, - validationLength, // Zone Validation Length ... - zoneDetectionLoopback // Zone Detection Loopback ... - ); - has = has && - ToResistanceBox(zoneBar, iZone, bar.time); - if (has) - { - // - AddIfNotExists( - iZone, - zones // - ); - } - - // - // Actions Counting ... - result = ArraySize(actions); - - // - // Cleanup ... - iZone.Clean(); - zoneBar.Clean(); - - // - return result; - } - - int CollectOBs( - XOHCL &bar, - XBoxZone &dest[], - int zonesLoopback = 5, - int maxRequiredZone = 0, - int loopback = 100 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 10); - zonesLoopback = NormalizeInt(zonesLoopback, 3); - maxRequiredZone = NormalizeInt(maxRequiredZone, 0); - - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return result; - } - - // - XOHCL iBar; - XBoxZone iBox; - ENUM_X_DIRECTION iDir; - int start = bar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - iBar.Clean(); - iBox.Clean(); - iDir = X_DIRECTION_NONE; - - // - has = bar.BarAt(i, iBar); - has = has && - HasOB(iBar, iDir, iBox, zonesLoopback); - if (has) - { - // - AddIfNotExists( - iBox, - dest // - ); - } - - // - has = maxRequiredZone <= 0 || - (maxRequiredZone > 0 && ArraySize(dest) < maxRequiredZone); - if (!has) - { - break; - } - } - - // - result = ArraySize(dest); - - // - // Cleanup ... - iBar.Clean(); - iBox.Clean(); - iDir = X_DIRECTION_NONE; - - // - return result; - } - - int CollectFVGs( - XOHCL &bar, - XBoxZone &dest[], - int zonesLoopback = 5, - int maxRequiredZone = 0, - int loopback = 100 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 10); - zonesLoopback = NormalizeInt(zonesLoopback, 3); - maxRequiredZone = NormalizeInt(maxRequiredZone, 0); - - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return result; - } - - // - XOHCL iBar; - XBoxZone iBox; - ENUM_X_DIRECTION iDir; - int start = bar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - iBar.Clean(); - iBox.Clean(); - iDir = X_DIRECTION_NONE; - - // - has = bar.BarAt(i, iBar); - has = has && - HasFVG(iBar, iDir, iBox, zonesLoopback); - if (has) - { - // - AddIfNotExists( - iBox, - dest // - ); - } - - // - has = maxRequiredZone <= 0 || - (maxRequiredZone > 0 && ArraySize(dest) < maxRequiredZone); - if (!has) - { - break; - } - } - - // - result = ArraySize(dest); - - // - // Cleanup ... - iBar.Clean(); - iBox.Clean(); - iDir = X_DIRECTION_NONE; - - // - return result; - } - - int CollectZones( - XOHCL &bar, - XBoxZone &dest[], - int zonesLoopback = 5, - int zonesValidationLength = 21, - int maxRequiredZone = 0, - int loopback = 100 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 10); - zonesLoopback = NormalizeInt(zonesLoopback, 3); - maxRequiredZone = NormalizeInt(maxRequiredZone, 0); - zonesValidationLength = NormalizeInt(zonesValidationLength, 3); - - // - // Validate ... - bool has = bar.IsValid(); - if (!has) - { - return result; - } - - // - XOHCL iBar; - XBoxZone iBox; - XOHCL iZoneBar; - int start = bar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - iBar.Clean(); - iBox.Clean(); - iZoneBar.Clean(); - - // - has = bar.BarAt(i, iBar); - if (!has) - { - continue; - } - - // - // Support ... - has = HasSupport(iBar, iZoneBar, zonesValidationLength, zonesLoopback); - if (has) - { - // - has = ToSupportBox(iZoneBar, iBox, bar.time, zonesValidationLength); - if (has) - { - // - AddIfNotExists( - iBox, - dest // - ); - } - } - - // - // Resistance ... - has = HasResistance(iBar, iZoneBar, zonesValidationLength, zonesLoopback); - if (has) - { - // - has = ToResistanceBox(iZoneBar, iBox, bar.time, zonesValidationLength); - if (has) - { - // - AddIfNotExists( - iBox, - dest // - ); - } - } - - // - has = maxRequiredZone <= 0 || - (maxRequiredZone > 0 && ArraySize(dest) < maxRequiredZone); - if (!has) - { - break; - } - } - - // - result = ArraySize(dest); - - // - // Cleanup ... - iBar.Clean(); - iBox.Clean(); - iZoneBar.Clean(); - - // - return result; - } - - /** - * Filter Zones ... - * - * @param bar: XOHCL, reference to Specified Filtering Bar ... - * @param source: XBoxZone, reference collection to hold's filtered zones ... - * @param filterDir: ENUM_X_DIRECTION, specified Filter Direction ... - * @param priceType: ENUM_X_PRICE, Specified Bar's Price type to Use for Filtering Zones ... - * @param forDir: ENUM_X_DIRECTION, Specified Zone's Direction to Handle Filtering ... - * - * @return ( int ) - */ - int FilterZones( - XOHCL &bar, - XBoxZone &source[], - ENUM_X_DIRECTION filterDir, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE // - ) - { - // - int result = 0; - - // - // Prepare ... - XBoxZone tmp[]; - Copy( - source, - tmp // - ); - XClean(source); - - // - // Validate ... - bool has = bar.IsValid() && - HasChild(tmp) && - IsXValid(priceType) && - HasDirection(filterDir); - if (!has) - { - // - XClean(tmp); - return result; - } - - // - XBoxZone iBox; - double price = bar.GetPrice(priceType); - bool isBullish = IsXBullish(filterDir); - while (HasChild(tmp)) - { - // - iBox = tmp[0]; - ArrayRemove(tmp, 0, 1); - - // - has = - // - // Direction Pass ... - (!HasDirection(forDir) - ? true - : forDir == iBox.dir) - // - && - // - // Price Pass ... - (isBullish - ? price > iBox.lower - : price < iBox.upper); - if (has) - { - AddIfNotExists(iBox, source); - } - - // - iBox.Clean(); - } - - // - result = ArraySize(source); - - // - // Cleanup ... - XClean(tmp); - iBox.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - // Tools / Actions ... - - /** - * Check Zones and Manage them ... - * - * @param forBar: XOHCL, reference to Specified Bar ... - * @param _zones: XBoxZone, reference to Specified Zone Collection ... - * @param sortBy: X_SORT_BY_DATE, Sort Zones by ... - * @param sortDir: ENUM_X_DIRECTION, Sort Zones in Direction ... - * @param maxAllowed: int, Specified Max Allowed Zones ... - */ - void CheckZones( - XOHCL &forBar, - XBoxZone &_zones[], - ENUM_X_SORT_BY sortBy = X_SORT_BY_DATE, - ENUM_X_DIRECTION sortDir = X_DIRECTION_BEARISH, - int maxAllowed = 50 // - ) - { - // - // Normalize ... - maxAllowed = NormalizeInt(maxAllowed, 0); - - // - // Validate ... - bool has = forBar.IsValid() && - HasChild(_zones); - if (!has) - { - return; - } - - // - // Looping Through Zones ... - int count = ArraySize(_zones); - for (int i = 0; i < count; i++) - { - // - // Check Break ... - has = IsXValid(_zones[i].breakAt); - if (has) - { - continue; - } - - // - _zones[i].to = forBar.time; - - // - // Check for Test ... - has = IsTested( - forBar, - _zones[i] // - ); - if (has) - { - // - Add( - forBar.time, - _zones[i].tests // - ); - } - - // - // Check for Inside ... - has = IsInside( - forBar, - _zones[i] // - ); - if (has) - { - // - Add( - forBar.time, - _zones[i].insides // - ); - } - - // - // Check for Break ... - has = IsBreaked( - forBar, - _zones[i] // - ); - if (has) - { - // - Add( - forBar.time, - _zones[i].breaks // - ); - } - - // - // Check for Act ... - has = IsActed( - forBar, - _zones[i] // - ); - if (has) - { - // - Add( - forBar.time, - _zones[i].acteds // - ); - } - - // - // Check for FakeBreakes ... - has = IsFakeBreaked( - forBar, - _zones[i] // - ); - if (has) - { - // - Add( - forBar.time, - _zones[i].fakeBreaks // - ); - } - - // - // Check for Valid Breakes ... - has = IsValidBreaked( - forBar, - _zones[i] // - ); - if (has) - { - _zones[i].breakAt = forBar.time; - } - } - - // - // Apply Sort and Cleanup ... - Sort( - _zones, - sortBy, - sortDir, - maxAllowed // - ); - } - - // - // Private ... - private: - // - // Props ... - XCBarAnalyser *barAnalyser; - - // - // Helpers ... - - /** - * Clean Specified Referenced Direction ... - * - * @param dir: ENUM_X_DIRECTION - */ - void CleanDirection(ENUM_X_DIRECTION &dir) - { - dir = X_DIRECTION_NONE; - } -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-poi.drawer.class copy.mq5 b/Documents/BKP/x-saherelm.x-poi.drawer.class copy.mq5 deleted file mode 100644 index 21fbd78c..00000000 --- a/Documents/BKP/x-saherelm.x-poi.drawer.class copy.mq5 +++ /dev/null @@ -1,1195 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XPOIDrawer -// Description: Provides Point of Interests -// Drawing Tools ... -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Classes/x-saherelm.x-cobject.class.mq5" -#include "../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" - -// -// Definitions ... - -// -// Extensions ... - -void AddObjects( - CArrayObj *&source, - CArrayObj &dest // -) -{ - // - bool has = source != NULL && - source.Total() > 0; - if (!has) - { - return; - } - - // - for (int i = 0; i < source.Total(); i++) - { - dest.Add(source.At(i)); - } -} - -// -// Implementations ... -class XCPOIDrawer : public XCBase -{ - // - public: - // - // Props ... - - // - XPOIStyle defaultBullishStyle; - XPOIStyle defaultBearishStyle; - - // - XPOIStyle boxBullishStyle; - XPOIStyle boxBearishStyle; - - // - // Constructor ... - void XCPOIDrawer() - { - // - Default(); - } - - // - // Deconstructor ... - void ~XCPOIDrawer() - { - // - boxBullishStyle.Clean(); - boxBearishStyle.Clean(); - defaultBullishStyle.Clean(); - defaultBearishStyle.Clean(); - } - - // - // Setter Getter (s) ... - - /** - * Get Prefix ... - * - * @return ( string ) - */ - string Prefix() - { - return mPrefix; - } - - /** - * Set Prifx ... - * - * @param value: String ... - */ - void Prefix(string value) - { - mPrefix = value; - } - - /** - * Get Chart ID ... - * - * @return ( long ) - */ - long ChartIdentification() - { - return mChartIdentification; - } - - /** - * Set Chart ID ... - * - * @param value: Long ... - */ - void ChartIdentification(long value) - { - // - if (value < 0) - { - value = 0; - } - - // - mChartIdentification = value; - } - - /** - * Get SubWindow Id ... - * - * @return ( int ) - */ - int SubWindowIdentification() - { - return mSubWindowIdentification; - } - - /** - * Set SubWindow Id ... - * - * @param value: Integer ... - */ - void SubWindowIdentification(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mSubWindowIdentification = value; - } - - // - // XOHCL ... - - /** - * Get Bar Width ... - * - * @return ( int ) - */ - int BarWidth() - { - return mBarWidth; - } - - /** - * Set Bar Width ... - * - * @param value: Integer ... - */ - void BarWidth(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mBarWidth = value; - } - - /** - * Get Bar Bullish Color ... - * - * @return ( color ) - */ - color BarBullishColor() - { - return mBarBullishColor; - } - - /** - * Set Bar Bullish Color ... - * - * @param value: Color ... - */ - void BarBullishColor(color value) - { - mBarBullishColor = value; - } - - /** - * Get Bar Bearish Color ... - * - * @return ( color ) - */ - color BarBearishColor() - { - return mBarBearishColor; - } - - /** - * Set Bar Bearish Color ... - * - * @param value: Color ... - */ - void BarBearishColor(color value) - { - mBarBearishColor = value; - } - - /** - * Get Fill Bar High Shadow State ... - * - * @return ( bool ) - */ - bool BarFillHighShadow() - { - return mBarFillHighShadow; - } - - /** - * Set Fill Bar High Shadow State ... - * - * @param value: Boolean ... - */ - void BarFillHighShadow(bool value) - { - mBarFillHighShadow = value; - } - - /** - * Get Bar High Shadow Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarHighShadowStyle() - { - return mBarHighShadowStyle; - } - - /** - * Set Bar High Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarHighShadowStyle(ENUM_LINE_STYLE value) - { - mBarHighShadowStyle = value; - } - - /** - * Get Fill Bar Body State ... - * - * @return ( bool ) - */ - bool BarFillBody() - { - return mBarFillBody; - } - - /** - * Set Fill Bar Body State ... - * - * @param value: Boolean ... - */ - void BarFillBody(bool value) - { - mBarFillBody = value; - } - - /** - * Get Bar Body Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarBodyStyle() - { - return mBarBodyStyle; - } - - /** - * Set Bar Body Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarBodyStyle(ENUM_LINE_STYLE value) - { - mBarBodyStyle = value; - } - - /** - * Get Fill Bar Low Show State ... - * - * @return ( bool ) - */ - bool BarFillLowShadow() - { - return mBarFillLowShadow; - } - - /** - * Set Fill Bar Low Show State ... - * - * @param value: Boolean ... - */ - void BarFillLowShadow(bool value) - { - mBarFillLowShadow = value; - } - - /** - * Get Bar Low Shadow Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarLowShadowStyle() - { - return mBarLowShadowStyle; - } - - /** - * Set Bar Low Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarLowShadowStyle(ENUM_LINE_STYLE value) - { - mBarLowShadowStyle = value; - } - - // - // Virtuals ... - - /** - * Apply Default Configurations ... - */ - virtual void Default() - { - // - // Apply Default Props ... - - // - Prefix(NULL); - ChartIdentification(0); - SubWindowIdentification(0); - - // - BarWidth(1); - BarBearishColor(clrRed); - BarBullishColor(clrLime); - BarFillBody(false); - BarFillHighShadow(false); - BarFillLowShadow(false); - BarBodyStyle(STYLE_DOT); - BarLowShadowStyle(STYLE_DOT); - BarHighShadowStyle(STYLE_DOT); - - // - defaultBullishStyle.width = 1; - defaultBullishStyle.clr = clrLime; - defaultBullishStyle.style = STYLE_SOLID; - - // - defaultBearishStyle.width = 1; - defaultBearishStyle.clr = clrRed; - defaultBearishStyle.style = STYLE_SOLID; - - // - boxBullishStyle = defaultBullishStyle; - boxBearishStyle = defaultBearishStyle; - } - - // - // Drawers ... - - /** - * Dar Specified Pivot ... - * - * @param pivot: XPivot, Specified Pivot ... - * @param object: XCBarArrowObject, pointer reference for Drawn Object ... - * @param peakArrow: int, Specified Arrow Code for Peak Pivots ... - * @param valeArrow: int, Specified Arrow Code for Vale Pivots ... - * @param threshold: int, distance between price and arrow in Point ... - * - * @return ( bool ) - */ - bool DrawPivot( - XPivot &pivot, - XCBarArrowObject *&object, - int peakArrow = 159, - int valeArrow = 159, - int threshold = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - object = NULL; - - // - // Normalize ... - threshold = NormalizeInt(threshold, 5); - peakArrow = NormalizeInt(peakArrow, 159); - valeArrow = NormalizeInt(valeArrow, 159); - - // - // Validate ... - result = pivot.IsValid(); - if (!result) - { - return result; - } - - // - // Get Pivot's Bar ... - XOHCL bar; - result = pivot.GetBar(bar); - if (!result) - { - return result; - } - - // - int arrow = pivot.IsPeak() - ? peakArrow - : valeArrow; - string name = pivot.GetObjectID(); - ENUM_X_PRICE type = pivot.IsPeak() - ? X_PRICE_HIGH - : X_PRICE_LOW; - XPOIStyle style = pivot.IsPeak() - ? defaultBullishStyle - : defaultBearishStyle; - ENUM_ARROW_ANCHOR anchor = pivot.IsPeak() - ? ANCHOR_BOTTOM - : ANCHOR_TOP; - object = new XCBarArrowObject(); - result = object.CreateByBar( - ChartIdentification(), - name, - SubWindowIdentification(), - arrow, - bar, - type, - threshold // - ); - if (result) - { - // - // Apply Styles ... - object.ArrowAnchor(anchor); - ApplyBarArrowStyle( - object, - style // - ); - } - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; - } - - /** - * Draw Specified Box ... - * - * @param object: XCBoxObject, pointer reference for Drawn Object ... - * @param name: Box Name ... - * @param upper: double, Box Upper ... - * @param lower: double, Box Lower ... - * @param from: datetime, From Time ... - * @param to: datetime, To Time ... - * @param at: datetime, Specified At Time ... - * - * @return ( bool ) - */ - bool DrawBox( - XCBoxObject *&object, - string name, - double upper, - double lower, - datetime from, - datetime to, - datetime at // - ) - { - // - bool result = false; - - // - // Prepare ... - object = NULL; - - // - // Normalize ... - to = NormalizeTime(to); - from = NormalizeTime(from); - - // - // Validate ... - result = - upper > 0 && - lower > 0 && - to > from && - IsSpecifiedValid(to) && - IsSpecifiedValid(name) && - IsSpecifiedValid(from) && - upper > lower; - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCBoxObject(); - result = object.Create( - chartID, - window, - name, - upper, - lower, - from, - to, - at, - prefix // - ); - - // - return result; - } - - /** - * Draw Specific Box ... - * - * @param box: XBoxZone, Specified Box ... - * @param object: XCBarArrowObject, pointer reference for Drawn Object ... - * @param ignoreAt: bool, Ignore Box at or not ... - * - * @return ( bool ) - */ - bool DrawBox( - XBoxZone &box, - XCBoxObject *&object, - bool ignoreAt = true // - ) - { - // - bool result = false; - - // - // Prepare ... - object = NULL; - - // - // Validate ... - result = box.IsValid(); - if (!result) - { - return result; - } - - // - datetime at = box.at; - if (ignoreAt) - { - at = NULL; - } - - // - string name = box.GetTag(); - result = DrawBox( - object, - name, - box.upper, - box.lower, - box.from, - box.to, - at // - ); - if (result) - { - // - // Apply Style ... - XPOIStyle style; - GetBoxStyle( - style, - box.dir // - ); - - // - ApplyBoxStyle( - object, - style // - ); - - // - style.Clean(); - } - - // - return result; - } - - /** - * Draw Specified Signal ... - * - * @param signal: XSignal, Specified Signal ... - * @param object: XCSignalObject, pointer reference for Drawn Object ... - * @param length: int, Signal Length ... - */ - bool DrawSignal( - XSignal &signal, - XCSignalObject *&object, - int length = 3 // - ) - { - // - bool result = false; - - // - object = NULL; - length = NormalizeInt(length, 3); - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCSignalObject(); - result = object.Create( - chartID, - window, - signal, - length, - prefix // - ); - if (!result) - { - return result; - } - - // - object.TPWidth(1); - object.TPColor(clrGreen); - object.TPWidth(STYLE_DOT); - - // - object.SLWidth(1); - object.SLColor(clrRed); - object.SLWidth(STYLE_DOT); - - // - object.TargetWidth(1); - object.TargetColor(clrLightBlue); - object.TargetWidth(STYLE_DOT); - - // - object.EntryWidth(1); - object.EntryColor(clrYellow); - object.EntryWidth(STYLE_DOT); - - // - return result; - } - - /** - * Draw Specified Trend Line ... - * - * @param fromPrice: double, from Price ... - * @param fromTime: datetime, from Time ... - * @param toPrice: double, to Price ... - * @param toTime: datetime, to Time ... - * @param object: CChartObjectTrend, pointer reference for Drawn Object ... - * @param name: Object Name ... - * @param rayRight: bool, ray to Right ... - * @param rayLeft: boo, ray to Left ... - * - * @return ( bool ) - */ - bool DrawTrendLine( - double fromPrice, - datetime fromTime, - double toPrice, - datetime toTime, - CChartObjectTrend *&object, - string name, - bool rayRight = false, - bool rayLeft = false // - ) - { - // - bool result = false; - - // - // Prepare ... - object = new CChartObjectTrend(); - - // - // Validate ... - result = - toPrice > 0 && - fromPrice > 0 && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime) && - toTime > fromTime; - if (!result) - { - return result; - } - - // - // Create Object ... - result = object.Create( - ChartIdentification(), - name, - SubWindowIdentification(), - fromTime, - fromPrice, - toTime, - toPrice // - ); - if (result) - { - // - ENUM_X_DIRECTION dir = - fromPrice < toPrice - ? X_DIRECTION_BULLISH - : fromPrice > toPrice - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - ApplyTrendLineStyle( - object, - dir // - ); - - // - object.RayLeft(rayLeft); - object.RayRight(rayRight); - } - - // - return result; - } - - /** - * Draw Trend Line based on Swings Points ... - * - * @param swings: XOHCL, Specified Swings ... - * @param dir: ENUM_X_DIRECTION, Specified Trend Direction ... - * @param object: CChartObjectTrend, pointer reference for Drawn Object ... - * @param rayRight: Ray to Right ... - * @param rayLeft: Ray to Left ... - * - * @return ( bool ) - */ - bool DrawSwingTrend( - XOHCL &swings[], - ENUM_X_DIRECTION dir, - CChartObjectTrend *&object, - bool rayRight = false, - bool rayLeft = false // - ) - { - // - bool result = false; - - // - int count = ArraySize(swings); - result = HasChild(swings) && - count >= 2 && - HasDirection(dir); - if (!result) - { - return result; - } - - // - bool isBullish = IsSpecifiedBullish(dir); - - // - double price1 = - isBullish - ? swings[0].low - : swings[0].high; - datetime time1 = swings[0].time; - - // - double price2 = - isBullish - ? swings[count - 1].low - : swings[count - 1].high; - datetime time2 = swings[count - 1].time; - - // - ulong chartId = ChartIdentification(); - int subWindow = SubWindowIdentification(); - string name = ToXString(dir) + "_Trend_" + ToXString(price1) + "_" + ToXString(price2); - - // - object = new CChartObjectTrend(); - result = object.Create( - chartId, - name, - subWindow, - time1, - price1, - time2, - price2 // - ); - if (result) - { - // - ApplyTrendLineStyle( - object, - dir // - ); - - // - object.RayLeft(rayLeft); - object.RayRight(rayRight); - } - - // - return result; - } - - /** - * Draw Pivot Analysis ... - * - * @param analysis: XPivotAnalysis, referece Specified Pivot Analysis ... - * - * @return ( bool ) - */ - bool DrawXPivotAnalysis( - XPivotAnalysis &analysis, - XCPivotAnalysisObject *&object // - ) - { - // - bool result = false; - - // - // Prepare ... - object = NULL; - - // - // Normalize ... - - // - // Validate ... - result = analysis.IsValid() && - analysis.IsAnalysed(); - if (!result) - { - return result; - } - - // - object = new XCPivotAnalysisObject(); - result = object.Create( - ChartIdentification(), - SubWindowIdentification(), - analysis // - ); - if (result) - { - // - ApplyPivotAnalysisStyle( - object, - analysis // - ); - } - - // - return result; - } - - // - // Stylers ... - - /** - * Get Specified Style for Specified Direction ... - * - * @param style: XPOIStyle, reference to hold result ... - * @param forDir: ENUM_X_DIRECTION, Specified Direction ... - */ - void GetStyle( - XPOIStyle &style, - ENUM_X_DIRECTION forDir // - ) - { - // - // Prepare ... - style.Clean(); - - // - // Validate ... - if (!HasDirection(forDir)) - { - return; - } - - // - if (IsSpecifiedBullish(forDir)) - { - style = defaultBullishStyle; - } - else - { - style = defaultBearishStyle; - } - } - - /** - * Get Specified Box Style for Specified Direction ... - * - * @param style: XPOIStyle, reference to hold result ... - * @param forDir: ENUM_X_DIRECTION, Specified Direction ... - */ - void GetBoxStyle( - XPOIStyle &style, - ENUM_X_DIRECTION forDir // - ) - { - // - // Prepare ... - style.Clean(); - - // - // Validate ... - if (!HasDirection(forDir)) - { - return; - } - - // - if (IsSpecifiedBullish(forDir)) - { - style = boxBullishStyle; - } - else - { - style = boxBearishStyle; - } - } - - /** - * Apply Specified Style to Specified Object ... - * - * @param object: XCBoxObject, pointer reference of Object ... - * @param style: XPOIStyle, Specifed Style to Apply ... - */ - void ApplyBoxStyle( - XCBoxObject *&object, - XPOIStyle &style // - ) - { - // - bool has = object != NULL; - if (!has) - { - return; - } - - // - object.BoxFill(style.fill); - object.BoxColor(style.clr); - object.BoxWidth(style.width); - object.BoxStyle(style.style); - } - - /** - * Apply Specified Style to Specified Object ... - * - * @param object: XCBarArrowObject, pointer reference of Object ... - * @param style: XPOIStyle, Specifed Style to Apply ... - */ - void ApplyBarArrowStyle( - XCBarArrowObject *&object, - XPOIStyle &style // - ) - { - // - bool has = object != NULL; - if (!has) - { - return; - } - - // - object.ArrowColor(style.clr); - object.ArrowWidth(style.width); - } - - /** - * Apply Specified Style to Specified Object ... - * - * @param object: CChartObject, pointer reference of Object ... - * @param forDir: ENUM_X_DIRECTION, Specified Direction ... - */ - void ApplyTrendLineStyle( - CChartObjectTrend *&object, - ENUM_X_DIRECTION forDir // - ) - { - // - bool has = object != NULL; - if (!has) - { - return; - } - - // - if (!HasDirection(forDir)) - { - return; - } - - // - XPOIStyle style; - GetStyle(style, forDir); - - // - object.Color(style.clr); - object.Style(style.style); - object.Width(style.width); - - // - style.Clean(); - } - - /** - * Apply Specified Style to Specified Object ... - * - * @param object: CChartObject, pointer reference of Object ... - * @param model: XPivotAnalysis, referece to access requirements ... - */ - void ApplyPivotAnalysisStyle( - XCPivotAnalysisObject *&object, - XPivotAnalysis &model // - ) - { - // - // Validate ... - bool has = model.IsValid() && - model.IsAnalysed() && - object != NULL; - if (!has) - { - return; - } - - // - XPOIStyle style; - - // - // Support ... - style = defaultBullishStyle; - object.SupportColor(style.clr); - object.SupportWidth(style.width); - object.SupportStyle(style.style); - - // - // Resistance ... - style = defaultBearishStyle; - object.ResistanceColor(style.clr); - object.ResistanceWidth(style.width); - object.ResistanceStyle(style.style); - - // - // Upper ... - if (model.IsPeakAnalysed()) - { - // - GetStyle( - style, - model.peakDir // - ); - if (!HasDirection(model.peakDir)) - { - // - style.Default(); - style.clr = clrGray; - } - - // - object.UpperColor(style.clr); - object.UpperWidth(style.width); - object.UpperStyle(style.style); - object.UpperRayLeft(false); - object.UpperRayRight(true); - } - - // - // Lower ... - if (model.IsValeAnalysed()) - { - // - GetStyle( - style, - model.valeDir // - ); - if (!HasDirection(model.valeDir)) - { - // - style.Default(); - style.clr = clrGray; - } - - // - object.LowerColor(style.clr); - object.LowerWidth(style.width); - object.LowerStyle(style.style); - object.UpperRayLeft(false); - object.LowerRayRight(true); - } - - // - style.Clean(); - } - - // - protected: - // - - // - private: - // - - // - // Props ... - - // - string mPrefix; // Prefix of Created Objects ... - long mChartIdentification; // Chart Id ... - int mSubWindowIdentification; // Sub Window ... - - // - // XOHCL ... - int mBarWidth; // Bar Width ... - color mBarBullishColor; // Bar Bullish Color ... - color mBarBearishColor; // Bar Bearish Color ... - bool mBarFillHighShadow; // Fill Bar High Shadow ... - ENUM_LINE_STYLE mBarHighShadowStyle; // Bar High Shadow Style ... - bool mBarFillBody; // Fill Bar Body ... - ENUM_LINE_STYLE mBarBodyStyle; // Bar Body Style ... - bool mBarFillLowShadow; // Fill Bar Low Show ... - ENUM_LINE_STYLE mBarLowShadowStyle; // Bar Low Shadow Style ... - - // -}; \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-poi.drawer.class.mq5 b/Documents/BKP/x-saherelm.x-poi.drawer.class.mq5 deleted file mode 100644 index 51e7c7c2..00000000 --- a/Documents/BKP/x-saherelm.x-poi.drawer.class.mq5 +++ /dev/null @@ -1,4384 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XPOIDrawer -// Description: Provides Point of Interests -// Drawing Tools ... -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Classes/x-saherelm.x-cobject.class.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" - -// -// Definitions ... - -// -// Extensions ... - -void AddObjects( - CArrayObj *&source, - CArrayObj &dest // -) -{ - // - bool has = source != NULL && - source.Total() > 0; - if (!has) - { - return; - } - - // - for (int i = 0; i < source.Total(); i++) - { - dest.Add(source.At(i)); - } -} - -// -// Implementations ... -class XCPOIDrawer : public XCBase -{ - // - public: - // - - // - // Constructor ... - void XCPOIDrawer() - { - // - Default(); - } - - // - // Deconstructor ... - void ~XCPOIDrawer() - { - // - Clean(mTicksZoneSpecs); - } - - // - // Setter Getter (s) ... - - /** - * Get Prefix ... - * - * @return ( string ) - */ - string Prefix() - { - return mPrefix; - } - - /** - * Set Prifx ... - * - * @param value: String ... - */ - void Prefix(string value) - { - mPrefix = value; - } - - /** - * Get Chart ID ... - * - * @return ( long ) - */ - long ChartIdentification() - { - return mChartIdentification; - } - - /** - * Set Chart ID ... - * - * @param value: Long ... - */ - void ChartIdentification(long value) - { - // - if (value < 0) - { - value = 0; - } - - // - mChartIdentification = value; - } - - /** - * Get SubWindow Id ... - * - * @return ( int ) - */ - int SubWindowIdentification() - { - return mSubWindowIdentification; - } - - /** - * Set SubWindow Id ... - * - * @param value: Integer ... - */ - void SubWindowIdentification(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mSubWindowIdentification = value; - } - - // - // XOHCL ... - - /** - * Get Bar Width ... - * - * @return ( int ) - */ - int BarWidth() - { - return mBarWidth; - } - - /** - * Set Bar Width ... - * - * @param value: Integer ... - */ - void BarWidth(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mBarWidth = value; - } - - /** - * Get Bar Bullish Color ... - * - * @return ( color ) - */ - color BarBullishColor() - { - return mBarBullishColor; - } - - /** - * Set Bar Bullish Color ... - * - * @param value: Color ... - */ - void BarBullishColor(color value) - { - mBarBullishColor = value; - } - - /** - * Get Bar Bearish Color ... - * - * @return ( color ) - */ - color BarBearishColor() - { - return mBarBearishColor; - } - - /** - * Set Bar Bearish Color ... - * - * @param value: Color ... - */ - void BarBearishColor(color value) - { - mBarBearishColor = value; - } - - /** - * Get Fill Bar High Shadow State ... - * - * @return ( bool ) - */ - bool BarFillHighShadow() - { - return mBarFillHighShadow; - } - - /** - * Set Fill Bar High Shadow State ... - * - * @param value: Boolean ... - */ - void BarFillHighShadow(bool value) - { - mBarFillHighShadow = value; - } - - /** - * Get Bar High Shadow Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarHighShadowStyle() - { - return mBarHighShadowStyle; - } - - /** - * Set Bar High Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarHighShadowStyle(ENUM_LINE_STYLE value) - { - mBarHighShadowStyle = value; - } - - /** - * Get Fill Bar Body State ... - * - * @return ( bool ) - */ - bool BarFillBody() - { - return mBarFillBody; - } - - /** - * Set Fill Bar Body State ... - * - * @param value: Boolean ... - */ - void BarFillBody(bool value) - { - mBarFillBody = value; - } - - /** - * Get Bar Body Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarBodyStyle() - { - return mBarBodyStyle; - } - - /** - * Set Bar Body Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarBodyStyle(ENUM_LINE_STYLE value) - { - mBarBodyStyle = value; - } - - /** - * Get Fill Bar Low Show State ... - * - * @return ( bool ) - */ - bool BarFillLowShadow() - { - return mBarFillLowShadow; - } - - /** - * Set Fill Bar Low Show State ... - * - * @param value: Boolean ... - */ - void BarFillLowShadow(bool value) - { - mBarFillLowShadow = value; - } - - /** - * Get Bar Low Shadow Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BarLowShadowStyle() - { - return mBarLowShadowStyle; - } - - /** - * Set Bar Low Shadow Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BarLowShadowStyle(ENUM_LINE_STYLE value) - { - mBarLowShadowStyle = value; - } - - // - // Swing Low ... - - /** - * Get Swing Low Width ... - * - * @return ( int ) - */ - int SwingLowWidth() - { - return mSwingLowWidth; - } - - /** - * Set Swing Low Width ... - * - * @param value: Integer ... - */ - void SwingLowWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSwingLowWidth = value; - } - - /** - * Get Swing Low Arrow Code ... - * - * @return ( int ) - */ - int SwingLowArrow() - { - return mSwingLowArrow; - } - - /** - * Set Swing Low Arrow Code ... - * - * @param value: Integer ... - */ - void SwingLowArrow(int value) - { - // - mSwingLowArrow = value; - } - - /** - * Get Swing Low Color ... - * - * @return ( color ) - */ - color SwingLowColor() - { - return mSwingLowColor; - } - - /** - * Set Swing Low Color ... - * - * @param value: Color ... - */ - void SwingLowColor(color value) - { - mSwingLowColor = value; - } - - // - // Swing High ... - - /** - * Get Swing High Width ... - * - * @return ( int ) - */ - int SwingHighWidth() - { - return mSwingHighWidth; - } - - /** - * Set Swing High Width ... - * - * @param value: Integer ... - */ - void SwingHighWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSwingHighWidth = value; - } - - /** - * Get Swing High Arrow Code ... - * - * @return ( int ) - */ - int SwingHighArrow() - { - return mSwingHighArrow; - } - - /** - * Set Swing High Arrow Code ... - * - * @param value: Integer ... - */ - void SwingHighArrow(int value) - { - // - mSwingHighArrow = value; - } - - /** - * Get Swing High Color ... - * - * @return ( color ) - */ - color SwingHighColor() - { - return mSwingHighColor; - } - - /** - * Set Swing High Color ... - * - * @param value: Color ... - */ - void SwingHighColor(color value) - { - mSwingHighColor = value; - } - - // - // Bullish Momentum Bar ... - - /** - * Get Bullish Momentum Bar Width ... - * - * @return ( int ) - */ - int BullishMomentumBarWidth() - { - return mBullishMomentumBarWidth; - } - - /** - * Set Bullish Momentum Bar Width ... - * - * @param value: Integer ... - */ - void BullishMomentumBarWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBullishMomentumBarWidth = value; - } - - /** - * Get Bullish Momentum Bar Arrow Code ... - * - * @return ( int ) - */ - int BullishMomentumBarArrow() - { - return mBullishMomentumBarArrow; - } - - /** - * Set Bullish Momentum Bar Arrow Code ... - * - * @param value: Integer ... - */ - void BullishMomentumBarArrow(int value) - { - // - mBullishMomentumBarArrow = value; - } - - /** - * Get Bullish Momentum Bar Color ... - * - * @return ( color ) - */ - color BullishMomentumBarColor() - { - return mBullishMomentumBarColor; - } - - /** - * Set Bullish Momentum Bar Color ... - * - * @param value: Color ... - */ - void BullishMomentumBarColor(color value) - { - mBullishMomentumBarColor = value; - } - - // - // Bearish Momentum Bar ... - - /** - * Get Bearish Momentum Bar Width ... - * - * @return ( int ) - */ - int BearishMomentumBarWidth() - { - return mBearishMomentumBarWidth; - } - - /** - * Set Bearish Momentum Bar Width ... - * - * @param value: Integer ... - */ - void BearishMomentumBarWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBearishMomentumBarWidth = value; - } - - /** - * Get Bearish Momentum Bar Arrow Code ... - * - * @return ( int ) - */ - int BearishMomentumBarArrow() - { - return mBearishMomentumBarArrow; - } - - /** - * Set Bearish Momentum Bar Arrow Code ... - * - * @param value: Integer ... - */ - void BearishMomentumBarArrow(int value) - { - // - mBearishMomentumBarArrow = value; - } - - /** - * Get Bearish Momentum Bar Color ... - * - * @return ( color ) - */ - color BearishMomentumBarColor() - { - return mBearishMomentumBarColor; - } - - /** - * Set Bearish Momentum Bar Color ... - * - * @param value: Color ... - */ - void BearishMomentumBarColor(color value) - { - mBearishMomentumBarColor = value; - } - - // - // Bullish Rejection Bar ... - - /** - * Get Bullish Rejection Bar Width ... - * - * @return ( int ) - */ - int BullishRejectionBarWidth() - { - return mBullishRejectionBarWidth; - } - - /** - * Set Bullish Rejection Bar Width ... - * - * @param value: Integer ... - */ - void BullishRejectionBarWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBullishRejectionBarWidth = value; - } - - /** - * Get Bullish Rejection Bar Arrow Code ... - * - * @return ( int ) - */ - int BullishRejectionBarArrow() - { - return mBullishRejectionBarArrow; - } - - /** - * Set Bullish Rejection Bar Arrow Code ... - * - * @param value: Integer ... - */ - void BullishRejectionBarArrow(int value) - { - // - mBullishRejectionBarArrow = value; - } - - /** - * Get Bullish Rejection Bar Color ... - * - * @return ( color ) - */ - color BullishRejectionBarColor() - { - return mBullishRejectionBarColor; - } - - /** - * Set Bullish Rejection Bar Color ... - * - * @param value: Color ... - */ - void BullishRejectionBarColor(color value) - { - mBullishRejectionBarColor = value; - } - - // - // Bearish Rejection Bar ... - - /** - * Get Bearish Rejection Bar Width ... - * - * @return ( int ) - */ - int BearishRejectionBarWidth() - { - return mBearishRejectionBarWidth; - } - - /** - * Set Bearish Rejection Bar Width ... - * - * @param value: Integer ... - */ - void BearishRejectionBarWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBearishRejectionBarWidth = value; - } - - /** - * Get Bearish Rejection Bar Arrow Code ... - * - * @return ( int ) - */ - int BearishRejectionBarArrow() - { - return mBearishRejectionBarArrow; - } - - /** - * Set Bearish Rejection Bar Arrow Code ... - * - * @param value: Integer ... - */ - void BearishRejectionBarArrow(int value) - { - // - mBearishRejectionBarArrow = value; - } - - /** - * Get Bearish Rejection Bar Color ... - * - * @return ( color ) - */ - color BearishRejectionBarColor() - { - return mBearishRejectionBarColor; - } - - /** - * Set Bearish Rejection Bar Color ... - * - * @param value: Color ... - */ - void BearishRejectionBarColor(color value) - { - mBearishRejectionBarColor = value; - } - - // - // Supply Zone ... - - /** - * Get Fill Supply Zone ... - * - * @return ( bool ) - */ - bool SupplyZoneFill() - { - return mSupplyZoneFill; - } - - /** - * Set Fill Supply Zone ... - * - * @param value: Boolean ... - */ - void SupplyZoneFill(bool value) - { - mSupplyZoneFill = value; - } - - /** - * Get Supply Zone Width ... - * - * @return ( int ) - */ - int SupplyZoneWidth() - { - return mSupplyZoneWidth; - } - - /** - * Set Supply Zone Width ... - * - * @param value: Integer ... - */ - void SupplyZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSupplyZoneWidth = value; - } - - /** - * Get Supply Zone Color ... - * - * @return ( color ) - */ - color SupplyZoneColor() - { - return mSupplyZoneColor; - } - - /** - * Set Supply Zone Color ... - * - * @param value: Color ... - */ - void SupplyZoneColor(color value) - { - mSupplyZoneColor = value; - } - - /** - * Get Supply Zone Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE SupplyZoneStyle() - { - return mSupplyZoneStyle; - } - - /** - * Set Supply Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void SupplyZoneStyle(ENUM_LINE_STYLE value) - { - mSupplyZoneStyle = value; - } - - // - // Demand Zone ... - - /** - * Get Fill Demand Zone ... - * - * @return ( bool ) - */ - bool DemandZoneFill() - { - return mDemandZoneFill; - } - - /** - * Set Fill Demand Zone ... - * - * @param value: Boolean ... - */ - void DemandZoneFill(bool value) - { - mDemandZoneFill = value; - } - - /** - * Get Demand Zone Width ... - * - * @return ( int ) - */ - int DemandZoneWidth() - { - return mDemandZoneWidth; - } - - /** - * Set Demand Zone Width ... - * - * @param value: Integer ... - */ - void DemandZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mDemandZoneWidth = value; - } - - /** - * Get Demand Zone Color ... - * - * @return ( color ) - */ - color DemandZoneColor() - { - return mDemandZoneColor; - } - - /** - * Set Demand Zone Color ... - * - * @param value: Color ... - */ - void DemandZoneColor(color value) - { - mDemandZoneColor = value; - } - - /** - * Get Demand Zone Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE DemandZoneStyle() - { - return mDemandZoneStyle; - } - - /** - * Set Demand Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void DemandZoneStyle(ENUM_LINE_STYLE value) - { - mDemandZoneStyle = value; - } - - // - // Resistance Zone ... - - /** - * Get Fill Resistance Zone ... - * - * @return ( bool ) - */ - bool ResistanceZoneFill() - { - return mResistanceZoneFill; - } - - /** - * Set Fill Resistance Zone ... - * - * @param value: Boolean ... - */ - void ResistanceZoneFill(bool value) - { - mResistanceZoneFill = value; - } - - /** - * Get Resistance Zone Width ... - * - * @return ( int ) - */ - int ResistanceZoneWidth() - { - return mResistanceZoneWidth; - } - - /** - * Set Resistance Zone Width ... - * - * @param value: Integer ... - */ - void ResistanceZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mResistanceZoneWidth = value; - } - - /** - * Get Resistance Zone Color ... - * - * @return ( color ) - */ - color ResistanceZoneColor() - { - return mResistanceZoneColor; - } - - /** - * Set Resistance Zone Color ... - * - * @param value: Color ... - */ - void ResistanceZoneColor(color value) - { - mResistanceZoneColor = value; - } - - /** - * Get Resistance Zone Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE ResistanceZoneStyle() - { - return mResistanceZoneStyle; - } - - /** - * Set Resistance Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void ResistanceZoneStyle(ENUM_LINE_STYLE value) - { - mResistanceZoneStyle = value; - } - - // - // Support Zone ... - - /** - * Get Fill Support Zone ... - * - * @return ( bool ) - */ - bool SupportZoneFill() - { - return mSupportZoneFill; - } - - /** - * Set Fill Support Zone ... - * - * @param value: Boolean ... - */ - void SupportZoneFill(bool value) - { - mSupportZoneFill = value; - } - - /** - * Get Support Zone Width ... - * - * @return ( int ) - */ - int SupportZoneWidth() - { - return mSupportZoneWidth; - } - - /** - * Set Support Zone Width ... - * - * @param value: Integer ... - */ - void SupportZoneWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mSupportZoneWidth = value; - } - - /** - * Get Support Zone Color ... - * - * @return ( color ) - */ - color SupportZoneColor() - { - return mSupportZoneColor; - } - - /** - * Set Support Zone Color ... - * - * @param value: Color ... - */ - void SupportZoneColor(color value) - { - mSupportZoneColor = value; - } - - /** - * Get Support Zone Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE SupportZoneStyle() - { - return mSupportZoneStyle; - } - - /** - * Set Support Zone Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void SupportZoneStyle(ENUM_LINE_STYLE value) - { - mSupportZoneStyle = value; - } - - // - // Bullish Order Block ... - - /** - * Get Fill Bullish Order Block ... - * - * @return ( bool ) - */ - bool BullishOrderBlockFill() - { - return mBullishOrderBlockFill; - } - - /** - * Set Fill Bullish Order Block ... - * - * @param value: Boolean ... - */ - void BullishOrderBlockFill(bool value) - { - mBullishOrderBlockFill = value; - } - - /** - * Get Bullish Order Block Width ... - * - * @return ( int ) - */ - int BullishOrderBlockWidth() - { - return mBullishOrderBlockWidth; - } - - /** - * Set Bullish Order Block Width ... - * - * @param value: Integer ... - */ - void BullishOrderBlockWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBullishOrderBlockWidth = value; - } - - /** - * Get Bullish Order Block Color ... - * - * @return ( color ) - */ - color BullishOrderBlockColor() - { - return mBullishOrderBlockColor; - } - - /** - * Set Bullish Order Block Color ... - * - * @param value: Color ... - */ - void BullishOrderBlockColor(color value) - { - mBullishOrderBlockColor = value; - } - - /** - * Get Bullish Order Block Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BullishOrderBlockStyle() - { - return mBullishOrderBlockStyle; - } - - /** - * Set Bullish Order Block Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BullishOrderBlockStyle(ENUM_LINE_STYLE value) - { - mBullishOrderBlockStyle = value; - } - - // - // Bearish Order Block ... - - /** - * Get Fill Bearish Order Block ... - * - * @return ( bool ) - */ - bool BearishOrderBlockFill() - { - return mBearishOrderBlockFill; - } - - /** - * Set Fill Bearish Order Block ... - * - * @param value: Boolean ... - */ - void BearishOrderBlockFill(bool value) - { - mBearishOrderBlockFill = value; - } - - /** - * Get Bearish Order Block Width ... - * - * @return ( int ) - */ - int BearishOrderBlockWidth() - { - return mBearishOrderBlockWidth; - } - - /** - * Set Bearish Order Block Width ... - * - * @param value: Integer ... - */ - void BearishOrderBlockWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBearishOrderBlockWidth = value; - } - - /** - * Get Bearish Order Block Color ... - * - * @return ( color ) - */ - color BearishOrderBlockColor() - { - return mBearishOrderBlockColor; - } - - /** - * Set Bearish Order Block Color ... - * - * @param value: Color ... - */ - void BearishOrderBlockColor(color value) - { - mBearishOrderBlockColor = value; - } - - /** - * Get Bearish Order Block Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BearishOrderBlockStyle() - { - return mBearishOrderBlockStyle; - } - - /** - * Set Bearish Order Block Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BearishOrderBlockStyle(ENUM_LINE_STYLE value) - { - mBearishOrderBlockStyle = value; - } - - // - // Bullish FVG ... - - /** - * Get Fill Bullish FVG ... - * - * @return ( bool ) - */ - bool BullishFVGFill() - { - return mBullishFVGFill; - } - - /** - * Set Fill Bullish FVG ... - * - * @param value: Boolean ... - */ - void BullishFVGFill(bool value) - { - mBullishFVGFill = value; - } - - /** - * Get Bullish FVG Width ... - * - * @return ( int ) - */ - int BullishFVGWidth() - { - return mBullishFVGWidth; - } - - /** - * Set Bullish FVG Width ... - * - * @param value: Integer ... - */ - void BullishFVGWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBullishFVGWidth = value; - } - - /** - * Get Bullish FVG Color ... - * - * @return ( color ) - */ - color BullishFVGColor() - { - return mBullishFVGColor; - } - - /** - * Set Bullish FVG Color ... - * - * @param value: Color ... - */ - void BullishFVGColor(color value) - { - mBullishFVGColor = value; - } - - /** - * Get Bullish FVG Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BullishFVGStyle() - { - return mBullishFVGStyle; - } - - /** - * Set Bullish FVG Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BullishFVGStyle(ENUM_LINE_STYLE value) - { - mBullishFVGStyle = value; - } - - // - // Bearish FVG ... - - /** - * Get Fill Bearish FVG ... - * - * @return ( bool ) - */ - bool BearishFVGFill() - { - return mBearishFVGFill; - } - - /** - * Set Fill Bearish FVG ... - * - * @param value: Boolean ... - */ - void BearishFVGFill(bool value) - { - mBearishFVGFill = value; - } - - /** - * Get Bearish FVG Width ... - * - * @return ( int ) - */ - int BearishFVGWidth() - { - return mBearishFVGWidth; - } - - /** - * Set Bearish FVG Width ... - * - * @param value: Integer ... - */ - void BearishFVGWidth(int value) - { - // - if (value < 1) - { - value = 1; - } - - // - mBearishFVGWidth = value; - } - - /** - * Get Bearish FVG Color ... - * - * @return ( color ) - */ - color BearishFVGColor() - { - return mBearishFVGColor; - } - - /** - * Set Bearish FVG Color ... - * - * @param value: Color ... - */ - void BearishFVGColor(color value) - { - mBearishFVGColor = value; - } - - /** - * Get Bearish FVG Style ... - * - * @return ( ENUM_LINE_STYLE ) - */ - ENUM_LINE_STYLE BearishFVGStyle() - { - return mBearishFVGStyle; - } - - /** - * Set Bearish FVG Style ... - * - * @param value: ENUM_LINE_STYLE member ... - */ - void BearishFVGStyle(ENUM_LINE_STYLE value) - { - mBearishFVGStyle = value; - } - - // - // Virtuals ... - - /** - * Apply Default Configurations ... - */ - virtual void Default() - { - // - // Apply Default Props ... - - // - Prefix(NULL); - ChartIdentification(0); - SubWindowIdentification(0); - - // - BarWidth(1); - BarBearishColor(clrRed); - BarBullishColor(clrLime); - BarFillBody(false); - BarFillHighShadow(false); - BarFillLowShadow(false); - BarBodyStyle(STYLE_DOT); - BarLowShadowStyle(STYLE_DOT); - BarHighShadowStyle(STYLE_DOT); - - // - int arrowWidth = 1; - - // - SwingLowArrow(108); - SwingLowColor(clrAqua); - SwingLowWidth(arrowWidth); - - // - SwingHighArrow(108); - SwingHighWidth(arrowWidth); - SwingHighColor(clrMagenta); - - // - arrowWidth++; - - // - BullishMomentumBarArrow(225); - BullishMomentumBarWidth(arrowWidth); - BullishMomentumBarColor(clrAqua); - - // - BearishMomentumBarArrow(226); - BearishMomentumBarWidth(arrowWidth); - BearishMomentumBarColor(clrMagenta); - - // - arrowWidth++; - - // - BullishRejectionBarArrow(217); - BullishRejectionBarWidth(arrowWidth); - BullishRejectionBarColor(clrAqua); - - // - BearishRejectionBarArrow(218); - BearishRejectionBarWidth(arrowWidth); - BearishRejectionBarColor(clrMagenta); - - // - SupportZoneFill(false); - SupportZoneWidth(1); - SupportZoneStyle(STYLE_DOT); - SupportZoneColor(clrLime); - - // - ResistanceZoneFill(false); - ResistanceZoneWidth(1); - ResistanceZoneStyle(STYLE_DOT); - ResistanceZoneColor(clrRed); - - // - SupplyZoneFill(false); - SupplyZoneWidth(1); - SupplyZoneStyle(STYLE_DOT); - SupplyZoneColor(clrRed); - - // - DemandZoneFill(false); - DemandZoneWidth(1); - DemandZoneStyle(STYLE_DOT); - DemandZoneColor(clrGreen); - - // - BullishOrderBlockFill(false); - BullishOrderBlockWidth(1); - BullishOrderBlockStyle(STYLE_DASHDOT); - BullishOrderBlockColor(clrLime); - - // - BearishOrderBlockFill(false); - BearishOrderBlockWidth(1); - BearishOrderBlockStyle(STYLE_DASHDOT); - BearishOrderBlockColor(clrRed); - - // - BullishFVGFill(false); - BullishFVGWidth(1); - BullishFVGStyle(STYLE_DOT); - BullishFVGColor(clrLime); - - // - BearishFVGFill(false); - BearishFVGWidth(1); - BearishFVGStyle(STYLE_DOT); - BearishFVGColor(clrRed); - - // - // Add Default TickZone Specs ... - bool isSpecsInited = false; - bool fillTickZone = false; - XTickZoneLevelSpecs specs10; - isSpecsInited = specs10.Init( - 10, - clrWhite, - clrWhite, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs10); - } - - // - XTickZoneLevelSpecs specs20; - isSpecsInited = specs20.Init( - 20, - clrOrange, - clrOrange, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs20); - } - - // - XTickZoneLevelSpecs specs30; - isSpecsInited = specs30.Init( - 30, - clrOrange, - clrOrange, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs30); - } - - // - XTickZoneLevelSpecs specs40; - isSpecsInited = specs40.Init( - 40, - clrOrange, - clrOrange, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs40); - } - - // - XTickZoneLevelSpecs specs50; - isSpecsInited = specs50.Init( - 50, - clrYellow, - clrYellow, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs50); - } - - // - XTickZoneLevelSpecs specs60; - isSpecsInited = specs60.Init( - 60, - clrYellow, - clrYellow, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs60); - } - - // - XTickZoneLevelSpecs specs70; - isSpecsInited = specs70.Init( - 70, - clrYellow, - clrYellow, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs70); - } - - // - XTickZoneLevelSpecs specs80; - isSpecsInited = specs80.Init( - 80, - clrRed, - clrRed, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs80); - } - - // - XTickZoneLevelSpecs specs90; - isSpecsInited = specs90.Init( - 90, - clrRed, - clrRed, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs90); - } - - // - XTickZoneLevelSpecs specs100; - isSpecsInited = specs100.Init( - 100, - clrRed, - clrRed, - fillTickZone // - ); - if (isSpecsInited) - { - AddTickZoneLevelSpecs(specs100); - } - - // - } - - // - // Object Creators ... - - // - // Swings ... - - /** - * Create Swing High Object ... - * - * @param swing: XCSwing instance ... - * @param object: XCSwingHighObject pointer ... - * - * @return ( bool ) - */ - bool CreateSwingHigh( - XCSwing &swing, - XCSwingHighObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - swing.IsValid() && - swing.IsSwingHigh(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = SwingHighArrow(); - int width = SwingHighWidth(); - color crl = SwingHighColor(); - - // - object = new XCSwingHighObject(); - result = object.Create( - chartID, - window, - arrow, - swing, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_BOTTOM); - - // - return result; - } - - /** - * Create Swing Low Object ... - * - * @param swing: XCSwing instance ... - * @param object: XCSwingLowObject pointer ... - * - * @return ( bool ) - */ - bool CreateSwingLow( - XCSwing &swing, - XCSwingLowObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - swing.IsValid() && - swing.IsSwingLow(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = SwingLowArrow(); - int width = SwingLowWidth(); - color crl = SwingLowColor(); - - // - object = new XCSwingLowObject(); - result = object.Create( - chartID, - window, - arrow, - swing, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_TOP); - - // - return result; - } - - // - // Momentum Bars ... - - /** - * Create Bullish Momentum Bar Object ... - * - * @param momentumBar: XCMomentumBar instance ... - * @param object: XCBullishMomentumObject pointer ... - * - * @return ( bool ) - */ - bool CreateBullishMomentumBar( - XCMomentumBar &momentumBar, - XCBullishMomentumBarObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - momentumBar.IsValid() && - momentumBar.IsBullish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = BullishMomentumBarArrow(); - int width = BullishMomentumBarWidth(); - color crl = BullishMomentumBarColor(); - - // - object = new XCBullishMomentumBarObject(); - result = object.Create( - chartID, - window, - arrow, - momentumBar, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_TOP); - - // - return result; - } - - /** - * Create Bearish Momentum Bar Object ... - * - * @param momentumBar: XCMomentumBar instance ... - * @param object: XCBearishMomentumObject pointer ... - * - * @return ( bool ) - */ - bool CreateBearishMomentumBar( - XCMomentumBar &momentumBar, - XCBearishMomentumBarObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - momentumBar.IsValid() && - momentumBar.IsBearish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = BearishMomentumBarArrow(); - int width = BearishMomentumBarWidth(); - color crl = BearishMomentumBarColor(); - - // - object = new XCBearishMomentumBarObject(); - result = object.Create( - chartID, - window, - arrow, - momentumBar, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_BOTTOM); - - // - return result; - } - - // - // Rejection Bars ... - - /** - * Create Bullish Rejection Bar Object ... - * - * @param momentumBar: XCRejectionBar instance ... - * @param object: XCBullishRejectionObject pointer ... - * - * @return ( bool ) - */ - bool CreateBullishRejectionBar( - XCRejectionBar &rejectionBar, - XCBullishRejectionBarObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - rejectionBar.IsValid() && - rejectionBar.IsBullish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = BullishRejectionBarArrow(); - int width = BullishRejectionBarWidth(); - color crl = BullishRejectionBarColor(); - - // - object = new XCBullishRejectionBarObject(); - result = object.Create( - chartID, - window, - arrow, - rejectionBar, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_TOP); - - // - return result; - } - - /** - * Create Bearish Rejection Bar Object ... - * - * @param rejectionBar: XCRejectionBar instance ... - * @param object: XCBearishRejectionObject pointer ... - * - * @return ( bool ) - */ - bool CreateBearishRejectionBar( - XCRejectionBar &rejectionBar, - XCBearishRejectionBarObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - rejectionBar.IsValid() && - rejectionBar.IsBearish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int arrow = BearishRejectionBarArrow(); - int width = BearishRejectionBarWidth(); - color crl = BearishRejectionBarColor(); - - // - object = new XCBearishRejectionBarObject(); - result = object.Create( - chartID, - window, - arrow, - rejectionBar, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ArrowColor(crl); - object.ArrowWidth(width); - object.ArrowAnchor(ANCHOR_BOTTOM); - - // - return result; - } - - // - // Support and Resistance ... - - /** - * Create Support Object ... - * - * @param zone: XCSupportZone instance ... - * @param object: XCSupportZoneObject pointer ... - * - * @return ( bool ) - */ - bool CreateSupportZone( - XCSupportZone &zone, - XCSupportZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = SupportZoneFill(); - int width = SupportZoneWidth(); - color crl = SupportZoneColor(); - ENUM_LINE_STYLE style = SupportZoneStyle(); - - // - object = new XCSupportZoneObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - /** - * Create Resistance Object ... - * - * @param zone: XCResistanceZone instance ... - * @param object: XCResistanceZoneObject pointer ... - * - * @return ( bool ) - */ - bool CreateResistanceZone( - XCResistanceZone &zone, - XCResistanceZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = ResistanceZoneFill(); - int width = ResistanceZoneWidth(); - color crl = ResistanceZoneColor(); - ENUM_LINE_STYLE style = ResistanceZoneStyle(); - - // - object = new XCResistanceZoneObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - // - // Supply and Demand Zones ... - - /** - * Create Supply Object ... - * - * @param zone: XCSupplyZone instance ... - * @param object: XCSupplyZoneObject pointer ... - * - * @return ( bool ) - */ - bool CreateSupplyZone( - XCSupplyZone &zone, - XCSupplyZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = SupplyZoneFill(); - int width = SupplyZoneWidth(); - color crl = SupplyZoneColor(); - ENUM_LINE_STYLE style = SupplyZoneStyle(); - - // - object = new XCSupplyZoneObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - /** - * Create Demand Object ... - * - * @param zone: XCDemandZone instance ... - * @param object: XCDemandZoneObject pointer ... - * - * @return ( bool ) - */ - bool CreateDemandZone( - XCDemandZone &zone, - XCDemandZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = DemandZoneFill(); - int width = DemandZoneWidth(); - color crl = DemandZoneColor(); - ENUM_LINE_STYLE style = DemandZoneStyle(); - - // - object = new XCDemandZoneObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - // - // Order Blocks ... - - /** - * Create Bullish Order Block Object ... - * - * @param zone: XCOrderBlock instance ... - * @param object: XCBullishOrderBlockObject pointer ... - * - * @return ( bool ) - */ - bool CreateBullishOrderBlock( - XCOrderBlock &zone, - XCBullishOrderBlockObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid() && - zone.IsBullish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = BullishOrderBlockFill(); - int width = BullishOrderBlockWidth(); - color crl = BullishOrderBlockColor(); - ENUM_LINE_STYLE style = BullishOrderBlockStyle(); - - // - object = new XCBullishOrderBlockObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - /** - * Create Bearish Order Block Object ... - * - * @param zone: XCOrderBlock instance ... - * @param object: XCBearishOrderBlockObject pointer ... - * - * @return ( bool ) - */ - bool CreateBearishOrderBlock( - XCOrderBlock &zone, - XCBearishOrderBlockObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = - zone.IsValid() && - zone.IsBearish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = BearishOrderBlockFill(); - int width = BearishOrderBlockWidth(); - color crl = BearishOrderBlockColor(); - ENUM_LINE_STYLE style = BearishOrderBlockStyle(); - - // - object = new XCBearishOrderBlockObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - bool CreateOrderBlock( - XCOrderBlock &zone, - XCBaseObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = zone.IsBullish(); - if (isBullish) - { - // - XCBullishOrderBlockObject *iObj; - result = CreateBullishOrderBlock( - zone, - iObj // - ); - if (result) - { - object = (XCBaseObject *)iObj; - } - } - else - { - // - XCBearishOrderBlockObject *iObj; - result = CreateBearishOrderBlock( - zone, - iObj // - ); - if (result) - { - object = (XCBaseObject *)iObj; - } - } - - // - return result; - } - - // - // Fair Value Gaps ... - - /** - * Create Bullish Fair Value Gap Object ... - * - * @param zone: XCFVG instance ... - * @param object: XCBullishOrderBlockObject pointer ... - * - * @return ( bool ) - */ - bool CreateBullishFairValueGap( - XCFVG &zone, - XCBullishFairValueGapObject *&object // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBullish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = BullishFVGFill(); - int width = BullishFVGWidth(); - color crl = BullishFVGColor(); - ENUM_LINE_STYLE style = BullishFVGStyle(); - - // - object = new XCBullishFairValueGapObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - /** - * Create Bearish Fair Value Gap Object ... - * - * @param zone: XCFVG instance ... - * @param object: XCBearishOrderBlockObject pointer ... - * - * @return ( bool ) - */ - bool CreateBearishFairValueGap( - XCFVG &zone, - XCBearishFairValueGapObject *&object // - ) - { - // - bool result = false; - - // - result = zone.IsValid() && - zone.IsBearish(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - bool fill = BearishFVGFill(); - int width = BearishFVGWidth(); - color crl = BearishFVGColor(); - ENUM_LINE_STYLE style = BearishFVGStyle(); - - // - object = new XCBearishFairValueGapObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.ZoneFill(fill); - object.ZoneColor(crl); - object.ZoneWidth(width); - object.ZoneStyle(style); - - // - return result; - } - - bool CreateFairValueGap( - XCFVG &zone, - XCBaseObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = zone.IsBullish(); - if (isBullish) - { - // - XCBullishFairValueGapObject *iObj; - result = CreateBullishFairValueGap( - zone, - iObj // - ); - if (result) - { - object = (XCBaseObject *)iObj; - } - } - else - { - // - XCBearishFairValueGapObject *iObj; - result = CreateBearishFairValueGap( - zone, - iObj // - ); - if (result) - { - object = (XCBaseObject *)iObj; - } - } - - // - return result; - } - - // - // Ticks Zone ... - - /** - * Add Tick Zone Draw Specifications ... - * - * @param specs: XTickZoneLevelSpecs instance ... - */ - void AddTickZoneLevelSpecs( - XTickZoneLevelSpecs &specs // - ) - { - // - if (!specs.IsValid()) - { - return; - } - - // - bool isExists = false; - int count = ArraySize(mTicksZoneSpecs); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XTickZoneLevelSpecs iSpec = mTicksZoneSpecs[i]; - - // - isExists = specs.percent == iSpec.percent; - if (isExists) - { - break; - } - } - } - if (isExists) - { - return; - } - - // - AddRef( - specs, - mTicksZoneSpecs // - ); - } - - /** - * Draw Specified Ticker Zone ... - * - * @param zone: XCTicksZone instance Specified Ticker Zone ... - * @param object: XCTicksZoneObject pointer ... - * - * @return ( bool ) - */ - bool CreateTicksZone( - XCTicksZone &zone, - XCTicksZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCTicksZoneObject(); - result = object.Create( - chartID, - window, - zone, - mTicksZoneSpecs, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Create Consolidation Zone Object ... - * - * @param zone: XConsolidationZone instance Reference ... - * - * @return ( bool ) - */ - bool CreateConsolidationZone( - XConsolidationZone &zone, - XCConsolidationZoneObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - color czColor = IsBullish(zone.dir) - ? BarBullishColor() - : BarBearishColor(); - - // - object = new XCConsolidationZoneObject(); - result = object.Create( - chartID, - window, - zone, - prefix // - ); - - // - if (result) - { - object.ZoneColor(czColor); - } - - // - return result; - } - - /** - * Create Bar Object ... - * - * @param bar: XOHCL instance Reference ... - * @param object: XCOHCLObject pointer Reference .. - * @param to: Datetime ... - * - * @return ( bool ) - */ - bool CreateBar( - XOHCL &bar, - XCOHCLObject *&object, - datetime to = NULL // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - to = NormalizeTime(to); - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - int width = BarWidth(); - - // - color mBullishColor = BarBullishColor(); - color mBearishColor = BarBearishColor(); - - // - bool fillBody = BarFillBody(); - bool fillHighShadow = BarFillHighShadow(); - bool fillLowShadow = BarFillLowShadow(); - - // - ENUM_LINE_STYLE bodyStyle = BarBodyStyle(); - ENUM_LINE_STYLE highShadowStyle = BarHighShadowStyle(); - ENUM_LINE_STYLE lowShadowStyle = BarLowShadowStyle(); - - // - object = new XCOHCLObject(); - result = object.Create( - chartID, - window, - bar, - to, - prefix // - ); - if (result) - { - // - // Apply Styling ... - - // - object.BodyWidth(width); - object.LowShadowWidth(width); - object.HighShadowWidth(width); - - // - object.BodyStyle(bodyStyle); - object.LowShadowStyle(lowShadowStyle); - object.HighShadowStyle(highShadowStyle); - - // - bool isBullish = bar.IsBullish(); - if (isBullish) - { - // - object.BodyColor(mBullishColor); - object.LowShadowColor(mBullishColor); - object.HighShadowColor(mBullishColor); - } - else - { - // - object.BodyColor(mBearishColor); - object.LowShadowColor(mBearishColor); - object.HighShadowColor(mBearishColor); - } - - // - object.BodyFill(fillBody); - object.HighShadowFill(fillHighShadow); - object.LowShadowFill(fillLowShadow); - } - - // - return result; - } - - /** - * Create Bar Arrow Object ... - * - * @param bar: XOHCL instance Reference ... - * @param priceType: ENUM_X_PRICE member ... - * @param arrow: int, Arrow Code ... - * @param clr: color, Arro Color ... - * @param width: int, Arrow Width ... - * @param anchor: ENUM_ARROW_ANCHOR, anchor of Arrow ... - * @param name: string, name of Arrow ... - * - * @return ( bool ) - */ - bool CreateBarArrow( - XOHCL &bar, - XCBarArrowObject *&object, - ENUM_X_PRICE priceType, - int arrow = 159, - color clr = clrYellow, - int width = 3, - ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, - string name = NULL // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - string barTag = bar.GetTag(name); - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - color mBullishColor = BarBullishColor(); - color mBearishColor = BarBearishColor(); - - // - prefix = - (IsValid(prefix) - ? prefix + "_" - : prefix) + - barTag; - - // - object = new XCBarArrowObject(); - result = object - .CreateByBar( - chartID, - prefix, - window, - arrow, - bar, - priceType // - ); - if (result) - { - // - object.ArrowColor(clr); - object.ArrowWidth(width); - } - - // - return result; - } - - /** - * Create Specific Box on Chart ... - * - * @param upper: Double ... - * @param lower: Double ... - * @param from: Datetime ... - * @param to: Datetime ... - * @param clr: Color ... - * @param width: Integer ... - * @param fill: Boolean ... - * @param style: ENUM_LINE_STYLE member ... - * - * @return ( bool ) - */ - bool CreateBox( - XCBoxObject *&object, - string name, - double upper, - double lower, - datetime from, - datetime to, - color clr = clrYellowGreen, - int width = 1, - bool fill = false, - ENUM_LINE_STYLE style = STYLE_SOLID // - ) - { - // - bool result = false; - - // - object = NULL; - - // - to = NormalizeTime(to); - - // - string dateStr = ToFormatString(from) + "|" + ToFormatString(to); - string dateMD5 = ToMD5(dateStr); - if (!IsValid(name)) - { - // - name = "XBox_" + - ToString(upper) + "_" + - ToString(lower) + "_" + - dateMD5; - } - - // - result = - upper > 0 && - lower > 0 && - to > from && - IsValid(to) && - IsValid(name) && - IsValid(from) && - upper > lower; - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCBoxObject(); - result = object.Create( - chartID, - window, - name, - upper, - lower, - from, - to, - prefix // - ); - - // - if (!result) - { - return result; - } - - // - object.BoxColor(clr); - object.BoxFill(fill); - object.BoxWidth(width); - object.BoxStyle(style); - - // - return result; - } - - /** - * Create Specific Box on Chart ... - * - * @param box: XBoxZone instance Reference ... - * @param clr: Color ... - * @param width: Integer ... - * @param fill: Boolean ... - * @param style: ENUM_LINE_STYLE member ... - * - * @return ( bool ) - */ - bool DrawBox( - XBoxZone &box, - XCBoxObject *&object // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - int width = 1; - bool fill = false; - color clr = - box.IsBullish() - ? BullishFVGColor() - : BearishFVGColor(); - ENUM_LINE_STYLE style = STYLE_DASHDOTDOT; - string name = box.GetTag(); - - // - result = CreateBox( - object, - name, - box.upper, - box.lower, - box.from, - box.to, - clr, - width, - fill, - style // - ); - - // - return result; - } - - /** - * Create Specific Box on Chart ... - * - * @param box: XBoxZone instance Reference ... - * @param clr: Color ... - * @param width: Integer ... - * @param fill: Boolean ... - * @param style: ENUM_LINE_STYLE member ... - * - * @return ( bool ) - */ - bool CreateBox( - XBoxZone &box, - XCBoxObject *&object, - color clr = clrYellowGreen, - int width = 1, - bool fill = false, - ENUM_LINE_STYLE style = STYLE_SOLID // - ) - { - // - bool result = false; - - // - object = NULL; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - string name = box.GetTag(); - - // - result = CreateBox( - object, - name, - box.upper, - box.lower, - box.from, - box.to, - clr, - width, - fill, - style // - ); - - // - return result; - } - - /** - * Draw Specified Signal ... - * - * @param signal: XSignal instance ... - */ - bool DrawSignal( - XSignal &signal, - XCSignalObject *&object, - int length = 3 // - ) - { - // - bool result = false; - - // - object = NULL; - length = NormalizeInt(length, 3); - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - string prefix = Prefix(); - long chartID = ChartIdentification(); - int window = SubWindowIdentification(); - - // - object = new XCSignalObject(); - result = object.Create( - chartID, - window, - signal, - length, - prefix // - ); - if (!result) - { - return result; - } - - // - object.TPWidth(1); - object.TPColor(clrGreen); - object.TPWidth(STYLE_DOT); - - // - object.SLWidth(1); - object.SLColor(clrRed); - object.SLWidth(STYLE_DOT); - - // - object.TargetWidth(1); - object.TargetColor(clrLightBlue); - object.TargetWidth(STYLE_DOT); - - // - object.EntryWidth(1); - object.EntryColor(clrYellow); - object.EntryWidth(STYLE_DOT); - - // - return result; - } - - /** - * Draw Signal Box ... - * - * @param box: XSignalBox instance Reference ... - * @param objects: XCBaseObject pointer instance Reference ... - * - * @return ( bool ) - */ - bool DrawSignalBox( - XSignalBox &box, - XCBaseObject *&objects[], - color clr = CLR_NONE // - ) - { - // - bool result = false; - - // - Clean(objects); - - // - bool has = false; - bool hasColor = clr != CLR_NONE; - - // - // Order Block ... - if (box.ob.IsValid()) - { - // - XCBoxObject *iObj; - has = DrawBox( - box.ob, - iObj // - ); - if (has) - { - // - iObj.BoxStyle(STYLE_DASH); - - // - if (hasColor) - { - iObj.BoxColor(clr); - } - - // - Add( - (XCBaseObject *)iObj, - objects // - ); - } - } - - // - // Fair Value Gap ... - if (box.fvg.IsValid()) - { - // - XCBoxObject *iObj; - has = DrawBox( - box.fvg, - iObj // - ); - if (has) - { - // - iObj.BoxStyle(STYLE_SOLID); - - // - if (hasColor) - { - iObj.BoxColor(clr); - } - - // - Add( - (XCBaseObject *)iObj, - objects // - ); - } - } - - // - // Sharp Zone ... - if (box.sharp.IsValid()) - { - // - XCBoxObject *iObj; - has = DrawBox( - box.sharp, - iObj // - ); - if (has) - { - // - iObj.BoxStyle(STYLE_DOT); - - // - if (hasColor) - { - iObj.BoxColor(clr); - } - - // - Add( - (XCBaseObject *)iObj, - objects // - ); - } - } - - // - result = HasChild(objects); - - // - return result; - } - - /** - * Draw Specified POI State ... - * - * @param state: XPOIState instance Reference ... - * @param drawnObjects: CArrayObj instance for Holding Drawn Objects ... - * @param drawTicksZone: Boolean ... - * @param ignoreSwingHighs: Boolean ... - * @param ignoreSwingLows: Boolean ... - * @param ignoreSupportZones: Boolean ... - * @param ignoreResistanceZones: Boolean ... - * @param ignoreSupplyZones: Boolean ... - * @param ignoreDemandZones: Boolean ... - * @param ignoreBullishOrderBlocks: Boolean ... - * @param ignoreBearishOrderBlocks: Boolean ... - * @param ignoreBullishFairValueGaps: Boolean ... - * @param ignoreBearishFairValueGaps: Boolean ... - * @param ignoreBullishRejectionBars: Boolean ... - * @param ignoreBearishRejectionBars: Boolean ... - * @param ignoreBullishMomentumBars: Boolean ... - * @param ignoreBearishMomentumBars: Boolean ... - */ - int DrawState( - XPOIState &state, - XCBaseObject *&drawnObjects[], - // - // Bullish ... - bool ignoreSwingLows = false, - bool ignoreDemandZones = false, - bool ignoreSupportZones = false, - bool ignoreBullishSharps = false, - bool ignoreBullishSpikes = false, - bool ignoreBullishPullbacks = false, - bool ignoreBullishMomentums = false, - bool ignoreBullishRejections = false, - bool ignoreBullishOrderBlocks = false, - bool ignoreBullishFairValueGaps = false, - bool ignoreBullishConsolidationZones = false, - // - // Bearish ... - bool ignoreSwingHighs = false, - bool ignoreSupplyZones = false, - bool ignoreResistanceZones = false, - bool ignoreBearishSharps = false, - bool ignoreBearishSpikes = false, - bool ignoreBearishPullbacks = false, - bool ignoreBearishMomentums = false, - bool ignoreBearishRejections = false, - bool ignoreBearishOrderBlocks = false, - bool ignoreBearishFairValueGaps = false, - bool ignoreBearishConsolidationZones = false // - ) - { - // - int result = 0; - - // - if (!state.IsValid() || - !state.HasChild()) - { - return result; - } - - // - Clean(drawnObjects); - - // - // Swings ... - - // - // SwingHighs ... - if (!ignoreSwingHighs) - { - // - int count = state.CountSwingHighs(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCSwing *iSwing = state.swingHighs[i]; - XCSwingHighObject *iObj; - - // - bool isCreated = CreateSwingHigh( - iSwing, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // SwingLows ... - if (!ignoreSwingLows) - { - // - int count = state.CountSwingLows(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCSwing *iSwing = state.swingLows[i]; - XCSwingLowObject *iObj; - - // - bool isCreated = CreateSwingLow( - iSwing, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Support / Resistance ... - - // - // SupportZones ... - if (!ignoreSupportZones) - { - // - int count = state.CountSupportZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCSupportZone *iZone = state.supportZones[i]; - XCSupportZoneObject *iObj; - - // - bool isCreated = CreateSupportZone( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // ResistanceZones ... - if (!ignoreResistanceZones) - { - // - int count = state.CountResistanceZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCResistanceZone *iZone = state.resistanceZones[i]; - XCResistanceZoneObject *iObj; - - // - bool isCreated = CreateResistanceZone( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Supply / Demand ... - - // - // SupplyZones ... - if (!ignoreSupplyZones) - { - // - int count = state.CountSupplyZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCSupplyZone *iZone = state.supplyZones[i]; - XCSupplyZoneObject *iObj; - - // - bool isCreated = CreateSupplyZone( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // DemandZones ... - if (!ignoreDemandZones) - { - // - int count = state.CountDemandZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCDemandZone *iZone = state.demandZones[i]; - XCDemandZoneObject *iObj; - - // - bool isCreated = CreateDemandZone( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Order Blocks ... - - // - // BullishOrderBlocks ... - if (!ignoreBullishOrderBlocks) - { - // - int count = state.CountBullishOrderBlocks(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCOrderBlock *iZone = state.bullishOrderBlocks[i]; - XCBullishOrderBlockObject *iObj; - - // - bool isCreated = CreateBullishOrderBlock( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // BearishOrderBlocks ... - if (!ignoreBearishOrderBlocks) - { - // - int count = state.CountBearishOrderBlocks(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCOrderBlock *iZone = state.bearishOrderBlocks[i]; - XCBearishOrderBlockObject *iObj; - - // - bool isCreated = CreateBearishOrderBlock( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Fair Value Gaps ... - - // - // BullishFairValueGaps ... - if (!ignoreBullishFairValueGaps) - { - // - int count = state.CountBullishFairValueGaps(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCFVG *iZone = state.bullishFairValueGaps[i]; - XCBullishFairValueGapObject *iObj; - - // - bool isCreated = CreateBullishFairValueGap( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // BearishFairValueGaps ... - if (!ignoreBearishFairValueGaps) - { - // - int count = state.CountBearishFairValueGaps(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCFVG *iZone = state.bearishFairValueGaps[i]; - XCBearishFairValueGapObject *iObj; - - // - bool isCreated = CreateBearishFairValueGap( - iZone, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Rejections ... - - // - // BullishRejectionBars ... - if (!ignoreBullishRejections) - { - // - int count = state.CountBullishRejections(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCRejectionBar *iBar = state.bullishRejections[i]; - XCBullishRejectionBarObject *iObj; - - // - bool isCreated = CreateBullishRejectionBar( - iBar, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // BearishRejectionBars ... - if (!ignoreBearishRejections) - { - // - int count = state.CountBearishRejections(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCRejectionBar *iBar = state.bearishRejections[i]; - XCBearishRejectionBarObject *iObj; - - // - bool isCreated = CreateBearishRejectionBar( - iBar, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Momentums ... - - // - // BullishMomentumBars ... - if (!ignoreBullishMomentums) - { - // - int count = state.CountBullishMomentums(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCMomentumBar *iBar = state.bullishMomentums[i]; - XCBullishMomentumBarObject *iObj; - - // - bool isCreated = CreateBullishMomentumBar( - iBar, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // BearishMomentumBars ... - if (!ignoreBearishMomentums) - { - // - int count = state.CountBearishMomentums(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCMomentumBar *iBar = state.bearishMomentums[i]; - XCBearishMomentumBarObject *iObj; - - // - bool isCreated = CreateBearishMomentumBar( - iBar, - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Pullbacks ... - - // - // Bullish ... - if (!ignoreBullishPullbacks) - { - // - int count = state.CountBullishPullbacks(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bullishPullbacks[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Bearish ... - if (!ignoreBearishPullbacks) - { - // - int count = state.CountBearishPullbacks(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bearishPullbacks[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Consolidation Zones ... - - // - // Bullish Consolidation Zones ... - if (!ignoreBullishConsolidationZones) - { - // - int count = state.CountBullishConsolidationZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCConsolidationZoneObject *iObj; - bool isCreated = CreateConsolidationZone( - state.bullishConsolidationZones[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Bearish Consolidation Zones ... - if (!ignoreBearishConsolidationZones) - { - // - int count = state.CountBearishConsolidationZones(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCConsolidationZoneObject *iObj; - bool isCreated = CreateConsolidationZone( - state.bearishConsolidationZones[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Spikes ... - - // - // Bullish ... - if (!ignoreBullishSpikes) - { - // - int count = state.CountBullishSpikes(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bullishSpikes[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Bearish ... - if (!ignoreBearishSpikes) - { - // - int count = state.CountBearishSpikes(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bearishSpikes[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Sharps ... - - // - // Bullish ... - if (!ignoreBullishSharps) - { - // - int count = state.CountBullishSharps(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bullishSharps[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - // Bearish ... - if (!ignoreBearishSharps) - { - // - int count = state.CountBearishSharps(); - if (IsValidSize(count)) - { - // - for (int i = 0; i < count; i++) - { - // - XCBoxObject *iObj; - bool isCreated = DrawBox( - state.bearishSharps[i], - iObj // - ); - if (isCreated) - { - // - Add( - (XCBaseObject *)iObj, - drawnObjects // - ); - } - } - } - } - - // - result = ArraySize(drawnObjects); - - // - return result; - } - - // - protected: - // - - // - private: - // - - // - // Props ... - - // - string mPrefix; // Prefix of Created Objects ... - long mChartIdentification; // Chart Id ... - int mSubWindowIdentification; // Sub Window ... - - // - // XOHCL ... - int mBarWidth; // Bar Width ... - color mBarBullishColor; // Bar Bullish Color ... - color mBarBearishColor; // Bar Bearish Color ... - bool mBarFillHighShadow; // Fill Bar High Shadow ... - ENUM_LINE_STYLE mBarHighShadowStyle; // Bar High Shadow Style ... - bool mBarFillBody; // Fill Bar Body ... - ENUM_LINE_STYLE mBarBodyStyle; // Bar Body Style ... - bool mBarFillLowShadow; // Fill Bar Low Show ... - ENUM_LINE_STYLE mBarLowShadowStyle; // Bar Low Shadow Style ... - - // - // Swing Low ... - int mSwingLowWidth; // Swing Low Width ... - int mSwingLowArrow; // Swing Low Arrow Code ... - color mSwingLowColor; // Swing Low Color ... - - // - // Swing High ... - int mSwingHighWidth; // Swing High Width ... - int mSwingHighArrow; // Swing High Arrow Code ... - color mSwingHighColor; // Swing High Color ... - - // - // Bullish Momentum Bar ... - int mBullishMomentumBarWidth; // Bullish Momentum Bar Width ... - int mBullishMomentumBarArrow; // Bullish Momentum Bar Arrow Code ... - color mBullishMomentumBarColor; // Bullish Momentum Bar Color ... - - // - // Bearish Momentum Bar ... - int mBearishMomentumBarWidth; // Bearish Momentum Bar Width ... - int mBearishMomentumBarArrow; // Bearish Momentum Bar Arrow Code ... - color mBearishMomentumBarColor; // Bearish Momentum Bar Color ... - - // - // Bullish Rejection Bar ... - int mBullishRejectionBarWidth; // Bullish Rejection Bar High Width ... - int mBullishRejectionBarArrow; // Bullish Rejection Bar High Arrow Code ... - color mBullishRejectionBarColor; // Bullish Rejection Bar High Color ... - - // - // Bearish Rejection Bar ... - int mBearishRejectionBarWidth; // Bearish Rejection Bar Width ... - int mBearishRejectionBarArrow; // Bearish Rejection Bar Arrow Code ... - color mBearishRejectionBarColor; // Bearish Rejection Bar Color ... - - // - // Supply Zone ... - bool mSupplyZoneFill; // Fill Supply Zone ... - int mSupplyZoneWidth; // Supply Zone Width ... - color mSupplyZoneColor; // Supply Zone Color ... - ENUM_LINE_STYLE mSupplyZoneStyle; // Supply Zone Style ... - - // - // Demand Zone ... - bool mDemandZoneFill; // Fill Demand Zone ... - int mDemandZoneWidth; // Demand Zone Width ... - color mDemandZoneColor; // Demand Zone Color ... - ENUM_LINE_STYLE mDemandZoneStyle; // Demand Zone Style ... - - // - // Resistance Zone ... - bool mResistanceZoneFill; // Fill Resistance Zone ... - int mResistanceZoneWidth; // Resistance Zone Width ... - color mResistanceZoneColor; // Resistance Zone Color ... - ENUM_LINE_STYLE mResistanceZoneStyle; // Resistance Zone Style ... - - // - // Support Zone ... - bool mSupportZoneFill; // Fill Support Zone ... - int mSupportZoneWidth; // Support Zone Width ... - color mSupportZoneColor; // Support Zone Color ... - ENUM_LINE_STYLE mSupportZoneStyle; // Support Zone Style ... - - // - // Bullish Order Block ... - bool mBullishOrderBlockFill; // Fill Bullish Order Block ... - int mBullishOrderBlockWidth; // Bullish Order Block Width ... - color mBullishOrderBlockColor; // Bullish Order Block Color ... - ENUM_LINE_STYLE mBullishOrderBlockStyle; // Bullish Order Block Style ... - - // - // Bearish Order Block ... - bool mBearishOrderBlockFill; // Fill Bearish Order Block ... - int mBearishOrderBlockWidth; // Bearish Order Block Width ... - color mBearishOrderBlockColor; // Bearish Order Block Color ... - ENUM_LINE_STYLE mBearishOrderBlockStyle; // Bearish Order Block Style ... - - // - // Bullish FVG ... - bool mBullishFVGFill; // Fill Bullish FVG ... - int mBullishFVGWidth; // Bullish FVG Width ... - color mBullishFVGColor; // Bullish FVG Color ... - ENUM_LINE_STYLE mBullishFVGStyle; // Bullish FVG Style ... - - // - // Bearish FVG ... - bool mBearishFVGFill; // Fill Bearish FVG ... - int mBearishFVGWidth; // Bearish FVG Width ... - color mBearishFVGColor; // Bearish FVG Color ... - ENUM_LINE_STYLE mBearishFVGStyle; // Bearish FVG Style ... - - // - // Ticks Zone ... - XTickZoneLevelSpecs mTicksZoneSpecs[]; // Zone Draw Specifications ... - - // -}; \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-poi.extensions.lib.mq5 b/Documents/BKP/x-saherelm.x-poi.extensions.lib.mq5 deleted file mode 100644 index abde4f03..00000000 --- a/Documents/BKP/x-saherelm.x-poi.extensions.lib.mq5 +++ /dev/null @@ -1,3807 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Seriallize Library -// --------------------------------------- -// Name: XPOILib -// Description: All models related to POIs ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright `023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Extensions ... - -template -bool ToZone( - T *&source[], - XCZone *&dest[] // -) -{ - // - bool result = false; - - // - Clean(dest); - - // - int count = ArraySize(source); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T *item = source[i]; - - // - if (item != NULL) - { - // - Add( - (XCZone *)item, - dest // - ); - } - } - - // - int destCount = ArraySize(dest); - result = IsValidSize(destCount); - - // - return result; -} - -template -bool ToBox( - T *&source[], - XBoxZone &dest[] // -) -{ - // - bool result = false; - - // - Clean(dest); - - // - int count = ArraySize(source); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T *item = source[i]; - - // - if (item != NULL) - { - // - XBoxZone iBox; - bool hasBox = ToBox( - iBox, - item // - ); - - // - if (hasBox) - { - // - AddRef( - iBox, - dest // - ); - } - } - } - - // - int destCount = ArraySize(dest); - result = IsValidSize(destCount); - - // - return result; -} - -template -int GetOldest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetOldest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetYoungest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetYoungest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetLowest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetLowest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -int GetHighest( - T *&source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone boxes[]; - bool isConverted = ToBox( - source, - boxes // - ); - if (!isConverted) - { - return result; - } - - // - int boxesCount = ArraySize(boxes); - - // - if (count != boxesCount) - { - return result; - } - - // - result = GetHighest(boxes); - - // - Clean(boxes); - - // - return result; -} - -template -bool IsSame( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = sourceBox.IsSameAs(destBox); - - // - return result; -} - -template -bool IsSameDiff( - T *source, - F *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = sourceBox.IsSame(destBox); - - // - return result; -} - -template -bool IsBelow( - T *source, - T *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxBelow( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsBelowDiff( - T *source, - F *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxBelow( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsAbove( - T *source, - T *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxAbove( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsAboveDiff( - T *source, - F *dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxAbove( - sourceBox, - destBox, - ignoreInside // - ); - - // - return result; -} - -template -bool IsInside( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInside( - sourceBox, - destBox // - ); - - // - return result; -} - -template -bool IsInsideOr( - T *source, - T *dest // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInsideOr( - sourceBox, - destBox // - ); - - // - return result; -} - -template -bool IsInsideDiff( - T *source, - F *dest, - bool forceSideOut = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInside( - sourceBox, - destBox, - forceSideOut // - ); - - // - return result; -} - -template -bool IsInsideOrDiff( - T *source, - F *dest, - bool forceSideOut = false // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - XBoxZone destBox; - result = ToBox( - destBox, - dest // - ); - if (!result) - { - return result; - } - - // - result = IsBoxInsideOr( - sourceBox, - destBox // - ); - - // - return result; -} - -template -bool FindIndex( - int &index, - T *item, - T *&items[] // -) -{ - // - bool result = false; - - // - index = -1; - - // - XBoxZone itemBox; - result = ToBox( - itemBox, - item // - ); - if (!result) - { - return result; - } - - // - XBoxZone itemsBox[]; - result = ToBox( - items, - itemsBox // - ); - if (!result) - { - return result; - } - - // - result = FindBoxIndex( - index, - itemBox, - itemsBox // - ); - - // - return result; -} - -template -bool IsInside( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsInsideBox( - value, - sourceBox // - ); - - // - return result; -} - -template -bool IsAbove( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsAboveBox( - value, - sourceBox // - ); - - // - return result; -} - -template -bool IsBelow( - double value, - T *source // -) -{ - // - bool result = false; - - // - XBoxZone sourceBox; - result = ToBox( - sourceBox, - source // - ); - if (!result) - { - return result; - } - - // - result = IsBelowBox( - value, - sourceBox // - ); - - // - return result; -} - -/** - * Find Specified Box Index inside a Collection of Boxes ... - * - * @param box: XBoxZone instance Reference ... - * @param boxes: XBoxZone instance Reference Collection ... - * - * @return ( int ) - */ -bool FindBoxIndex( - int &index, - XBoxZone &box, - XBoxZone &boxes[] // -) -{ - // - bool result = false; - - // - index = -1; - - // - int count = ArraySize(boxes); - result = box.IsValid() && - IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = boxes[i]; - - // - bool isSame = box.IsSameAs(iBox); - if (isSame) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; -} - -/** - * Check a BaxHas Valid Place for Specified Bar ... - * - * @param bar: XOHCL instance reference, Specified Bar ... - * #param box: XBoxZone instance reference, Specified Box ... - * - * @return ( bool ) - */ -bool IsBoxPlaceValidForBar( - XOHCL &bar, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = bar.IsValid() && - box.IsValid(); - if (!result) - { - return result; - } - - // - result = - box.IsBullish() - ? bar.low > box.upper - : bar.high < box.upper; - - // - return result; -} - -/** - * Check Source Box is Below Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param ignoreInside: bool ... - * - * @return ( bool ) - */ -bool IsBoxBelow( - XBoxZone &source, - XBoxZone &dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - if (!ignoreInside) - { - result = source.upper < dest.lower; - } - else - { - result = (source.upper < dest.lower || - source.upper >= dest.upper) && - source.lower < dest.lower; - } - - // - return result; -} - -/** - * Check Source Box is Above Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param ignoreInside: bool ... - * - * @return ( bool ) - */ -bool IsBoxAbove( - XBoxZone &source, - XBoxZone &dest, - bool ignoreInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - if (!ignoreInside) - { - result = source.lower > dest.upper; - } - else - { - result = (source.lower > dest.upper || - source.lower <= dest.upper) && - source.upper > dest.upper; - } - - // - return result; -} - -/** - * Check Source Box is Inside Dest ... - * - * @param source: XBoxZone instance Reference ... - * @param dest: XBoxZone instance Reference ... - * @param forceSideOut: bool, force check Box has One Side Out ... - * @param ignoreSideOut: bool, Accept if source Box one Side is out of Dest Box ... - * - * @return ( bool ) - */ -bool IsBoxInside( - XBoxZone &source, - XBoxZone &dest, - bool forceSideOut = false, // - bool ignoreSideOut = true // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(dest.dir); - - // - if (!forceSideOut) - { - // - if (ignoreSideOut) - { - // - result = source.lower >= dest.lower && - source.upper <= dest.upper; - } - else - { - result = source.lower >= dest.lower || - source.upper <= dest.upper; - } - } - else - { - // - bool hasSideIn = - isBullish - ? source.lower >= dest.lower - : source.upper <= dest.upper; - bool hasSideOut = - isBullish - ? source.upper >= dest.upper - : source.lower <= dest.lower; - result = - hasSideIn && - hasSideOut; - } - - // - return result; -} - -/** - * Detect source BoX is Inside Dest Box or Have a Side Out on it ... - * - * @param source: XBoxZone instance, source box which checks by dest ... - * @param dest: XBoxZone instance, dest Box which compares source with it ... - * - * @return ( bool ) - */ -bool IsBoxInsideOr( - XBoxZone &source, - XBoxZone &dest, - bool forceInside = false // -) -{ - // - bool result = false; - - // - result = source.IsValid() && - dest.IsValid() && - !source.IsSameAs(dest); - if (!result) - { - return result; - } - - // - bool isInside = - source.upper <= dest.upper && - source.upper >= dest.lower && - source.lower >= dest.lower && - source.lower <= dest.upper; - bool isUpperInside = - source.upper <= dest.upper && - source.upper >= dest.lower; - bool isLowerInside = - source.lower >= dest.lower && - source.lower <= dest.upper; - - // - result = - forceInside - ? isInside - : (isInside || - isLowerInside || - isUpperInside); - - // - return result; -} - -/** - * Check Value is Inside Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsInsideBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value <= box.upper && - value >= box.lower; - - // - return result; -} - -/** - * Check Bar is Inside Specified Box ... - * - * @param bar: XOHCL instance reference, Specified Bar ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsInsideBox( - XOHCL &bar, - XBoxZone &box // -) -{ - // - bool result = false; - - // - // Validate Args ... - result = bar.IsValid() && - box.IsValid(); - if (!result) - { - return result; - } - - // - result = - bar.close <= box.upper && - bar.close >= box.lower; - - // - return result; -} - -/** - * Check Value is Above Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsAboveBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value > box.upper; - - // - return result; -} - -/** - * Check Value is Below Specified Box ... - * - * @param value: double ... - * @param box: XCBozZone instance Reference ... - * - * @return ( bool ) - */ -bool IsBelowBox( - double value, - XBoxZone &box // -) -{ - // - bool result = false; - - // - result = value > 0 && - box.IsValid() && - value < box.lower; - - // - return result; -} - -/** - * Check a Box is Used or not ... - * - * @param box: XBoxZone instance Reference ... - * @param fromIndex: int ... - * @param toIndex: int - * @param forPeriod: Specified Period ... - * - * @return ( bool ) - */ -bool IsBoxUsed( - XBoxZone &box, - int fromIndex, - int toIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - if (toIndex < 0) - { - toIndex = 0; - } - - // - result = - // - box.IsValid() && - fromIndex > 0 && - fromIndex > toIndex - // - ; - if (!result) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - ENUM_X_DIRECTION forDir = box.dir; - bool isBullish = IsBullish(forDir); - - // - bool isTouched = false; - for (int i = fromIndex; i >= toIndex; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - box.symbol, - forPeriod, - i // - ); - - // - isTouched = - isInited && - (isBullish - ? iBar.low > box.upper - : iBar.high < box.lower); - if (!isTouched) - { - continue; - } - - // - iBar.Clean(); - break; - } - - // - result = isTouched; - - // - return result; -} - -/** - * Validate Box ... - * - * @param box: XBoxZone instance ... - * @param barIndex: int, Current Bar Index ... - * @param forPeriod: Testing Period ... - * - * @return ( bool ) - */ -bool IsBoxValid( - XBoxZone &box, - int barIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - return true; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - int toIndex = iBarShift( - box.symbol, - forPeriod, - box.to // - ); - result = IsValidIndex(toIndex); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool isBullish = box.IsBullish(); - for (int i = barIndex; i < toIndex; i++) - { - // - result = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!result) - { - break; - } - - // - result = - isBullish - ? iBar.low > box.upper - : iBar.high < box.lower; - if (!result) - { - break; - } - - // - iBar.Clean(); - } - - // - iBar.Clean(); - - // - return result; -} - -/** - * Check Box Breaked ... - * - * @param box: XBoxZone instance ... - * @param barIndex: int, Current Bar Index ... - * @param forPeriod: Testing Period ... - * - * @return ( bool ) - */ -bool IsBoxBreaked( - XBoxZone &box, - int barIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - int toIndex = iBarShift( - box.symbol, - forPeriod, - box.to // - ); - result = IsValidIndex(toIndex); - if (!result) - { - return result; - } - - // - XOHCL iBar; - bool isBullish = box.IsBullish(); - for (int i = barIndex; i < toIndex; i++) - { - // - result = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!result) - { - break; - } - - // - result = - isBullish - ? iBar.high < box.lower - : iBar.low > box.upper; - if (!result) - { - break; - } - - // - iBar.Clean(); - } - - // - iBar.Clean(); - - // - return result; -} - -/** - * Check a Box is Breaked or not ... - * - * @param box: XBoxZone instance Reference ... - * @param fromIndex: int ... - * @param toIndex: int - * @param forPeriod: Specified Period ... - * - * @return ( bool ) - */ -bool IsBoxBreaked( - XBoxZone &box, - int fromIndex, - int toIndex = 0, - ENUM_TIMEFRAMES forPeriod = NULL // -) -{ - // - bool result = false; - - // - if (toIndex < 0) - { - toIndex = 0; - } - - // - result = - // - box.IsValid() && - fromIndex > 0 && - fromIndex > toIndex - // - ; - if (!result) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - ENUM_X_DIRECTION forDir = box.dir; - bool isBullish = IsBullish(forDir); - - // - bool isBreaked = false; - for (int i = fromIndex; i >= toIndex; i--) - { - // - XOHCL iBar; - bool isInited = iBar.Init( - box.symbol, - forPeriod, - i // - ); - - // - isBreaked = - isInited && - (isBullish - ? iBar.high <= box.lower - : iBar.low >= box.upper); - if (!isBreaked) - { - continue; - } - - // - iBar.Clean(); - break; - } - - // - result = isBreaked; - - // - return result; -} - -/** - * Find an Inside Box of source in a Collection ... - * - * @param index: int, Founded Index ... - * @param source: XBoxZone instance ... - * @param dest: XBoxZone instance Collection ... - * - * @return ( bool ) - */ -bool HasInsideBox( - int &index, - XBoxZone &source, - XBoxZone &dest[] // -) -{ - // - bool result = false; - - // - index = -1; - - // - result = source.IsValid() && - HasChild(dest); - - // - int count = ArraySize(dest); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = dest[i]; - - // - bool isInside = !iBox.IsSameAs(source) && - IsBoxInsideOr( - iBox, - source // - ); - if (isInside) - { - // - index = i; - iBox.Clean(); - - // - break; - } - - // - iBox.Clean(); - } - - // - result = IsValidIndex(index); - - // - return result; -} - -/** - * Remove Specified Box from Collection ... - */ -bool RemoveBox( - XBoxZone &box, - XBoxZone &boxes[] // -) -{ - // - bool result = false; - - // - result = - box.IsValid() && - HasChild(boxes); - if (!result) - { - return result; - } - - // - int idx = -1; - result = FindBoxIndex( - idx, - box, - boxes // - ); - if (!result) - { - return result; - } - - // - result = ArrayRemove( - boxes, - idx, - 1 // - ); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCOrderBlock *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = item.IsBullish() - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCFVG *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = item.IsBullish() - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCSupportZone *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = X_DIRECTION_BULLISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCResistanceZone *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = X_DIRECTION_BEARISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCSupplyZone *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = X_DIRECTION_BEARISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XCDemandZone *item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item != NULL && - item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.To(); - box.from = item.From(); - box.upper = item.Upper(); - box.lower = item.Lower(); - box.symbol = item.GetSymbol(); - box.period = item.GetPeriod(); - box.type = item.TypeAsString(); - box.dir = X_DIRECTION_BULLISH; - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -bool ToBox( - XBoxZone &box, - XConsolidationZone &item // -) -{ - // - bool result = false; - - // - box.Clean(); - - // - result = item.IsValid(); - if (!result) - { - return result; - } - - // - box.to = item.to; - box.dir = item.dir; - box.from = item.from; - box.upper = item.upper; - box.lower = item.lower; - box.symbol = item.symbol; - box.period = item.period; - box.type = IsBullish(item.dir) - ? ToString(X_BULLISH_CONSOLIDATION_ZONE) - : ToString(X_BEARISH_CONSOLIDATION_ZONE); - - // - result = box.IsValid(); - - // - return result; -} - -/** - * Converts to XBoxZone ... - * - * @return ( bool ) - */ -int ToBox( - XConsolidationZone &source[], - XBoxZone &dest[] // -) -{ - // - int result = 0; - - // - Clean(dest); - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XConsolidationZone iZone = source[i]; - - // - XBoxZone iBox; - bool hasBox = ToBox( - iBox, - iZone // - ); - - // - if (hasBox) - { - // - AddRef( - iBox, - dest // - ); - } - - // - iBox.Clean(); - iZone.Clean(); - } - - // - result = ArraySize(dest); - - // - return result; -} - -/** - * Get Oldest Box Index ... - * - * @param source: XBoxZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetOldest( - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from > iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} -int GetOldest( - XOHCL &bar, - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - if (!bar.IsValid()) - { - return result; - } - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool isBoxValidForBar = IsBoxPlaceValidForBar(bar, iBox); - if (!isBoxValidForBar) - { - // - iBox.Clean(); - - // - continue; - } - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from > iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Youngest Box Index ... - * - * @param source: XBoxZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetYoungest( - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from < iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} -int GetYoungest( - XOHCL &bar, - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - if (!bar.IsValid()) - { - return result; - } - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool isBoxValidForBar = IsBoxPlaceValidForBar(bar, iBox); - if (!isBoxValidForBar) - { - // - iBox.Clean(); - - // - continue; - } - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from < iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Highest Box Index ... - * - * @param source: XBoxZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetHighest( - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.upper < iBox.upper; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} -int GetHighest( - XOHCL &bar, - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - if (!bar.IsValid()) - { - return result; - } - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool isBoxValidForBar = IsBoxPlaceValidForBar(bar, iBox); - if (!isBoxValidForBar) - { - // - iBox.Clean(); - - // - continue; - } - - // - bool canSet = - !selected.IsValid() - ? true - : selected.upper < iBox.upper; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Lowest Box Index ... - * - * @param source: XBoxZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetLowest( - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.lower > iBox.lower; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} -int GetLowest( - XOHCL &bar, - XBoxZone &source[] // -) -{ - // - int result = -1; - - // - if (!bar.IsValid()) - { - return result; - } - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - bool isBoxValidForBar = IsBoxPlaceValidForBar(bar, iBox); - if (!isBoxValidForBar) - { - // - iBox.Clean(); - - // - continue; - } - - // - bool canSet = - !selected.IsValid() - ? true - : selected.lower > iBox.lower; - if (canSet) - { - // - result = i; - selected = iBox; - } - - // - iBox.Clean(); - } - - // - selected.Clean(); - - // - return result; -} - -// -// -// - -/** - * Get Oldest Index ... - * - * @param source: XConsolidationZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetOldest( - XConsolidationZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone tmpBoxes[]; - int boxesCount = ToBox( - source, - tmpBoxes // - ); - if (!IsValidSize(boxesCount)) - { - // - Clean(tmpBoxes); - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < boxesCount; i++) - { - // - XBoxZone iBox = tmpBoxes[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from > iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - Clean(tmpBoxes); - selected.Clean(); - - // - return result; -} - -/** - * Get Youngest Index ... - * - * @param source: XConsolidationZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetYoungest( - XConsolidationZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone tmpBoxes[]; - int boxesCount = ToBox( - source, - tmpBoxes // - ); - if (!IsValidSize(boxesCount)) - { - // - Clean(tmpBoxes); - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < boxesCount; i++) - { - // - XBoxZone iBox = tmpBoxes[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.from < iBox.from; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - Clean(tmpBoxes); - selected.Clean(); - - // - return result; -} - -/** - * Get Highest Index ... - * - * @param source: XConsolidationZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetHighest( - XConsolidationZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone tmpBoxes[]; - int boxesCount = ToBox( - source, - tmpBoxes // - ); - if (!IsValidSize(boxesCount)) - { - // - Clean(tmpBoxes); - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < boxesCount; i++) - { - // - XBoxZone iBox = tmpBoxes[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.upper < iBox.upper; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - Clean(tmpBoxes); - selected.Clean(); - - // - return result; -} - -/** - * Get Lowest Index ... - * - * @param source: XConsolidationZone instance Reference Collection ... - * - * @return ( int ) - */ -int GetLowest( - XConsolidationZone &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XBoxZone tmpBoxes[]; - int boxesCount = ToBox( - source, - tmpBoxes // - ); - if (!IsValidSize(boxesCount)) - { - // - Clean(tmpBoxes); - return result; - } - - // - XBoxZone selected; - for (int i = 0; i < boxesCount; i++) - { - // - XBoxZone iBox = tmpBoxes[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.lower > iBox.lower; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - Clean(tmpBoxes); - selected.Clean(); - - // - return result; -} - -// -// -// - -// -template -void SortZones( - T *&source[], - ENUM_X_DIRECTION forDir, - bool ignoreInside = true // -) -{ - // - int idx = -1; - int count = 0; - bool has = false; - - // - has = HasDirection(forDir); - if (!has) - { - return; - } - - // - bool isBullish = IsBullish(forDir); - - // - count = ArraySize(source); - has = IsValidSize(count); - if (!has) - { - return; - } - - // - T *tmpItems[]; - T *last = NULL; - bool hasLast = false; - while (HasChild(source)) - { - // - if (!hasLast) - { - // - idx = GetOldest(source); - hasLast = IsValidIndex(idx); - if (hasLast) - { - // - last = source[idx]; - ArrayRemove( - source, - idx, - 1 // - ); - - // - Add( - last, - tmpItems // - ); - } - - // - count = ArraySize(source); - has = IsValidSize(count); - if (!has) - { - // - ZeroMemory(last); - break; - } - } - if (!hasLast) - { - // - ZeroMemory(last); - break; - } - - // - T *item = NULL; - idx = GetOldest(source); - has = IsValidIndex(idx); - if (!has) - { - // - ZeroMemory(last); - ZeroMemory(item); - break; - } - item = source[idx]; - ArrayRemove( - source, - idx, - 1 // - ); - - // - bool isAbove = IsAbove( - item, - last, - ignoreInside // - ); - - // - bool isBelow = IsBelow( - item, - last, - ignoreInside // - ); - - // - has = - isBullish - ? isAbove - : isBelow; - if (has) - { - // - Add( - item, - tmpItems // - ); - - // - last = item; - hasLast = item != NULL; - } - } - - // - Clean(source); - Copy( - tmpItems, - source // - ); - - // - Clean(tmpItems); -} - -/** - * Extract all Zones Which provided bar is Inside it ... - * - * @return ( int ) - */ -template -int ExtractInsideZones( - XOHCL &bar, // Bar ... - T *&zones[], // Source of Zones ... - T *&dest[] // Dest (all inside Zones) ... -) -{ - // - int result = 0; - - // - Clean(dest); - - // - int count = ArraySize(zones); - bool isValid = bar.IsValid() && - IsValidSize(count); - if (!isValid) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T *iZone = zones[i]; - - // - bool isHighInside = IsInside( - bar.high, - iZone // - ); - - // - bool isLowInside = IsInside( - bar.low, - iZone // - ); - - // - bool isInside = - isLowInside && - isHighInside; - - // - if (isInside) - { - // - Add( - iZone, - dest // - ); - } - - // - ZeroMemory(iZone); - } - - // - result = ArraySize(dest); - - // - return result; -} - -/** - * Add Specific Item into a Collection Reference only if it's not Exists ... - * - * @return ( bool ) - */ -template -bool AddIfNotExists( - T *item, - T *&items[] // -) -{ - // - bool result = false; - - // - result = item != NULL; - if (!result) - { - return result; - } - - // - int before = ArraySize(items); - - // - int idx = FindIndex( - item, - items // - ); - bool has = IsValidIndex(idx); - result = !has; - if (!result) - { - return result; - } - - // - Add( - item, - items // - ); - - // - int after = ArraySize(items); - - // - result = after > before; - - // - return result; -} -bool AddIfNotExists( - XConsolidationZone &item, - XConsolidationZone &items[] // -) -{ - // - bool result = false; - - // - result = item.IsValid(); - if (!result) - { - return result; - } - - // - int before = ArraySize(items); - - // - int idx = FindIndex( - item, - items // - ); - bool has = IsValidIndex(idx); - result = !has; - if (!result) - { - return result; - } - - // - AddRef( - item, - items // - ); - - // - int after = ArraySize(items); - - // - result = after > before; - - // - return result; -} - -/** - * Add items Collection reference Members into source Collection only if it's not Exists ...alignas - * @return ( int ) - */ -template -int AddIfNotExists( - T *&items[], - T *&sources[] // -) -{ - // - int result = 0; - - // - bool has = HasChild(items); - if (!has) - { - return result; - } - - // - int before = ArraySize(sources); - - // - int count = ArraySize(items); - for (int i = 0; i < count; i++) - { - // - has = AddIfNotExists( - items[i], - sources // - ); - } - - // - int after = ArraySize(sources); - - // - result = after > before; - - // - return result; -} -int AddIfNotExists( - XConsolidationZone &items[], - XConsolidationZone &sources[] // -) -{ - // - int result = 0; - - // - bool has = HasChild(items); - if (!has) - { - return result; - } - - // - int before = ArraySize(sources); - - // - int count = ArraySize(items); - for (int i = 0; i < count; i++) - { - // - has = AddIfNotExists( - items[i], - sources // - ); - } - - // - int after = ArraySize(sources); - - // - result = after > before; - - // - return result; -} - -/** - * Update to Time of Specifiex Collection ... - * - * @param items: XOBFVG instance Collection ... - * @param value: datetime ... - */ -template -void SpecifiedUpdateTo( - T *&items[], - datetime value = NULL // -) -{ - // - value = NormalizeTime(value); - - // - int count = ArraySize(items); - bool has = HasChild(items); - if (!has) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - items[i].To(value); - } -} - -// -template -int FilterZones( - // - T *&source[], - // - ENUM_X_DIRECTION forDir, - ENUM_TIMEFRAMES forPeriod = NULL, - datetime after = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false, - // - bool applySort = false, - // - bool ignoreInside = true - // -) -{ - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - has = HasDirection(forDir); - if (!has) - { - return result; - } - - // - bool isBullish = IsBullish(forDir); - - // - count = ArraySize(source); - has = IsValidSize(count); - if (!has) - { - return result; - } - - // - T *tmpZones[]; - XOHCL passedBar; - bool isPassed = false; - for (int i = 0; i < count; i++) - { - // - T *iZone = source[i]; - - // - // Apply after Filter ... - isPassed = - !IsValid(after) - ? true - : iZone.From() >= after; - if (!isPassed) - { - // - ZeroMemory(iZone); - continue; - } - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - forDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - forDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - forDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - forDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - tmpZones // - ); - if (has) - { - // - ZeroMemory(iZone); - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - tmpZones // - ); - } - - // - Clean(source); - - // - has = HasChild(tmpZones); - if (!has) - { - // - Clean(tmpZones); - passedBar.Clean(); - return result; - } - - // - // Apply Sorting ... - if (applySort) - { - // - T *last = NULL; - bool hasLast = false; - while (HasChild(tmpZones)) - { - // - idx = GetYoungest(tmpZones); - hasLast = IsValidIndex(idx); - if (hasLast) - { - // - last = tmpZones[idx]; - ArrayRemove( - tmpZones, - idx, - 1 // - ); - - // - Add( - last, - source // - ); - } - - // - has = HasChild(tmpZones); - if (!has) - { - break; - } - - // - T *zone = NULL; - bool hasZone = false; - idx = GetYoungest(tmpZones); - hasZone = IsValidIndex(idx); - if (hasZone) - { - // - zone = tmpZones[idx]; - ArrayRemove( - tmpZones, - idx, - 1 // - ); - } - if (!hasZone) - { - // - ZeroMemory(zone); - continue; - } - - // - bool isAbove = IsAbove( - zone, - last, - ignoreInside // - ); - - // - bool isBelow = IsBelow( - zone, - last, - ignoreInside // - ); - - // - isPassed = - isBullish - ? isAbove - : isBelow; - if (!isPassed) - { - // - ZeroMemory(zone); - continue; - } - - // - Add( - zone, - source // - ); - } - } - else - { - // - Copy( - tmpZones, - source // - ); - } - - // - result = ArraySize(source); - - // - return result; -} - -// -// -// - -/** - * Detect Nearest Price Out of Specified Box ... - * - * @param box: XBoxZone instance Reference ... - * @param outSideBar: XOHCL instance Reference which Represents Out Side Bar if Exists ... - * @param forPeriod: ENUM_TIMEFRAMES member which provides time frame of Out Bar, if not Provides used box Period as Default ... - * @param forDir: ENUM_X_DIRECTION member which Specified outSide Direction, use Box Dir as Default ... - * @param forceBodyIn: bool value which Specifyed Body Breakes or not, Default is false ... - * @param barIndex: integer value which Specified Start Bar Index, Default is 0 ... - * - * @return ( bool ) - */ -bool DetectBoxNearestPriceOut( - XBoxZone &box, - XOHCL &outSideBar, - ENUM_TIMEFRAMES forPeriod = NULL, - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, - bool forceBodyIn = false, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - outSideBar.Clean(); - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - if (!HasDirection(forDir)) - { - forDir = box.dir; - } - - // - bool isBullish = IsBullish(forDir); - - // - int fromIndex = iBarShift( - box.symbol, - forPeriod, - box.from // - ); - result = IsValidIndex(fromIndex); - if (!result) - { - return result; - } - - // - XOHCL iBar; - XOHCL iPBar; - bool has = false; - for (int i = barIndex; i < fromIndex; i++) - { - // - has = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!has) - { - continue; - } - - // - has = iBar.GetPreviousBar(iPBar); - if (!has) - { - continue; - } - - // - bool isInsideFromLower = - iBar.high < box.lower && - iPBar.high > box.lower; - - // - bool isInsideFromUpper = - iBar.low > box.upper && - iPBar.low < box.upper; - - // - bool isInsideBodyFromLower = - iPBar.GetUp() > box.lower; - - // - bool isInsideBodyFromUpper = - iPBar.GetDown() < box.upper; - - // - result = - isBullish - ? (!forceBodyIn - ? isInsideFromLower - : isInsideFromLower && - isInsideBodyFromLower) - : (!forceBodyIn - ? isInsideFromUpper - : isInsideFromUpper && - isInsideBodyFromUpper); - if (result) - { - // - outSideBar = iBar; - break; - } - } - - // - iBar.Clean(); - iPBar.Clean(); - - // - return result; -} - -/** - * Count number of Box Retests ... - * - * @param box: XBoxZone instance Reference ... - * @param forDir: ENUM_X_DIRECTION member, Specified Retesting Direction ... - * @param forPeriod: ENUM_TIMEFRAMES member, Specified Retesting Period ... - * @param forceType: bool, Specified Retest Bar Direction is Same as Retesting Direction ... - * @param forcePressure: bool, Specified Retest Bar must Has Fibo Pressure or not ... - * - * @return ( int ) - */ -int CountBoxRetest( - XBoxZone &box, - ENUM_X_DIRECTION forDir = NULL, - ENUM_TIMEFRAMES forPeriod = NULL, - bool forceType = false, - bool forcePressure = false // -) -{ - // - int result = 0; - - // - if (!IsValid(forPeriod)) - { - forPeriod = box.period; - } - - // - if (!IsValid(forDir)) - { - forDir = box.dir; - } - - // - bool isValid = - box.IsValid() && - IsValid(forDir); - if (!isValid) - { - return result; - } - - // - int fromIDX = GetBarIndex( - box.symbol, - forPeriod, - box.from // - ); - - // - int toIDX = GetBarIndex( - box.symbol, - forPeriod, - box.to // - ); - - // - for (int i = fromIDX; i >= toIDX; i--) - { - // - // Initialize Indexed Bar ... - XOHCL iBar; - isValid = iBar.Init( - box.symbol, - forPeriod, - i // - ); - if (!isValid) - { - // - iBar.Clean(); - continue; - } - - // - bool isUpperBullishRejected = iBar.IsRejected( - box.upper, - X_DIRECTION_BULLISH, - forceType, - forcePressure // - ); - bool isUpperBearishRejected = iBar.IsRejected( - box.upper, - X_DIRECTION_BEARISH, - forceType, - forcePressure // - ); - - // - bool isLowerBullishRejected = iBar.IsRejected( - box.lower, - X_DIRECTION_BULLISH, - forceType, - forcePressure // - ); - bool isLowerBearishRejected = iBar.IsRejected( - box.lower, - X_DIRECTION_BEARISH, - forceType, - forcePressure // - ); - - // - if (forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BULLISH) - { - // - if (isUpperBullishRejected || - isLowerBullishRejected) - { - result++; - } - } - - // - if (forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BEARISH) - { - // - if (isUpperBearishRejected || - isLowerBearishRejected) - { - result++; - } - } - - // - iBar.Clean(); - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-poi.state.lib.mq5 b/Documents/BKP/x-saherelm.x-poi.state.lib.mq5 deleted file mode 100644 index e52ea2b5..00000000 --- a/Documents/BKP/x-saherelm.x-poi.state.lib.mq5 +++ /dev/null @@ -1,4680 +0,0 @@ - -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Seriallize Library -// --------------------------------------- -// Name: XPOILib -// Description: All models related to POIs ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright `023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -enum ENUM_X_OBFVG_FVG_FILTERS -{ - X_OBFVG_FVG_FILTER_NONE, - X_OBFVG_FVG_FILTER_INSIDE_OR, - X_OBFVG_FVG_FILTER_ABOVE_BELOW, -}; - -// -enum ENUM_X_OBFVG_FVG_SELECTION -{ - X_OBFVG_FVG_SELECT_NONE, - X_OBFVG_FVG_SELECT_OLDEST, - X_OBFVG_FVG_SELECT_LOWEST, - X_OBFVG_FVG_SELECT_HIGHEST, - X_OBFVG_FVG_SELECT_YOUNGEST, - X_OBFVG_FVG_SELECT_HIGHEST_LOWEST, - X_OBFVG_FVG_SELECT_LOWEST_HIGHEST, -}; - -// -struct XSignalBox -{ - // - XBoxZone ob; - XBoxZone fvg; - XBoxZone sharp; - - // - double sl; - double tp; - - // - // Constructor ... - XSignalBox() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - sl = 0; - tp = 0; - - // - ob.Clean(); - fvg.Clean(); - sharp.Clean(); - - // - ZeroMemory(this); - } - - /** - * Validate Model ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - ob.IsValid() && - fvg.IsValid() && - sharp.IsValid(); - - // - return result; - } - - /** - * Update Structure Models To Date ... - * - * @param value: datetime ... - */ - void UpdateTo(datetime value = NULL) - { - // - value = NormalizeTime(value); - - // - if (ob.IsValid()) - { - ob.to = value; - } - - // - if (fvg.IsValid()) - { - fvg.to = value; - } - - // - if (sharp.IsValid()) - { - sharp.to = value; - } - } - - // -}; - -// -// Model State Parsing ... -struct XPOIStateEvents -{ - // - // Props ... - - // - // Swings ... - bool hasNewSwing; - bool hasNewSwingLow; - bool hasNewSwingHigh; - - // - // Momentums ... - bool hasNewMomentum; - bool hasNewBullishMomentum; - bool hasNewBearishMomentum; - - // - // Rejections ... - bool hasNewRejection; - bool hasNewBullishRejection; - bool hasNewBearishRejection; - - // - // Pullbacks ... - bool hasNewPullback; - bool hasNewBullishPullback; - bool hasNewBearishPullback; - - // - // Support/Resistance (s) ... - bool hasNewSupportZone; - bool hasNewResistanceZone; - - // - // Supply/Demand (s) ... - bool hasNewSupplyZone; - bool hasNewDemandZone; - - // - // Fair Value Gaps ... - bool hasNewFairValueGap; - bool hasNewBullishFairValueGap; - bool hasNewBearishFairValueGap; - - // - // Order Blocks ... - bool hasNewOrderBlock; - bool hasNewBullishOrderBlock; - bool hasNewBearishOrderBlock; - - // - // Spikes ... - bool hasNewSpike; - bool hasNewBullishSpike; - bool hasNewBearishSpike; - - // - // Sharps ... - bool hasNewSharp; - bool hasNewBullishSharp; - bool hasNewBearishSharp; - - // - // Consolidation Zones ... - bool hasNewConsolidationZone; - bool hasNewBullishConsolidationZone; - bool hasNewBearishConsolidationZone; - - // - // Constructor ... - XPOIStateEvents() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - hasNewSwing = false; - hasNewSwingLow = false; - hasNewSwingHigh = false; - - // - hasNewMomentum = false; - hasNewBullishMomentum = false; - hasNewBearishMomentum = false; - - // - hasNewRejection = false; - hasNewBullishRejection = false; - hasNewBearishRejection = false; - - // - hasNewSupportZone = false; - hasNewResistanceZone = false; - - // - hasNewSupplyZone = false; - hasNewDemandZone = false; - - // - hasNewFairValueGap = false; - hasNewBullishFairValueGap = false; - hasNewBearishFairValueGap = false; - - // - hasNewOrderBlock = false; - hasNewBullishOrderBlock = false; - hasNewBearishOrderBlock = false; - - // - hasNewSpike = false; - hasNewBullishSpike = false; - hasNewBearishSpike = false; - - // - hasNewSharp = false; - hasNewBullishSharp = false; - hasNewBearishSharp = false; - - // - hasNewConsolidationZone = false; - hasNewBullishConsolidationZone = false; - hasNewBearishConsolidationZone = false; - - // - ZeroMemory(this); - } - - /** - * Initialize Event Parser Model ... - * - * @param events: ENUM_XPOI_EVENTS members Collection Reference ... - */ - void Init(ENUM_XPOI_EVENTS &events[]) - { - // - hasNewSwing = HasNewSwing(events); - hasNewSwingLow = HasNewSwingLow(events); - hasNewSwingHigh = HasNewSwingHigh(events); - - // - hasNewMomentum = HasNewMomentum(events); - hasNewBullishMomentum = HasNewBullishMomentum(events); - hasNewBearishMomentum = HasNewBearishMomentum(events); - - // - hasNewRejection = HasNewRejection(events); - hasNewBullishRejection = HasNewBullishRejection(events); - hasNewBearishRejection = HasNewBearishRejection(events); - - // - hasNewPullback = HasNewPullback(events); - hasNewBullishPullback = HasNewBullishPullback(events); - hasNewBearishPullback = HasNewBearishPullback(events); - - // - hasNewSupportZone = HasNewSupportZone(events); - hasNewResistanceZone = HasNewResistanceZone(events); - - // - hasNewSupplyZone = HasNewSupplyZone(events); - hasNewDemandZone = HasNewDemandZone(events); - - // - hasNewFairValueGap = HasNewFairValueGap(events); - hasNewBullishFairValueGap = HasNewBullishFairValueGap(events); - hasNewBearishFairValueGap = HasNewBearishFairValueGap(events); - - // - hasNewOrderBlock = HasNewOrderBlock(events); - hasNewBullishOrderBlock = HasNewBullishOrderBlock(events); - hasNewBearishOrderBlock = HasNewBearishOrderBlock(events); - - // - hasNewSpike = HasNewSpike(events); - hasNewBullishSpike = HasNewBullishSpike(events); - hasNewBearishSpike = HasNewBearishSpike(events); - - // - hasNewSharp = HasNewSharp(events); - hasNewBullishSharp = HasNewBullishSharp(events); - hasNewBearishSharp = HasNewBearishSharp(events); - - // - hasNewConsolidationZone = HasNewConsolidationZone(events); - hasNewBullishConsolidationZone = HasNewBullishConsolidationZone(events); - hasNewBearishConsolidationZone = HasNewBearishConsolidationZone(events); - } - - // -}; - -// -// Model Exists Founded POIs ... -struct XPOIState -{ - // - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - XCSwing *swings[]; // Holds Founded Swing ... - XCSwing *swingLows[]; // Holds Founded Swing Lows ... - XCSwing *swingHighs[]; // Holds Founded Swing Highs ... - - // - XCMomentumBar *momentums[]; // Holds Founded Momentum Bars ... - XCMomentumBar *bullishMomentums[]; // Holds Founded Bullish Momentum Bars ... - XCMomentumBar *bearishMomentums[]; // Holds Founded Bearish Momentum Bars ... - - // - XCRejectionBar *rejections[]; // Holds Founded Rejection Bars ... - XCRejectionBar *bullishRejections[]; // Holds Founded Bullish Rejection Bars ... - XCRejectionBar *bearishRejections[]; // Holds Founded Bearish Rejection Bars ... - - // - XCSupportZone *supportZones[]; // Holds Founded Support Zones ... - XCResistanceZone *resistanceZones[]; // Holds Founded Resistance Zones ... - - // - XCSupplyZone *supplyZones[]; // Holds Founded Supply Zones ... - XCDemandZone *demandZones[]; // Holds Founded Demand Zones ... - - // - XCOrderBlock *orderBlocks[]; // Holds Founded Order Blocks ... - XCOrderBlock *bullishOrderBlocks[]; // Holds Founded Bullish Order Blocks ... - XCOrderBlock *bearishOrderBlocks[]; // Holds Founded Bearish Order Blocks ... - - // - XCFVG *fairValueGaps[]; // Holds Founded Fair Value Gaps ... - XCFVG *bullishFairValueGaps[]; // Holds Founded Bullish Fair Value Gaps ... - XCFVG *bearishFairValueGaps[]; // Holds Founded Bearish Fair Value Gaps ... - - // - XConsolidationZone consolidationZones[]; // Holds Founded Consolidation Zones ... - XConsolidationZone bullishConsolidationZones[]; // Holds Founded Bullish Consolidation Zones ... - XConsolidationZone bearishConsolidationZones[]; // Holds Founded Bearih Consolidation Zones ... - - // - XBoxZone spikes[]; // Holds Founded Spikes ... - XBoxZone bullishSpikes[]; // Holds Founded Bullish Spikes ... - XBoxZone bearishSpikes[]; // Holds Founded Bearih Spikes ... - - // - XBoxZone sharps[]; // Holds Founded Sharps ... - XBoxZone bullishSharps[]; // Holds Founded Bullish Sharps ... - XBoxZone bearishSharps[]; // Holds Founded Bearih Sharps ... - - // - XBoxZone pullbacks[]; // Holds Founded Pullbacks ... - XBoxZone bullishPullbacks[]; // Holds Founded Bullish Pullbacks ... - XBoxZone bearishPullbacks[]; // Holds Founded Bearish Pullbacks ... - - // - // Constructor ... - void XPOIState() - { - Clean(); - } - - // - // Actions ... - - /** - * Cleanup all props ... - */ - void Clean() - { - // - time = NULL; - symbol = NULL; - period = NULL; - - // - // Swings ... - Clean(swings); - Clean(swingLows); - Clean(swingHighs); - - // - // Momentums ... - Clean(momentums); - Clean(bullishMomentums); - Clean(bearishMomentums); - - // - // Rejections ... - Clean(rejections); - Clean(bullishRejections); - Clean(bearishRejections); - - // - // Support / Resistance Zones ... - Clean(supportZones); - Clean(resistanceZones); - - // - // Supply / Demand Zones ... - Clean(supplyZones); - Clean(demandZones); - - // - // Fair Value Gaps ... - Clean(fairValueGaps); - Clean(bullishFairValueGaps); - Clean(bearishFairValueGaps); - - // - // Order Blocks ... - Clean(orderBlocks); - Clean(bullishOrderBlocks); - Clean(bearishOrderBlocks); - - // - // Spikes ... - Clean(spikes); - Clean(bullishSpikes); - Clean(bearishSpikes); - - // - // Sharps ... - Clean(sharps); - Clean(bullishSharps); - Clean(bearishSharps); - - // - // Pullbaks ... - Clean(pullbacks); - Clean(bullishPullbacks); - Clean(bearishPullbacks); - - // - // Consolidation Zones ... - Clean(consolidationZones); - Clean(bullishConsolidationZones); - Clean(bearishConsolidationZones); - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - IsSpecifiedValid(symbol) && - IsSpecifiedValid(period) && - IsSpecifiedValid(time); - - // - return result; - } - - /** - * Check State has Childs or not ... - * - * @return ( bool ) - */ - bool HasChild() - { - // - bool result = false; - - // - result = - // - // Swings ... - HasSwings() || - HasSwingLows() || - HasSwingHighs() || - // - // Momentums ... - HasMomentums() || - HasBullishMomentums() || - HasBearishMomentums() || - // - // Rejections ... - HasRejections() || - HasBullishRejections() || - HasBearishRejections() || - // - // Pullbacks ... - HasPullbacks() || - HasBullishPullbacks() || - HasBearishPullbacks() || - // - // Support / Resistance Zones ... - HasSupportZones() || - HasResistanceZones() || - // - // Supply / Demand Zones ... - HasSupplyZones() || - HasDemandZones() || - // - // Fair Value Gaps ... - HasFairValueGaps() || - HasBullishFairValueGaps() || - HasBearishFairValueGaps() || - // - // Order Blocks ... - HasOrderBlocks() || - HasBullishOrderBlocks() || - HasBearishOrderBlocks() || - // - // Spikes ... - HasSpikes() || - HasBullishSpikes() || - HasBearishSpikes() || - // - // Sharps ... - HasSharps() || - HasBullishSharps() || - HasBearishSharps() || - // - // Consolidation Zones ... - HasConsolidationZones() || - HasBullishConsolidationZones() || - HasBearishConsolidationZones() - // - ; - - // - return result; - } - - // - // Checkers ... - - // - // Swings ... - - // - // Has ... - - // - bool HasSwings() - { - return HasChild(swings); - } - - // - bool HasSwingLows() - { - return HasChild(swingLows); - } - - // - bool HasSwingHighs() - { - return HasChild(swingHighs); - } - - // - // Count ... - - // - int CountSwings() - { - return ArraySize(swings); - } - - // - int CountSwingLows() - { - return ArraySize(swingLows); - } - - // - int CountSwingHighs() - { - return ArraySize(swingHighs); - } - - // - // Momentums ... - - // - // Has ... - - // - bool HasMomentums() - { - return HasChild(momentums); - } - - // - bool HasBullishMomentums() - { - return HasChild(bullishMomentums); - } - - // - bool HasBearishMomentums() - { - return HasChild(bearishMomentums); - } - - // - // Count ... - - // - int CountMomentums() - { - return ArraySize(momentums); - } - - // - int CountBullishMomentums() - { - return ArraySize(bullishMomentums); - } - - // - int CountBearishMomentums() - { - return ArraySize(bearishMomentums); - } - - // - // Rejections ... - - // - // Has ... - - // - bool HasRejections() - { - return HasChild(rejections); - } - - // - bool HasBullishRejections() - { - return HasChild(bullishRejections); - } - - // - bool HasBearishRejections() - { - return HasChild(bearishRejections); - } - - // - // Count ... - - // - int CountRejections() - { - return ArraySize(rejections); - } - - // - int CountBullishRejections() - { - return ArraySize(bullishRejections); - } - - // - int CountBearishRejections() - { - return ArraySize(bearishRejections); - } - - // - // Pullbacks ... - - // - // Has ... - - // - bool HasPullbacks() - { - return HasChild(pullbacks); - } - - // - bool HasBullishPullbacks() - { - return HasChild(bullishPullbacks); - } - - // - bool HasBearishPullbacks() - { - return HasChild(bearishPullbacks); - } - - // - // Count ... - - // - int CountPullbacks() - { - return ArraySize(pullbacks); - } - - // - int CountBullishPullbacks() - { - return ArraySize(bullishPullbacks); - } - - // - int CountBearishPullbacks() - { - return ArraySize(bearishPullbacks); - } - - // - // Support / Resistance Zones ... - - // - // Has ... - - // - bool HasSupportZones() - { - return HasChild(supportZones); - } - - // - bool HasResistanceZones() - { - return HasChild(resistanceZones); - } - - // - // Count ... - - // - int CountSupportZones() - { - return ArraySize(supportZones); - } - - // - int CountResistanceZones() - { - return ArraySize(resistanceZones); - } - - // - // Supply / Demand Zones ... - - // - // Has ... - - // - bool HasSupplyZones() - { - return HasChild(supplyZones); - } - - // - bool HasDemandZones() - { - return HasChild(demandZones); - } - - // - // Count ... - - // - int CountSupplyZones() - { - return ArraySize(supplyZones); - } - - // - int CountDemandZones() - { - return ArraySize(demandZones); - } - - // - // Fair Value Gaps ... - - // - // Has ... - - // - bool HasFairValueGaps() - { - return HasChild(fairValueGaps); - } - - // - bool HasBullishFairValueGaps() - { - return HasChild(bullishFairValueGaps); - } - - // - bool HasBearishFairValueGaps() - { - return HasChild(bearishFairValueGaps); - } - - // - // Count ... - - // - int CountFairValueGaps() - { - return ArraySize(fairValueGaps); - } - - // - int CountBullishFairValueGaps() - { - return ArraySize(bullishFairValueGaps); - } - - // - int CountBearishFairValueGaps() - { - return ArraySize(bearishFairValueGaps); - } - - // - // Order Blocks ... - - // - // Has ... - - // - bool HasOrderBlocks() - { - return HasChild(orderBlocks); - } - - // - bool HasBullishOrderBlocks() - { - return HasChild(bullishOrderBlocks); - } - - // - bool HasBearishOrderBlocks() - { - return HasChild(bearishOrderBlocks); - } - - // - // Count ... - - // - int CountOrderBlocks() - { - return ArraySize(orderBlocks); - } - - // - int CountBullishOrderBlocks() - { - return ArraySize(bullishOrderBlocks); - } - - // - int CountBearishOrderBlocks() - { - return ArraySize(bearishOrderBlocks); - } - - // - // Spikes ... - - // - // Has ... - - // - bool HasSpikes() - { - return HasChild(spikes); - } - - // - bool HasBullishSpikes() - { - return HasChild(bullishSpikes); - } - - // - bool HasBearishSpikes() - { - return HasChild(bearishSpikes); - } - - // - // Count ... - - // - int CountSpikes() - { - return ArraySize(spikes); - } - - // - int CountBullishSpikes() - { - return ArraySize(bullishSpikes); - } - - // - int CountBearishSpikes() - { - return ArraySize(bearishSpikes); - } - - // - // Sharps ... - - // - // Has ... - - // - bool HasSharps() - { - return HasChild(sharps); - } - - // - bool HasBullishSharps() - { - return HasChild(bullishSharps); - } - - // - bool HasBearishSharps() - { - return HasChild(bearishSharps); - } - - // - // Count ... - - // - int CountSharps() - { - return ArraySize(sharps); - } - - // - int CountBullishSharps() - { - return ArraySize(bullishSharps); - } - - // - int CountBearishSharps() - { - return ArraySize(bearishSharps); - } - - // - // Consolidation Zone ... - - // - // Has ... - - // - bool HasConsolidationZones() - { - return HasChild(consolidationZones); - } - - // - bool HasBullishConsolidationZones() - { - return HasChild(bullishConsolidationZones); - } - - // - bool HasBearishConsolidationZones() - { - return HasChild(bearishConsolidationZones); - } - - // - // Count ... - - // - int CountConsolidationZones() - { - return ArraySize(consolidationZones); - } - - // - int CountBullishConsolidationZones() - { - return ArraySize(bullishConsolidationZones); - } - - // - int CountBearishConsolidationZones() - { - return ArraySize(bearishConsolidationZones); - } - - // - // Box Retrievers ... - - // - int SupportResistancesAsBox(XBoxZone &items[]) - { - // - XBoxZone tmpBoxes[]; - - // - ToBox( - supportZones, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - ToBox( - resistanceZones, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - int result = ArraySize(items); - - // - return result; - } - - // - int SupplyDemandsAsBox(XBoxZone &items[]) - { - // - XBoxZone tmpBoxes[]; - - // - ToBox( - supplyZones, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - ToBox( - demandZones, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - int result = ArraySize(items); - - // - return result; - } - - // - int OrderBlocksAsBox(XBoxZone &items[]) - { - // - XBoxZone tmpBoxes[]; - - // - ToBox( - bullishOrderBlocks, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - ToBox( - bearishOrderBlocks, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - int result = ArraySize(items); - - // - return result; - } - - // - int FairValueGapsAsBox(XBoxZone &items[]) - { - // - XBoxZone tmpBoxes[]; - - // - ToBox( - bullishFairValueGaps, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - ToBox( - bearishFairValueGaps, - tmpBoxes // - ); - Copy( - tmpBoxes, - items, - false // - ); - Clean(tmpBoxes); - - // - int result = ArraySize(items); - - // - return result; - } - - // - int SpikesAsBox(XBoxZone &items[]) - { - // - Copy( - bullishSpikes, - items, - false // - ); - - // - Copy( - bearishSpikes, - items, - false // - ); - - // - int result = ArraySize(items); - - // - return result; - } - - // - int SharpsAsBox(XBoxZone &items[]) - { - // - Copy( - bullishSharps, - items, - false // - ); - - // - Copy( - bearishSharps, - items, - false // - ); - - // - int result = ArraySize(items); - - // - return result; - } - - // - // Tools ... - - // - void UpdateTo(datetime value = NULL) - { - // - value = NormalizeTime(value); - - // - int count = 0; - bool has = false; - - // - has = HasMomentums(); - if (has) - { - // - count = CountMomentums(); - for (int i = 0; i < count; i++) - { - momentums[i].To(value); - } - } - - // - has = HasBullishMomentums(); - if (has) - { - // - count = CountBullishMomentums(); - for (int i = 0; i < count; i++) - { - bullishMomentums[i].To(value); - } - } - - // - has = HasBearishMomentums(); - if (has) - { - // - count = CountBearishMomentums(); - for (int i = 0; i < count; i++) - { - bearishMomentums[i].To(value); - } - } - - // - has = HasRejections(); - if (has) - { - // - count = CountRejections(); - for (int i = 0; i < count; i++) - { - rejections[i].To(value); - } - } - - // - has = HasBullishRejections(); - if (has) - { - // - count = CountBullishRejections(); - for (int i = 0; i < count; i++) - { - bullishRejections[i].To(value); - } - } - - // - has = HasBearishRejections(); - if (has) - { - // - count = CountBearishRejections(); - for (int i = 0; i < count; i++) - { - bearishRejections[i].To(value); - } - } - - // - has = HasSupportZones(); - if (has) - { - // - count = CountSupportZones(); - for (int i = 0; i < count; i++) - { - supportZones[i].To(value); - } - } - - // - has = HasResistanceZones(); - if (has) - { - // - count = CountResistanceZones(); - for (int i = 0; i < count; i++) - { - resistanceZones[i].To(value); - } - } - - // - has = HasSupplyZones(); - if (has) - { - // - count = CountSupplyZones(); - for (int i = 0; i < count; i++) - { - supplyZones[i].To(value); - } - } - - // - has = HasDemandZones(); - if (has) - { - // - count = CountDemandZones(); - for (int i = 0; i < count; i++) - { - demandZones[i].To(value); - } - } - - // - has = HasOrderBlocks(); - if (has) - { - // - count = CountOrderBlocks(); - for (int i = 0; i < count; i++) - { - orderBlocks[i].To(value); - } - } - - // - has = HasBullishOrderBlocks(); - if (has) - { - // - count = CountBullishOrderBlocks(); - for (int i = 0; i < count; i++) - { - bullishOrderBlocks[i].To(value); - } - } - - // - has = HasBearishOrderBlocks(); - if (has) - { - // - count = CountBearishOrderBlocks(); - for (int i = 0; i < count; i++) - { - bearishOrderBlocks[i].To(value); - } - } - - // - has = HasFairValueGaps(); - if (has) - { - // - count = CountFairValueGaps(); - for (int i = 0; i < count; i++) - { - fairValueGaps[i].To(value); - } - } - - // - has = HasBullishFairValueGaps(); - if (has) - { - // - count = CountBullishFairValueGaps(); - for (int i = 0; i < count; i++) - { - bullishFairValueGaps[i].To(value); - } - } - - // - has = HasBearishFairValueGaps(); - if (has) - { - // - count = CountBearishFairValueGaps(); - for (int i = 0; i < count; i++) - { - bearishFairValueGaps[i].To(value); - } - } - - // - has = HasConsolidationZones(); - if (has) - { - // - count = CountConsolidationZones(); - for (int i = 0; i < count; i++) - { - consolidationZones[i].to = value; - } - } - - // - has = HasBullishConsolidationZones(); - if (has) - { - // - count = CountBullishConsolidationZones(); - for (int i = 0; i < count; i++) - { - bullishConsolidationZones[i].to = value; - } - } - - // - has = HasBearishConsolidationZones(); - if (has) - { - // - count = CountBearishConsolidationZones(); - for (int i = 0; i < count; i++) - { - bearishConsolidationZones[i].to = value; - } - } - - // - has = HasSpikes(); - if (has) - { - // - count = CountSpikes(); - for (int i = 0; i < count; i++) - { - spikes[i].to = value; - } - } - - // - has = HasBullishSpikes(); - if (has) - { - // - count = CountBullishSpikes(); - for (int i = 0; i < count; i++) - { - bullishSpikes[i].to = value; - } - } - - // - has = HasBearishSpikes(); - if (has) - { - // - count = CountBearishSpikes(); - for (int i = 0; i < count; i++) - { - bearishSpikes[i].to = value; - } - } - - // - has = HasSharps(); - if (has) - { - // - count = CountSharps(); - for (int i = 0; i < count; i++) - { - sharps[i].to = value; - } - } - - // - has = HasBullishSharps(); - if (has) - { - // - count = CountBullishSharps(); - for (int i = 0; i < count; i++) - { - bullishSharps[i].to = value; - } - } - - // - has = HasBearishSharps(); - if (has) - { - // - count = CountBearishSharps(); - for (int i = 0; i < count; i++) - { - bearishSharps[i].to = value; - } - } - } - - // - // Filter Zones ... - - // - // Support ... - int FilterSupportZones( - XCSupportZone *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasSupportZones(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BULLISH; - count = CountSupportZones(); - for (int i = 0; i < count; i++) - { - // - XCSupportZone *iZone = supportZones[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Resistance ... - int FilterResistanceZones( - XCResistanceZone *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasResistanceZones(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BEARISH; - count = CountResistanceZones(); - for (int i = 0; i < count; i++) - { - // - XCResistanceZone *iZone = resistanceZones[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Supply ... - int FilterSupplyZones( - XCSupplyZone *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasSupplyZones(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BEARISH; - count = CountSupplyZones(); - for (int i = 0; i < count; i++) - { - // - XCSupplyZone *iZone = supplyZones[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Demand ... - int FilterDemandZones( - XCDemandZone *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasDemandZones(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BULLISH; - count = CountDemandZones(); - for (int i = 0; i < count; i++) - { - // - XCDemandZone *iZone = demandZones[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // OrderBlock ... - int FilterOrderBlocks( - XCOrderBlock *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasOrderBlocks(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - count = CountOrderBlocks(); - for (int i = 0; i < count; i++) - { - // - XCOrderBlock *iZone = orderBlocks[i]; - passedDir = iZone.GetDirection(); - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Bullish OrderBlock ... - int FilterBullishOrderBlocks( - XCOrderBlock *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasBullishOrderBlocks(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BULLISH; - count = CountBullishOrderBlocks(); - for (int i = 0; i < count; i++) - { - // - XCOrderBlock *iZone = bullishOrderBlocks[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Bearish OrderBlock ... - int FilterBearishOrderBlocks( - XCOrderBlock *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasBearishOrderBlocks(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BEARISH; - count = CountBearishOrderBlocks(); - for (int i = 0; i < count; i++) - { - // - XCOrderBlock *iZone = bearishOrderBlocks[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // FairValueGap ... - int FilterFairValueGaps( - XCFVG *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasFairValueGaps(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - count = CountFairValueGaps(); - for (int i = 0; i < count; i++) - { - // - XCFVG *iZone = fairValueGaps[i]; - passedDir = iZone.GetDirection(); - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Bullish FairValueGap ... - int FilterBullishFairValueGaps( - XCFVG *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasBullishFairValueGaps(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BULLISH; - count = CountBullishFairValueGaps(); - for (int i = 0; i < count; i++) - { - // - XCFVG *iZone = bullishFairValueGaps[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Bearish FairValueGap ... - int FilterBearishFairValueGaps( - XCFVG *&dest[], - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int result = 0; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - Clean(dest); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasBearishFairValueGaps(); - if (!has) - { - return result; - } - - // - XOHCL passedBar; - ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; - passedDir = X_DIRECTION_BEARISH; - count = CountBearishFairValueGaps(); - for (int i = 0; i < count; i++) - { - // - XCFVG *iZone = bearishFairValueGaps[i]; - - // - // Check Started State ... - if (startState == XZONE_STATE_PASSED || - startState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isStarted = iZone.IsStarted( - passedDir, - passedBar, - isBodyOut, - forPeriod // - ); - - // - bool isPassed = - startState == XZONE_STATE_FAILED - ? !isStarted - : !forceStartedBodyOut - ? isStarted - : isStarted && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Activation State ... - if (activeState == XZONE_STATE_PASSED || - activeState == XZONE_STATE_FAILED) - { - // - bool isBodyIn = false; - bool isActivated = iZone.IsActivated( - passedDir, - passedBar, - isBodyIn, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - activeState == XZONE_STATE_FAILED - ? !isActivated - : !forceActivatedBodyIn - ? isActivated - : isActivated && - isBodyIn; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Break State ... - if (breakState == XZONE_STATE_PASSED || - breakState == XZONE_STATE_FAILED) - { - // - bool isBodyOut = false; - bool isBreaked = iZone.IsBreaked( - passedDir, - passedBar, - isBodyOut, - forceStartedBodyOut, - forPeriod // - ); - - // - bool isPassed = - breakState == XZONE_STATE_FAILED - ? !isBreaked - : !forceBreakedBodyOut - ? isBreaked - : isBreaked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Work State ... - if (workState == XZONE_STATE_PASSED || - workState == XZONE_STATE_FAILED) - { - // - bool ignoreActivation = activeState != XZONE_STATE_PASSED; - - // - bool isBodyOut = false; - bool isWorked = iZone.IsWorked( - passedDir, - passedBar, - isBodyOut, - ignoreActivation, - forceStartedBodyOut, - forceActivatedBodyIn, - forPeriod // - ); - - // - bool isPassed = - workState == XZONE_STATE_FAILED - ? !isWorked - : !forceWorkedBodyOut - ? isWorked - : isWorked && - isBodyOut; - - // - passedBar.Clean(); - if (!isPassed) - { - continue; - } - } - - // - // Check Filtered Zone Doesn't Exists ... - has = FindIndex( - idx, - iZone, - dest // - ); - if (has) - { - // - passedBar.Clean(); - continue; - } - - // - Add( - iZone, - dest // - ); - - // - // End For ... - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - void Filter( - XPOIState &dest, - ENUM_TIMEFRAMES forPeriod = NULL, - // - // Start ... - ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, - bool forceStartedBodyOut = false, - // - // Activation ... - ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, - bool forceActivatedBodyIn = false, - // - // Breaktion ... - ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, - bool forceBreakedBodyOut = false, - // - // Works ... - ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, - bool forceWorkedBodyOut = false // - ) - { - // - int count = 0; - bool has = false; - - // - dest.Clean(); - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - has = IsValid() && - HasChild(); - if (!has) - { - return; - } - - // - dest = this; - - // - // Support Zones ... - FilterSupportZones( - dest.supportZones, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Resistance Zones ... - FilterResistanceZones( - dest.resistanceZones, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Supply Zones ... - FilterSupplyZones( - dest.supplyZones, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Demand Zones ... - FilterDemandZones( - dest.demandZones, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // OrderBlocks ... - FilterOrderBlocks( - dest.orderBlocks, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Bullish OrderBlocks ... - FilterBullishOrderBlocks( - dest.bullishOrderBlocks, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Bearish OrderBlocks ... - FilterBearishOrderBlocks( - dest.bearishOrderBlocks, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // FairValueGaps ... - FilterFairValueGaps( - dest.fairValueGaps, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Bullish FairValueGaps ... - FilterBullishFairValueGaps( - dest.bullishFairValueGaps, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - // Bearish FairValueGaps ... - FilterBearishFairValueGaps( - dest.bearishFairValueGaps, - forPeriod, - startState, - forceStartedBodyOut, - activeState, - forceActivatedBodyIn, - breakState, - forceBreakedBodyOut, - workState, - forceWorkedBodyOut // - ); - - // - } - - // -}; - -// -// Extensions Functions ... -// - -/** - * Get Oldest Index ... - * - * @param source: XSignalBox instance Reference Collection ... - * - * @return ( int ) - */ -int GetOldest( - XSignalBox &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XSignalBox selected; - for (int i = 0; i < count; i++) - { - // - XSignalBox iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.fvg.from > iBox.fvg.from - : selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.fvg.from > iBox.ob.from - : !selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.ob.from > iBox.fvg.from - : !selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.ob.from > iBox.ob.from - : false; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Youngest Index ... - * - * @param source: XSignalBox instance Reference Collection ... - * - * @return ( int ) - */ -int GetYoungest( - XSignalBox &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XSignalBox selected; - for (int i = 0; i < count; i++) - { - // - XSignalBox iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.fvg.from < iBox.fvg.from - : selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.fvg.from < iBox.ob.from - : !selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.ob.from < iBox.fvg.from - : !selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.ob.from < iBox.ob.from - : false; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Highest Index ... - * - * @param source: XSignalBox instance Reference Collection ... - * - * @return ( int ) - */ -int GetHighest( - XSignalBox &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XSignalBox selected; - for (int i = 0; i < count; i++) - { - // - XSignalBox iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.fvg.upper < iBox.fvg.upper - : selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.fvg.upper < iBox.ob.upper - : !selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.ob.upper < iBox.fvg.upper - : !selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.ob.upper < iBox.ob.upper - : false; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Get Lowest Index ... - * - * @param source: XSignalBox instance Reference Collection ... - * - * @return ( int ) - */ -int GetLowest( - XSignalBox &source[] // -) -{ - // - int result = -1; - - // - int count = ArraySize(source); - if (!IsValidSize(count)) - { - return result; - } - - // - XSignalBox selected; - for (int i = 0; i < count; i++) - { - // - XSignalBox iBox = source[i]; - - // - bool canSet = - !selected.IsValid() - ? true - : selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.fvg.lower > iBox.fvg.lower - : selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.fvg.lower > iBox.ob.lower - : !selected.fvg.IsValid() && - iBox.fvg.IsValid() - ? selected.ob.lower > iBox.fvg.lower - : !selected.fvg.IsValid() && - !iBox.fvg.IsValid() - ? selected.ob.lower > iBox.ob.lower - : false; - if (canSet) - { - // - result = i; - selected = iBox; - } - } - - // - selected.Clean(); - - // - return result; -} - -/** - * Find Index of a Signal Box on another ... - * - * @param index: int, index of exists ... - * @param item: XSignal Box ... - * @param items: XSignal Box Collection ... - * - * @return ( bool ) - */ -bool FindIndex( - int &index, - XSignalBox &item, - XSignalBox &items[] // -) -{ - // - bool result = false; - - // - index = -1; - int count = ArraySize(items); - - // - result = item.IsValid() && - HasChild(items); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - bool isSame = item.ob - .IsSameAs(items[i].ob); - if (isSame) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; -} - -/** - * Find Index of a Signal Box on another ... - * - * @param index: int, index of exists ... - * @param item: XSignal Box ... - * @param items: XSignal Box Collection ... - * - * @return ( bool ) - */ -bool FindIndex( - int &index, - XBoxZone &item, - XSignalBox &items[] // -) -{ - // - bool result = false; - - // - index = -1; - int count = ArraySize(items); - - // - result = item.IsValid() && - HasChild(items); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - bool isSame = item.IsSameAs(items[i].ob); - if (isSame) - { - // - index = i; - break; - } - - // - isSame = item.IsSameAs(items[i].fvg); - if (isSame) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; -} - -/** - * Add a Signal Box in a Collection if not Exists ... - * - * @param item: XSignal Box ... - * @param items: XSignal Box Collection ... - * - * @return ( bool ) - */ -bool AddIfNotExists( - XSignalBox &item, - XSignalBox &items[] // -) -{ - // - bool result = false; - - // - result = item.IsValid(); - if (!result) - { - return result; - } - - // - int idx = -1; - result = !FindIndex( - idx, - item, - items // - ); - if (!result) - { - return result; - } - - // - AddRef( - item, - items // - ); - - // - return result; -} - -// -// XPOI State Event Parsers ... - -// -// Swings ... - -// -bool HasNewSwing(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewSwingLow(events) || - HasNewSwingHigh(events); -} - -// -bool HasNewSwingLow(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_SWING_LOW_DETECTED, - events // - ); -} - -// -bool HasNewSwingHigh(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_SWING_HIGH_DETECTED, - events // - ); -} - -// -// Momentums ... - -// -bool HasNewMomentum(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishMomentum(events) || - HasNewBearishMomentum(events); -} - -// -bool HasNewBullishMomentum(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_MOMENTUM_BAR_DETECTED, - events // - ); -} - -// -bool HasNewBearishMomentum(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_MOMENTUM_BAR_DETECTED, - events // - ); -} - -// -// Rejections ... - -// -bool HasNewRejection(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishRejection(events) || - HasNewBearishRejection(events); -} - -// -bool HasNewBullishRejection(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_REJECTION_BAR_DETECTED, - events // - ); -} - -// -bool HasNewBearishRejection(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_REJECTION_BAR_DETECTED, - events // - ); -} - -// -// Support / Resistance Zones ... - -// -bool HasNewSupportZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_SUPPORT_ZONE_DETECTED, - events // - ); -} - -// -bool HasNewResistanceZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_RESISTANCE_ZONE_DETECTED, - events // - ); -} - -// -// Supply / Demand Zones ... - -// -bool HasNewSupplyZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_SUPPLY_ZONE_DETECTED, - events // - ); -} - -// -bool HasNewDemandZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_DEMAND_ZONE_DETECTED, - events // - ); -} - -// -// Fair Value Gaps ... - -// -bool HasNewFairValueGap(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishFairValueGap(events) || - HasNewBearishFairValueGap(events); -} - -// -bool HasNewBullishFairValueGap(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_FVG_DETECTED, - events // - ); -} - -// -bool HasNewBearishFairValueGap(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_FVG_DETECTED, - events // - ); -} - -// -// Order Blocks ... - -// -bool HasNewOrderBlock(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishOrderBlock(events) || - HasNewBearishOrderBlock(events); -} - -// -bool HasNewBullishOrderBlock(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_ORDERBLOCK_DETECTED, - events // - ); -} - -// -bool HasNewBearishOrderBlock(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_ORDERBLOCK_DETECTED, - events // - ); -} - -// -// Spikes ... - -// -bool HasNewSpike(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishSpike(events) || - HasNewBearishSpike(events); -} - -// -bool HasNewBullishSpike(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_SPIKE_DETECTED, - events // - ); -} - -// -bool HasNewBearishSpike(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_SPIKE_DETECTED, - events // - ); -} - -// -// Sharps ... - -// -bool HasNewSharp(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishSharp(events) || - HasNewBearishSharp(events); -} - -// -bool HasNewBullishSharp(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_SHARP_DETECTED, - events // - ); -} - -// -bool HasNewBearishSharp(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_SHARP_DETECTED, - events // - ); -} - -// -// Pullbacks ... - -// -bool HasNewPullback(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishPullback(events) || - HasNewBearishPullback(events); -} - -// -bool HasNewBullishPullback(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_PULLBACK_DETECTED, - events // - ); -} - -// -bool HasNewBearishPullback(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_PULLBACK_DETECTED, - events // - ); -} - -// -// Consolidation Zones ... - -// -bool HasNewConsolidationZone(ENUM_XPOI_EVENTS &events[]) -{ - return HasNewBullishConsolidationZone(events) || - HasNewBearishConsolidationZone(events); -} - -// -bool HasNewBullishConsolidationZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BULLISH_CONSOLIDATION_ZONE_DETECTED, - events // - ); -} - -// -bool HasNewBearishConsolidationZone(ENUM_XPOI_EVENTS &events[]) -{ - return Contains( - X_BEARISH_CONSOLIDATION_ZONE_DETECTED, - events // - ); -} diff --git a/Documents/BKP/x-saherelm.x121.xcatb.v1.mq5 b/Documents/BKP/x-saherelm.x121.xcatb.v1.mq5 deleted file mode 100644 index 70f72ec3..00000000 --- a/Documents/BKP/x-saherelm.x121.xcatb.v1.mq5 +++ /dev/null @@ -1,5499 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: X121 XCATB -// Description: Integrates All Requirements inside -// this indicator for analyse Markets to -// Detect Trigger Blocks ... -// -// - HK Bars; -// - ATR Band; -// - Signal Bars; -// - Parabolic Sar; -// - HK Signal Bars; -// - Peaks and Vales; -// - Peaks and Vales Goldens; -// - Trending Average Prices; -// -// - ATR; -// - RSI; -// - ADX; -// - DELTA; -// - VOLUME; -// -// 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 X121 XCATB Indicator" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -// Definitions ... - -// -#define ShortName "X121 XCATB" - -// -// Imports ... -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Market"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// Select Trending Cycle ... -// this Cycle Used for All Calculations ... -input ENUM_X_MARKET_CYCLES appliedCycle = X_MARKET_CYCLE_HIND; // Applied Cycle - -// -// Presentation ... -input group "Presentation"; -input bool showBars = true; // Show Bars -input bool showKI = false; // Show KI -input bool showPV = false; // Show PV -input bool showPVGolden = false; // Show PV Golden -input bool showSar = false; // Show Sar -input bool showTrend = false; // Show Trend -input bool showATRBand = false; // Show ATR Band -input bool showSignalBars = false; // Show Signal Bars -input bool showHKSignalBars = false; // Show Hiken Ashi Signal Bars - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -// Non Inputs ... -double sarStep = 0.02; // Step -double sarMax = 0.2; // Maximum -double rsiOBLevel = 70.0; // RSI OB Level -double rsiOSLevel = 30.0; // RSI OS Level -double adxThreshold = 25.0; // ADX Threshold -int kiLength = 144; // KI Length -int sarArrowCode = 159; // Parabolic Sar Arrow Code -int peakArrowCode = 159; // Peaks Arrow Code -int valeArrowCode = 159; // Vales Arrow Code -double atrMultiplier = 1.5; // ATR Band Multiplier -bool showShortCycle = false; // Show Short Cycle Range -bool showMediumCycle = false; // Show Medium Cycle Range -bool showLongCycle = false; // Show Long Cycle Range -bool showHindCycle = false; // Show Hind Cycle Range -ENUM_MA_METHOD trendMode = MODE_SMA; // Trend Mode -ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method -ENUM_X_PRICE atrUpperPriceType = X_PRICE_HIGH; // ATR Upper Zone Applied To -ENUM_X_PRICE atrLowerPriceType = X_PRICE_LOW; // ATR Lower Zone Applied To -ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // RSI Applied To -ENUM_APPLIED_PRICE trendAppliedTo = PRICE_MEDIAN; // Trend Applied To -ENUM_X_MA_METHOD atrSignalMethod = X_MA_MODE_EMA; // ATR Signalling Method -ENUM_X_MA_METHOD barsSignalMethod = X_MA_MODE_EMA; // Bars Signalling Method -ENUM_X_MA_METHOD deltaSignalMethod = X_MA_MODE_EMA; // Delta Signalling Method -ENUM_X_MA_METHOD hkSignalBarMethod = X_MA_MODE_EMA; // Hiken Ashi Signal Method -ENUM_X_MA_METHOD volumeSignalMethod = X_MA_MODE_EMA; // Volume Signalling Method - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -// Plot: 18 -// Color: 4 -// Bar: 8 -// Data Buffer: 29 -#property indicator_buffers 50 -#property indicator_plots 19 - -// -// Plot Buffers ... - -// -// SAR ... - -// -#define sarBufferIndex 0 -#define sarBufferPlotIndex 0 -double sarBuffer[]; - -// -#define sarColorBufferIndex 1 -double sarColorBuffer[]; - -// -#property indicator_label1 "SAR" -#property indicator_type1 DRAW_COLOR_ARROW -#property indicator_color1 CLR_NONE, clrLime, clrRed, clrGray -#property indicator_width1 2 - -// -// PEAKS ... - -// -#define peakBufferIndex 2 -#define peakBufferPlotIndex 1 -double peakBuffer[]; - -// -#property indicator_label2 "PEAK" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 1 - -// -// VALES ... - -// -#define valeBufferIndex 3 -#define valeBufferPlotIndex 2 -double valeBuffer[]; - -// -#property indicator_label3 "VALE" -#property indicator_type3 DRAW_ARROW -#property indicator_color3 clrAqua -#property indicator_width3 1 - -// -// PEAKS Golden ... - -// -#define peakGoldenBufferIndex 4 -#define peakGoldenBufferPlotIndex 3 -double peakGoldenBuffer[]; - -// -#property indicator_label4 "PEAK Golden" -#property indicator_type4 DRAW_LINE -#property indicator_color4 clrMagenta -#property indicator_style4 STYLE_DOT -#property indicator_width4 1 - -// -// VALE Golden ... - -// -#define valeGoldenBufferIndex 5 -#define valeGoldenBufferPlotIndex 4 -double valeGoldenBuffer[]; - -// -#property indicator_label5 "VALES Golden" -#property indicator_type5 DRAW_LINE -#property indicator_color5 clrAqua -#property indicator_style5 STYLE_DOT -#property indicator_width5 1 - -// -// ATR ... - -// -// Upper ... - -// -#define atrUpperBufferIndex 6 -#define atrUpperBufferPlotIndex 5 -double atrUpperBuffer[]; - -// -#property indicator_label6 "XATRU" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrYellow -#property indicator_style6 STYLE_SOLID -#property indicator_width6 1 - -// -// Lower ... - -// -#define atrLowerBufferIndex 7 -#define atrLowerBufferPlotIndex 6 -double atrLowerBuffer[]; - -// -#property indicator_label7 "XATRL" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrYellow -#property indicator_style7 STYLE_SOLID -#property indicator_width7 1 - -// -// TREND ... - -// -#define trendBufferIndex 8 -#define trendBufferPlotIndex 7 -double trendBuffer[]; - -// -#define trendColorBufferIndex 9 -double trendColorBuffer[]; - -// -#property indicator_label8 "Trend" -#property indicator_type8 DRAW_COLOR_LINE -#property indicator_color8 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_style8 STYLE_SOLID -#property indicator_width8 2 - -// -// Signal Bar ... - -// -#define sBarOpenBufferIndex 10 -double sBarOpenBuffer[]; - -// -#define sBarHighBufferIndex 11 -double sBarHighBuffer[]; - -// -#define sBarLowBufferIndex 12 -double sBarLowBuffer[]; - -// -#define sBarCloseBufferIndex 13 -double sBarCloseBuffer[]; - -// -#define sBarColorBufferIndex 14 -double sBarColorBuffer[]; - -// -#define sBarBufferPlotIndex 8 -#property indicator_label9 "XSGB Open;XSGB High;XSGB Low;XSGB Close" -#property indicator_type9 DRAW_COLOR_CANDLES -#property indicator_color9 CLR_NONE, clrLime, clrRed - -// -// XHK SIGNAL ... - -// -#define hkSBarOpenBufferIndex 15 -double hkSBarOpenBuffer[]; - -// -#define hkSBarHighBufferIndex 16 -double hkSBarHighBuffer[]; - -// -#define hkSBarLowBufferIndex 17 -double hkSBarLowBuffer[]; - -// -#define hkSBarCloseBufferIndex 18 -double hkSBarCloseBuffer[]; - -// -#define hkSBarColorBufferIndex 19 -double hkSBarColorBuffer[]; - -// -#define hkSBarBufferPlotIndex 9 -#property indicator_label10 "XHKSGB Open;XHKSGB High;XHKSGB Low;XHKSGB Close" -#property indicator_type10 DRAW_COLOR_CANDLES -#property indicator_color10 CLR_NONE, clrAqua, clrMagenta - -// -// CYCLES Range ... - -// -// SHORT ... - -// -#define sHHBufferIndex 20 -#define sHHBufferPlotIndex 10 -double sHHBuffer[]; - -// -#property indicator_label11 "SH" -#property indicator_type11 DRAW_LINE -#property indicator_color11 clrGray -#property indicator_style11 STYLE_DOT -#property indicator_width11 1 - -// -#define sLLBufferIndex 21 -#define sLLBufferPlotIndex 11 -double sLLBuffer[]; - -// -#property indicator_label12 "SL" -#property indicator_type12 DRAW_LINE -#property indicator_color12 clrGray -#property indicator_style12 STYLE_DOT -#property indicator_width12 1 - -// -// MEDIUM ... - -// -#define mHHBufferIndex 22 -#define mHHBufferPlotIndex 12 -double mHHBuffer[]; - -// -#property indicator_label13 "MH" -#property indicator_type13 DRAW_LINE -#property indicator_color13 clrIndigo -#property indicator_style13 STYLE_DOT -#property indicator_width13 1 - -// -#define mLLBufferIndex 23 -#define mLLBufferPlotIndex 13 -double mLLBuffer[]; - -// -#property indicator_label14 "ML" -#property indicator_type14 DRAW_LINE -#property indicator_color14 clrIndigo -#property indicator_style14 STYLE_DOT -#property indicator_width14 1 - -// -// LONG ... - -// -#define lHHBufferIndex 24 -#define lHHBufferPlotIndex 14 -double lHHBuffer[]; - -// -#property indicator_label15 "LH" -#property indicator_type15 DRAW_LINE -#property indicator_color15 clrGoldenrod -#property indicator_style15 STYLE_DOT -#property indicator_width15 1 - -// -#define lLLBufferIndex 25 -#define lLLBufferPlotIndex 15 -double lLLBuffer[]; - -// -#property indicator_label16 "LL" -#property indicator_type16 DRAW_LINE -#property indicator_color16 clrGoldenrod -#property indicator_style16 STYLE_DOT -#property indicator_width16 1 - -// -// HIND ... - -// -#define hHHBufferIndex 26 -#define hHHBufferPlotIndex 16 -double hHHBuffer[]; - -// -#property indicator_label17 "HH" -#property indicator_type17 DRAW_LINE -#property indicator_color17 clrBrown -#property indicator_style17 STYLE_DOT -#property indicator_width17 1 - -// -#define hLLBufferIndex 27 -#define hLLBufferPlotIndex 17 -double hLLBuffer[]; - -// -#property indicator_label18 "HL" -#property indicator_type18 DRAW_LINE -#property indicator_color18 clrBrown -#property indicator_style18 STYLE_DOT -#property indicator_width18 1 - -// -// KI ... - -// -#define kiBufferIndex 28 -#define kiBufferPlotIndex 18 -double kiBuffer[]; - -// -#define kiColorBufferIndex 29 -double kiColorBuffer[]; - -// -#property indicator_label19 "KI" -#property indicator_type19 DRAW_COLOR_LINE -#property indicator_color19 CLR_NONE, clrGreen, clrRed, clrGray -#property indicator_style19 STYLE_DASHDOTDOT -#property indicator_width19 2 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 29 - -// -// SAR ... - -// -#define sarStateBufferIndex mLastBufferIndex + 1 -double sarStateBuffer[]; - -// -// TREND State ... - -// -#define trendStateBufferIndex mLastBufferIndex + 2 -double trendStateBuffer[]; - -// -// RSI ... - -// -#define rsiBufferIndex mLastBufferIndex + 3 -double rsiBuffer[]; - -// -// ADX ... - -// -#define adxBufferIndex mLastBufferIndex + 4 -double adxBuffer[]; - -// -#define adxpBufferIndex mLastBufferIndex + 5 -double adxpBuffer[]; - -// -#define adxnBufferIndex mLastBufferIndex + 6 -double adxnBuffer[]; - -// -// DELTA ... - -// -#define deltaBufferIndex mLastBufferIndex + 7 -double deltaBuffer[]; - -// -#define deltaSignalBufferIndex mLastBufferIndex + 8 -double deltaSignalBuffer[]; - -// -// VOLUMES ... - -// -#define bullishVolumeBufferIndex mLastBufferIndex + 9 -double bullishVolumeBuffer[]; - -// -#define bearishVolumeBufferIndex mLastBufferIndex + 10 -double bearishVolumeBuffer[]; - -// -#define bullishVolumeSignalBufferIndex mLastBufferIndex + 11 -double bullishVolumeSignalBuffer[]; - -// -#define bearishVolumeSignalBufferIndex mLastBufferIndex + 12 -double bearishVolumeSignalBuffer[]; - -// -// ATR ... - -// -#define atrBufferIndex mLastBufferIndex + 13 -double atrBuffer[]; - -// -#define atrUpperRawBufferIndex mLastBufferIndex + 14 -double atrUpperRawBuffer[]; - -// -#define atrLowerRawBufferIndex mLastBufferIndex + 15 -double atrLowerRawBuffer[]; - -// -// HK ... - -// -#define openHKBufferIndex mLastBufferIndex + 16 -double openHKBuffer[]; - -// -#define highHKBufferIndex mLastBufferIndex + 17 -double highHKBuffer[]; - -// -#define lowHKBufferIndex mLastBufferIndex + 18 -double lowHKBuffer[]; - -// -#define closeHKBufferIndex mLastBufferIndex + 19 -double closeHKBuffer[]; - -// -// KI ... - -// -#define kiStateBufferIndex mLastBufferIndex + 20 -double kiStateBuffer[]; - -// -// Variables, Properties and etc ... - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -// Bars Color Variables ... -color _upColor = clrLime; -color _downColor = clrRed; -color _lineColor = clrLime; -color _bullishColor = clrLime; -color _bearishColor = clrRed; - -// -// XMarketCycle sc; -int mSCLength = 0; -ENUM_TIMEFRAMES mSCPeriod = NULL; - -// -// XMarketCycle mc; -int mMCLength = 0; -ENUM_TIMEFRAMES mMCPeriod = NULL; - -// -// XMarketCycle lc; -int mLCLength = 0; -ENUM_TIMEFRAMES mLCPeriod = NULL; - -// -// XMarketCycle hc; -int mHCLength = 0; -ENUM_TIMEFRAMES mHCPeriod = NULL; - -// -// Applied Cycle ... -int mAppliedLength; -ENUM_TIMEFRAMES mAppliedPeriod = NULL; - -// -// Handlers ... -int atrHandler = INVALID_HANDLE; -int sarHandler = INVALID_HANDLE; -int rsiHandler = INVALID_HANDLE; -int adxHandler = INVALID_HANDLE; -int trendHandler = INVALID_HANDLE; - -// -CArrayObj mObjects; -XCPOIDrawer *mDrawer; -XCBarAnalyser *mBarAnalyser; - -// -// Conditions Variables ... - -// -// Temparory ... -int mCount = 0; -XSignal mSignal; -bool mHas = false; -XBoxZone mSignalBox; -ENUM_X_DIRECTION mDir; -bool mHasSignal = false; -bool mIsBullish = false; -bool mIsBearish = false; -XDirectionShift mDirShift; -string mArrowNamePrefix = NULL; - -// -// Signals ... - -// -bool mDrawSignals = false; -bool mDrawSignalBoxes = false; -bool mDrawSignalArrows = true; -bool mDrawSignalBoxAtLines = false; - -// -int _bullishArrowCode = 225; -int _bearishArrowCode = 226; - -// -color _bullishArrowColor = clrLime; -color _bearishArrowColor = clrRed; - -// -XPOIStyle mBullishSignalBoxStyle; -XPOIStyle mBearishSignalBoxStyle; - -// -ENUM_ARROW_ANCHOR mBullishAnchor = ANCHOR_TOP; -ENUM_ARROW_ANCHOR mBearishAnchor = ANCHOR_BOTTOM; - -// -// POI(s) ... - -// -// Liquidities ... -bool mDrawLiquidities = false; -bool mDetectLiquidities = true; -XBoxZone mBullishLiquidities[]; -XBoxZone mBearishLiquidities[]; -XPOIStyle mBullishLiquidityStyle; -XPOIStyle mBearishLiquidityStyle; - -// -// Range Breakes ... -bool mDrawRangeBreakes = false; -bool mDetectRangeBreakes = true; -XBoxZone mBullishRangeBreakes[]; -XBoxZone mBearishRangeBreakes[]; -XPOIStyle mBullishRangeBreakStyle; -XPOIStyle mBearishRangeBreakStyle; - -// -// Counters ... - -// -int mSameSBCount = 0; -int mSameBullishSBCount = 0; -int mSameBearishSBCount = 0; - -// -int mSameKICount = 0; -int mSameBullishKICount = 0; -int mSameBearishKICount = 0; - -// -int mSameHKSCount = 0; -int mSameBullishHKSCount = 0; -int mSameBearishHKSCount = 0; - -// -int mSameSarCount = 0; -int mSameBullishSarCount = 0; -int mSameBearishSarCount = 0; - -// -int mSameTrendCount = 0; -int mSameBullishTrendCount = 0; -int mSameBearishTrendCount = 0; - -// -int mSamePeakCount = 0; -int mSameValeCount = 0; -int mSamePeakGoldenCount = 0; -int mSameValeGoldenCount = 0; - -// -double mSamePeakGoldenMin = 0; -double mSamePeakGoldenMax = 0; -double mSameValeGoldenMin = 0; -double mSameValeGoldenMax = 0; - -// -// Direction Shift ... - -// -XDirectionShift mBullishKIChanges[]; -XDirectionShift mBearishKIChanges[]; - -// -XDirectionShift mBullishSBChanges[]; -XDirectionShift mBearishSBChanges[]; - -// -XDirectionShift mBullishHKSChanges[]; -XDirectionShift mBearishHKSChanges[]; - -// -XDirectionShift mBullishSarChanges[]; -XDirectionShift mBearishSarChanges[]; - -// -XDirectionShift mBullishTrendChanges[]; -XDirectionShift mBearishTrendChanges[]; - -// -// Liquidities ... - -// -bool isLiquidity = false; -bool isBullishLiquidity = false; -bool isBearishLiquidity = false; - -// -// Trigger Bars Conditions ... - -// -bool isTriggerBarCond1 = false; -bool isTriggerBarCond1Bullish = false; -bool isTriggerBarCond1Bearish = false; - -// -bool isTriggerBarCond2 = false; -bool isTriggerBarCond2Bullish = false; -bool isTriggerBarCond2Bearish = false; - -// -bool isTriggerBarCond3 = false; -bool isTriggerBarCond3Bullish = false; -bool isTriggerBarCond3Bearish = false; - -// -bool isTriggerBarCond4 = false; -bool isTriggerBarCond4Bullish = false; -bool isTriggerBarCond4Bearish = false; - -// -bool isTriggerBarCond5 = false; -bool isTriggerBarCond5Bullish = false; -bool isTriggerBarCond5Bearish = false; - -// -bool isTriggerBarCond6 = false; -bool isTriggerBarCond6Bullish = false; -bool isTriggerBarCond6Bearish = false; - -// -bool isTriggerBarCond7 = false; -bool isTriggerBarCond7Bullish = false; -bool isTriggerBarCond7Bearish = false; - -// -// Summarizing Trigger Bar ... -bool isTriggerBar = false; -bool isTriggerBarBullish = false; -bool isTriggerBarBearish = false; - -// -// XPV ... - -// -bool isSamePeak = false; -bool isSamePeakP = false; - -// -bool isSameVale = false; -bool isSameValeP = false; - -// -bool isPeakOverLast = false; -bool isPeakUnderLast = false; - -// -bool isValeOverLast = false; -bool isValeUnderLast = false; - -// -bool isSamePeakOverLast = false; -bool isSamePeakUnderLast = false; - -// -bool isSameValeOverLast = false; -bool isSameValeUnderLast = false; - -// -bool isSamePeakGolden = false; -bool isSamePeakGoldenP = false; - -// -bool isSameValeGolden = false; -bool isSameValeGoldenP = false; - -// -bool isPeakGoldenOverLast = false; -bool isPeakGoldenUnderLast = false; - -// -bool isValeGoldenOverLast = false; -bool isValeGoldenUnderLast = false; - -// -bool isSamePeakGoldenOverLast = false; -bool isSamePeakGoldenUnderLast = false; - -// -bool isSameValeGoldenOverLast = false; -bool isSameValeGoldenUnderLast = false; - -// -// XSAR ... - -// -bool isSarBullish = false; -bool isSarBullishP = false; - -// -bool isSarBearish = false; -bool isSarBearishP = false; - -// -bool isSarSwitchedToBullish = false; -bool isSarSwitchedToBearish = false; - -// -bool isBullishSarBreakedLast = false; -bool isBearishSarBreakedLast = false; - -// -// XSB ... - -// -double mSBMax = 0; -double mSBMin = 0; - -// -double mSBPMax = 0; -double mSBPMin = 0; - -// -bool isSBBullish = false; -bool isSBBullishP = false; - -// -bool isSBBearish = false; -bool isSBBearishP = false; - -// -bool isSBSwitchedToBullish = false; -bool isSBSwitchedToBearish = false; - -// -bool isBullishSBBreakedLast = false; -bool isBearishSBBreakedLast = false; - -// -// XHKS ... - -// -double mHKSMax = 0; -double mHKSMin = 0; - -// -double mHKSPMax = 0; -double mHKSPMin = 0; - -// -bool isHKSBullish = false; -bool isHKSBullishP = false; - -// -bool isHKSBearish = false; -bool isHKSBearishP = false; - -// -bool isHKSSwitchedToBullish = false; -bool isHKSSwitchedToBearish = false; - -// -bool isBullishHKSBreakedLast = false; -bool isBearishHKSBreakedLast = false; - -// -// XKI ... - -// -bool isKIBullish = false; -bool isKIBullishP = false; - -// -bool isKIBearish = false; -bool isKIBearishP = false; - -// -bool isSameKI = false; -bool isSameBullishKI = false; -bool isSameBearishKI = false; - -// -bool isKISwitchedToBullish = false; -bool isKISwitchedToBearish = false; - -// -bool isBullishKIBreakedLast = false; -bool isBearishKIBreakedLast = false; - -// -// XTREND ... - -// -bool isTrendBullish = false; -bool isTrendBullishP = false; - -// -bool isTrendBearish = false; -bool isTrendBearishP = false; - -// -bool isTrendSwitchedToBullish = false; -bool isTrendSwitchedToBearish = false; - -// -bool isBullishTrendBreakedLast = false; -bool isBearishTrendBreakedLast = false; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - ReadBarStyle(); - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - has = InitCycles(); - if (!has) - { - return INIT_FAILED; - } - - // - // 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 ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - has = InitRequirements(); - if (!has) - { - return INIT_FAILED; - } - - // - if (showBars) - { - ShowBars(); - } - else - { - HideBars(); - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Initial Requirements ... - mDrawer = new XCPOIDrawer(); - mBarAnalyser = new XCBarAnalyser(); - - // - // Preparing Styles ... - - // - // Signals ... - - // - // Bullish ... - mBullishSignalBoxStyle.width = 1; - mBullishSignalBoxStyle.clr = clrAqua; - mBullishSignalBoxStyle.style = STYLE_DOT; - - // - // Bearish ... - mBearishSignalBoxStyle.width = 1; - mBearishSignalBoxStyle.style = STYLE_DOT; - mBearishSignalBoxStyle.clr = clrMagenta; - - // - // Liquidities ... - - // - // Bullish ... - mBullishLiquidityStyle.width = 1; - mBullishLiquidityStyle.clr = clrLime; - - // - // Bearish ... - mBearishLiquidityStyle.width = 1; - mBearishLiquidityStyle.clr = clrRed; - - // - // Range Breakes ... - - // - // Bullish ... - mBullishRangeBreakStyle.width = 1; - mBullishRangeBreakStyle.clr = clrAqua; - - // - // Bearish ... - mBearishRangeBreakStyle.width = 1; - mBearishRangeBreakStyle.clr = clrMagenta; - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -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 - - // - ShowBars(); - - // - // De Initial Requirements ... - mObjects.Clear(); - - // - delete mDrawer; - ZeroMemory(mDrawer); - - delete mBarAnalyser; - ZeroMemory(mBarAnalyser); - - // - // De Initialize all Handlers and etc ... - IndicatorRelease(atrHandler); - IndicatorRelease(sarHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(trendHandler); - - // - mSignal.Clean(); - mDirShift.Clean(); - mSignalBox.Clean(); - - // - Clean(mBullishKIChanges); - Clean(mBearishKIChanges); - Clean(mBullishSBChanges); - Clean(mBearishSBChanges); - Clean(mBullishHKSChanges); - Clean(mBearishHKSChanges); - Clean(mBullishSarChanges); - Clean(mBearishSarChanges); - Clean(mBullishTrendChanges); - Clean(mBearishTrendChanges); - - // - Clean(mBullishLiquidities); - Clean(mBearishLiquidities); - Clean(mBullishRangeBreakes); - Clean(mBearishRangeBreakes); - - // - mBullishSignalBoxStyle.Clean(); - mBearishSignalBoxStyle.Clean(); - - // - mBullishLiquidityStyle.Clean(); - mBearishLiquidityStyle.Clean(); - mBullishRangeBreakStyle.Clean(); - mBearishRangeBreakStyle.Clean(); - - // -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - 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); - - // - // Validate Calculated Bars ... - - // - // ATR ... - int atrCalculatedBars = BarsCalculated(atrHandler); - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - // RSI ... - int rsiCalculatedBars = BarsCalculated(rsiHandler); - - // - // ADX ... - int adxCalculatedBars = BarsCalculated(adxHandler); - - // - // TREND ... - int trendCalculatedBars = BarsCalculated(trendHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // ATR ... - atrCalculatedBars >= maxLength && - // - // SAR ... - sarCalculatedBars >= maxLength && - // - // RSI ... - rsiCalculatedBars >= maxLength && - // - // ADX ... - adxCalculatedBars >= maxLength && - // - // TREND ... - trendCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // ATR ... - int copiedAtrs = CopyBuffer(atrHandler, MAIN_LINE, 0, limit, atrBuffer); - - // - // SAR ... - int copiedSars = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // RSI ... - int copiedRSIs = CopyBuffer(rsiHandler, MAIN_LINE, 0, limit, rsiBuffer); - - // - // ADX ... - int copiedADXs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); - - // - // ADX Plus ... - int copiedADXPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxpBuffer); - - // - // ADX Negative ... - int copiedADXNs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxnBuffer); - - // - // TREND ... - int copiedTrends = CopyBuffer(trendHandler, MAIN_LINE, 0, limit, trendBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // ATR ... - copiedAtrs >= limit && - // - // SAR ... - copiedSars >= limit && - // - // RSI ... - copiedRSIs >= limit && - // - // TREND ... - copiedTrends >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - if (prev_calculated == 0) - { - // - string message = "History Started ..."; - Print(message); - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - if (prev_calculated == 0) - { - // - string message = "History Finished ..."; - Print(message); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - sarMax > 0 && - sarStep > 0 && - rsiOBLevel > 0 && - rsiOSLevel > 0 && - adxThreshold > 0 && - sarMax > sarStep && - atrMultiplier > 0 && - // - IsValid(appliedCycle) && - // - IsValid(atrUpperPriceType) && - IsValid(atrLowerPriceType) && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(mSCLength, mMCLength); - result = MathMax(result, mLCLength); - result = MathMax(result, mHCLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSar); - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - // PEAK / VALE ... - - // - ENUM_DRAW_TYPE pvDrawType = showPV ? DRAW_ARROW : DRAW_NONE; - - // - // PEAK ... - - // - ArraySetAsSeries(peakBuffer, true); - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ArraySetAsSeries(valeBuffer, true); - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // PV GOLDEN ... - - // - ENUM_DRAW_TYPE pvGoldenDrawType = showPVGolden ? DRAW_LINE : DRAW_NONE; - - // - // PEAK Golden ... - - // - ArraySetAsSeries(peakGoldenBuffer, true); - SetIndexBuffer(peakGoldenBufferIndex, peakGoldenBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakGoldenBufferPlotIndex, PLOT_SHOW_DATA, showPVGolden); - PlotIndexSetInteger(peakGoldenBufferPlotIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); - - // - PlotIndexSetDouble(peakGoldenBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // VALE Golden ... - - // - ArraySetAsSeries(valeGoldenBuffer, true); - SetIndexBuffer(valeGoldenBufferIndex, valeGoldenBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeGoldenBufferPlotIndex, PLOT_SHOW_DATA, showPVGolden); - PlotIndexSetInteger(valeGoldenBufferPlotIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); - - // - PlotIndexSetDouble(valeGoldenBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // ATR Band ... - - // - // UPPER ... - ENUM_DRAW_TYPE atrUpperDrawType = showATRBand ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(atrUpperBuffer, true); - SetIndexBuffer(atrUpperBufferIndex, atrUpperBuffer, INDICATOR_DATA); - - // - PlotIndexSetDouble(atrUpperBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(atrUpperBufferPlotIndex, PLOT_SHOW_DATA, showATRBand); - PlotIndexSetInteger(atrUpperBufferPlotIndex, PLOT_DRAW_TYPE, atrUpperDrawType); - - // - // LOWER ... - ENUM_DRAW_TYPE atrLowerDrawType = showATRBand ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(atrLowerBuffer, true); - SetIndexBuffer(atrLowerBufferIndex, atrLowerBuffer, INDICATOR_DATA); - - // - PlotIndexSetDouble(atrLowerBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(atrLowerBufferPlotIndex, PLOT_SHOW_DATA, showATRBand); - PlotIndexSetInteger(atrLowerBufferPlotIndex, PLOT_DRAW_TYPE, atrLowerDrawType); - - // - // TREND ... - - // - ArraySetAsSeries(trendBuffer, true); - SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrend); - PlotIndexSetDouble(trendBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(trendColorBuffer, true); - SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(trendStateBuffer, true); - SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); - - // - // SIGNAL Bar ... - - // - // Signal Bars Color ... - ArraySetAsSeries(sBarColorBuffer, true); - SetIndexBuffer(sBarColorBufferIndex, sBarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(sBarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sBarBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(sBarOpenBuffer, true); - SetIndexBuffer(sBarOpenBufferIndex, sBarOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(sBarHighBuffer, true); - SetIndexBuffer(sBarHighBufferIndex, sBarHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(sBarLowBuffer, true); - SetIndexBuffer(sBarLowBufferIndex, sBarLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(sBarCloseBuffer, true); - SetIndexBuffer(sBarCloseBufferIndex, sBarCloseBuffer, INDICATOR_DATA); - - // - // XHK SIGNAL Bar ... - - // - // HK Bars Color ... - ArraySetAsSeries(hkSBarColorBuffer, true); - SetIndexBuffer(hkSBarColorBufferIndex, hkSBarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(hkSBarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(hkSBarBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(hkSBarOpenBuffer, true); - SetIndexBuffer(hkSBarOpenBufferIndex, hkSBarOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(hkSBarHighBuffer, true); - SetIndexBuffer(hkSBarHighBufferIndex, hkSBarHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(hkSBarLowBuffer, true); - SetIndexBuffer(hkSBarLowBufferIndex, hkSBarLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(hkSBarCloseBuffer, true); - SetIndexBuffer(hkSBarCloseBufferIndex, hkSBarCloseBuffer, INDICATOR_DATA); - - // - // CYCLES ... - - // - // SHORT ... - - // - ENUM_DRAW_TYPE sDrawType = showShortCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(sHHBuffer, true); - SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_SHOW_DATA, showShortCycle); - PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_DRAW_TYPE, sDrawType); - PlotIndexSetDouble(sHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(sLLBuffer, true); - SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_SHOW_DATA, showShortCycle); - PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_DRAW_TYPE, sDrawType); - PlotIndexSetDouble(sLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // MEDIUM ... - - // - ENUM_DRAW_TYPE mDrawType = showMediumCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(mHHBuffer, true); - SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_SHOW_DATA, showMediumCycle); - PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_DRAW_TYPE, mDrawType); - PlotIndexSetDouble(mHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(mLLBuffer, true); - SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_SHOW_DATA, showMediumCycle); - PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_DRAW_TYPE, mDrawType); - PlotIndexSetDouble(mLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LONG ... - - // - ENUM_DRAW_TYPE lDrawType = showLongCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(lHHBuffer, true); - SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_SHOW_DATA, showLongCycle); - PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_DRAW_TYPE, lDrawType); - PlotIndexSetDouble(lHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(lLLBuffer, true); - SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_SHOW_DATA, showLongCycle); - PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_DRAW_TYPE, lDrawType); - PlotIndexSetDouble(lLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // HIND ... - - // - ENUM_DRAW_TYPE hDrawType = showHindCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(hHHBuffer, true); - SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_SHOW_DATA, showHindCycle); - PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_DRAW_TYPE, hDrawType); - PlotIndexSetDouble(hHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(hLLBuffer, true); - SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_SHOW_DATA, showHindCycle); - PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_DRAW_TYPE, hDrawType); - PlotIndexSetDouble(hLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // KI ... - - // - ArraySetAsSeries(kiBuffer, true); - SetIndexBuffer(kiBufferIndex, kiBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(kiBufferPlotIndex, PLOT_SHOW_DATA, showKI); - PlotIndexSetDouble(kiBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(kiColorBuffer, true); - SetIndexBuffer(kiColorBufferIndex, kiColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Data Buffers ... - - // - // RSI ... - ArraySetAsSeries(rsiBuffer, true); - SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); - - // - // ADX ... - - // - ArraySetAsSeries(adxBuffer, true); - SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxpBuffer, true); - SetIndexBuffer(adxpBufferIndex, adxpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxnBuffer, true); - SetIndexBuffer(adxnBufferIndex, adxnBuffer, INDICATOR_CALCULATIONS); - - // - // DELTA ... - - // - ArraySetAsSeries(deltaBuffer, true); - SetIndexBuffer(deltaBufferIndex, deltaBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(deltaSignalBuffer, true); - SetIndexBuffer(deltaSignalBufferIndex, deltaSignalBuffer, INDICATOR_CALCULATIONS); - - // - // VOLUME ... - - // - ArraySetAsSeries(bullishVolumeBuffer, true); - SetIndexBuffer(bullishVolumeBufferIndex, bullishVolumeBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bearishVolumeBuffer, true); - SetIndexBuffer(bearishVolumeBufferIndex, bearishVolumeBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bullishVolumeSignalBuffer, true); - SetIndexBuffer(bullishVolumeSignalBufferIndex, bullishVolumeSignalBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bearishVolumeSignalBuffer, true); - SetIndexBuffer(bearishVolumeSignalBufferIndex, bearishVolumeSignalBuffer, INDICATOR_CALCULATIONS); - - // - // ATR ... - - ArraySetAsSeries(atrBuffer, true); - SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(atrUpperRawBuffer, true); - SetIndexBuffer(atrUpperRawBufferIndex, atrUpperRawBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(atrLowerRawBuffer, true); - SetIndexBuffer(atrLowerRawBufferIndex, atrLowerRawBuffer, INDICATOR_CALCULATIONS); - - // - // XHK ... - - // - ArraySetAsSeries(openHKBuffer, true); - SetIndexBuffer(openHKBufferIndex, openHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(highHKBuffer, true); - SetIndexBuffer(highHKBufferIndex, highHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(lowHKBuffer, true); - SetIndexBuffer(lowHKBufferIndex, lowHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(closeHKBuffer, true); - SetIndexBuffer(closeHKBufferIndex, closeHKBuffer, INDICATOR_CALCULATIONS); - - // - // KI ... - - // - ArraySetAsSeries(kiStateBuffer, true); - SetIndexBuffer(kiStateBufferIndex, kiStateBuffer, INDICATOR_CALCULATIONS); - - // -} - -/** - * Initial Market Cycles ... - * - * @return ( bool ) - */ -bool InitCycles() -{ - // - bool result = false; - - // - int cPeriodSeconds = PeriodSeconds(_Period); - - // - // Find Cycle Period ... - if (scMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mSCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_SHORT, - _Period // - ); - } - else - { - mSCPeriod = scPeriod; - } - - // - if (IsValid(mSCPeriod)) - { - mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (mcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mMCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_MEDIUM, - _Period // - ); - } - else - { - mMCPeriod = mcPeriod; - } - - // - if (IsValid(mMCPeriod)) - { - mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (lcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mLCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_LONG, - _Period // - ); - } - else - { - mLCPeriod = lcPeriod; - } - - // - if (IsValid(mLCPeriod)) - { - mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (hcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mHCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mHCPeriod = hcPeriod; - } - - // - if (IsValid(mHCPeriod)) - { - mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; - } - - // - result = mSCLength > 0 && - mMCLength > mSCLength && - mLCLength > mMCLength && - mHCLength > mLCLength; - - // - // Selecte Applied Cycle ... - if (result) - { - // - switch (appliedCycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - mAppliedLength = mSCLength; - mAppliedPeriod = mSCPeriod; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - mAppliedLength = mMCLength; - mAppliedPeriod = mMCPeriod; - break; - - // - case X_MARKET_CYCLE_LONG: - // - mAppliedLength = mLCLength; - mAppliedPeriod = mLCPeriod; - break; - - // - case X_MARKET_CYCLE_HIND: - // - mAppliedLength = mHCLength; - mAppliedPeriod = mHCPeriod; - break; - } - } - - // - return result; -} - -/** - * Initial all Indicator Requirements ... - * - * @return ( false ) - * - */ -bool InitRequirements() -{ - // - bool result = false; - - // - // Handlers ... - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - result = sarHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // ATR ... - atrHandler = iATR( - _Symbol, - _Period, - mAppliedLength // - ); - result = atrHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // RSI ... - rsiHandler = iRSI( - _Symbol, - _Period, - mAppliedLength, - rsiAppliedTo // - ); - result = rsiHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // ADX ... - adxHandler = iADX( - _Symbol, - _Period, - mAppliedLength // - ); - result = adxHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // TREND ... - trendHandler = iMA( - _Symbol, - _Period, - mAppliedLength, - 0, - trendMode, - trendAppliedTo // - ); - result = trendHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; -} - -/** - * Calculate Custom Buffers ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - if (barsLimit == 0) - { - // - barsLimit = ratesTotal; - firstBarIndex = barsLimit - 1; - } - else - { - firstBarIndex = startCalculationForLastBars; - } - - // - // bool canCalculate = true; - bool canCalculate = - barIndex <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(barIndex); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - kiColorBuffer[barIndex] = hideColorIDX; - sarColorBuffer[barIndex] = hideColorIDX; - trendColorBuffer[barIndex] = hideColorIDX; - - // - atrUpperRawBuffer[barIndex] = emptyValue; - atrLowerRawBuffer[barIndex] = emptyValue; -} - -// -// Value Calculators ... - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Cycle Ranges ... - CalculateCycleRanges( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // KI ... - CalculateKI( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // PV ... - CalculatePV( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // SAR ... - CalculateSAR( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // SBAR ... - CalculateSBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // HKBAR ... - CalculateHKBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // DELTA ... - CalculateDelta( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // TREND ... - CalculateTrend( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // VOLUME ... - CalculateVolume( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // ATR Band ... - CalculateATRBand( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Handling Process ... - - // - // Prepare Market Conditions ... - PrepareMarketConditions( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Detecting POI(s) ... - DetectPOIs( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Validating ... - ValidatePOIs( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Drawing ... - DrawPOIs( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Do Process on Bars ... - DoProcess( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); -} - -/** - * Calculate Cycle Ranges Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateCycleRanges( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // SHORT ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_SHORT, - sHHBuffer, - sLLBuffer // - ); - - // - // MEDIUM ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_MEDIUM, - mHHBuffer, - mLLBuffer // - ); - - // - // LONG ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_LONG, - lHHBuffer, - lLLBuffer // - ); - - // - // HIND ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_HIND, - hHHBuffer, - hLLBuffer // - ); -} - -/** - * Calculate KI Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateKI( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - XOHCL iBar; - bool isInited = iBar.Init( - _Symbol, - _Period, - barIndex // - ); - - // - double iClose = close[barIndex]; - - // - // Calculate KI / Color ... - double lastKI = - isFirstBar - ? emptyValue - : kiBuffer[lastBarIndex]; - double iKI = lastKI; - if (isInited) - { - // - double iLLKI = iBar.FindLowest(kiLength, MODE_LOW); - double iHHKI = iBar.FindHighest(kiLength, MODE_HIGH); - - // - iKI = (iHHKI + iLLKI) / 2; - if (iLLKI == 0 || iHHKI == 0) - { - iKI = lastKI; - } - } - else - { - iKI = lastKI; - } - kiBuffer[barIndex] = iKI; - - // - double iKIState = neuturalState; - double iKIColor = neuturalColorIDX; - if (iClose > iKI) - { - // - iKIState = bullishState; - iKIColor = - !showKI - ? hideColorIDX - : bullishColorIDX; - } - else if (iClose < iKI) - { - // - iKIState = bearishState; - iKIColor = - !showKI - ? hideColorIDX - : bearishColorIDX; - } - kiStateBuffer[barIndex] = iKIState; - kiColorBuffer[barIndex] = iKIColor; - - // - iBar.Clean(); -} - -/** - * Calculate Peaks and Vales Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculatePV( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iSHH = sHHBuffer[barIndex]; - double iSLL = sLLBuffer[barIndex]; - - // - double iMHH = mHHBuffer[barIndex]; - double iMLL = mLLBuffer[barIndex]; - - // - double iLHH = lHHBuffer[barIndex]; - double iLLL = lLLBuffer[barIndex]; - - // - double iHHH = hHHBuffer[barIndex]; - double iHLL = hLLBuffer[barIndex]; - - // - // Calculate VALE ... - bool isVale = iSLL == iMLL && - iMLL == iLLL && - iLLL == iHLL; - double iPVale = - isFirstBar - ? emptyValue - : valeBuffer[lastBarIndex]; - double iVale = - isVale - ? iSLL - : iPVale; - valeBuffer[barIndex] = iVale; - - // - // Calculate PEAK ... - bool isPeak = iSHH == iMHH && - iMHH == iLHH && - iLHH == iHHH; - double iPPeak = - isFirstBar - ? emptyValue - : peakBuffer[lastBarIndex]; - double iPeak = - isPeak - ? iSHH - : iPPeak; - peakBuffer[barIndex] = iPeak; - - // - // GOLDEN ... - - XOHCL iBar; - bool isInited = iBar.Init( - _Symbol, - _Period, - barIndex // - ); - - // - // Calculate PV Gold ... - double lastPeakGold = - isFirstBar - ? emptyValue - : peakGoldenBuffer[lastBarIndex]; - double lastValeGold = - isFirstBar - ? emptyValue - : valeGoldenBuffer[lastBarIndex]; - double iPeakGold = lastPeakGold; - double iValeGold = lastValeGold; - if (isInited) - { - // - iPeakGold = iBar.FindHighest(mHCLength, MODE_CLOSE); - if (iPeakGold == 0) - { - iPeakGold = lastPeakGold; - } - - // - iValeGold = iBar.FindLowest(mHCLength, MODE_CLOSE); - if (iValeGold == 0) - { - iValeGold = lastValeGold; - } - } - else - { - // - iPeakGold = lastPeakGold; - iValeGold = lastValeGold; - } - - // - peakGoldenBuffer[barIndex] = iPeakGold; - valeGoldenBuffer[barIndex] = iValeGold; - - // - iBar.Clean(); -} - -/** - * Calculate PSar Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateSAR( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iLow = low[barIndex]; - double iHigh = low[barIndex]; - double iSar = sarBuffer[barIndex]; - - // - bool isBullish = iSar < iLow; - bool isBearish = iSar > iHigh; - - // - double iSarState = isBullish - ? 1 - : isBearish - ? -1 - : 0; - double iSarColor = iSarState > 0 - ? bullishColorIDX - : iSarState < 0 - ? bearishColorIDX - : neuturalColorIDX; - sarStateBuffer[barIndex] = iSarState; - sarColorBuffer[barIndex] = showSar - ? iSarColor - : hideColorIDX; -} - -/** - * Calculate Signal Bar Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateSBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - open, - sBarOpenBuffer, - barsSignalMethod // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - close, - sBarCloseBuffer, - barsSignalMethod // - ); - - // - double min = MathMin(sBarCloseBuffer[barIndex], sBarOpenBuffer[barIndex]); - double max = MathMin(sBarCloseBuffer[barIndex], sBarOpenBuffer[barIndex]); - - // - sBarLowBuffer[barIndex] = min; - sBarHighBuffer[barIndex] = max; - - // - // Calculate HK Signal Color ... - double iSignalColorValue = - sBarOpenBuffer[barIndex] < sBarCloseBuffer[barIndex] - ? bullishColorIDX - : bearishColorIDX; - sBarColorBuffer[barIndex] = - showSignalBars - ? iSignalColorValue - : hideColorIDX; -} - -/** - * Calculate HK and HK Signal Bars Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateHKBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double lastHKOpen = - isFirstBar - ? emptyValue - : openHKBuffer[lastBarIndex]; - double lastHKClose = - isFirstBar - ? emptyValue - : closeHKBuffer[lastBarIndex]; - - // - double iHKOpenValue = (lastHKOpen + lastHKClose) / 2; - double iHKCloseValue = (open[barIndex] + high[barIndex] + close[barIndex] + low[barIndex]) / 4; - double iHKHighValue = MathMax(high[barIndex], MathMax(iHKOpenValue, iHKCloseValue)); - double iHKLowValue = MathMin(low[barIndex], MathMin(iHKOpenValue, iHKCloseValue)); - - // - // Raw HK Buffers ... - openHKBuffer[barIndex] = iHKOpenValue; - highHKBuffer[barIndex] = iHKHighValue; - lowHKBuffer[barIndex] = iHKLowValue; - closeHKBuffer[barIndex] = iHKCloseValue; - - // - // XHK Signal ... - - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - openHKBuffer, - hkSBarOpenBuffer, - hkSignalBarMethod // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - closeHKBuffer, - hkSBarCloseBuffer, - hkSignalBarMethod // - ); - - // - double min = MathMin(hkSBarCloseBuffer[barIndex], hkSBarOpenBuffer[barIndex]); - double max = MathMin(hkSBarCloseBuffer[barIndex], hkSBarOpenBuffer[barIndex]); - - // - hkSBarLowBuffer[barIndex] = min; - hkSBarHighBuffer[barIndex] = max; - - // - // Calculate HK Signal Color ... - double iHKSignalColorValue = - hkSBarOpenBuffer[barIndex] < hkSBarCloseBuffer[barIndex] - ? bullishColorIDX - : bearishColorIDX; - hkSBarColorBuffer[barIndex] = - showHKSignalBars - ? iHKSignalColorValue - : hideColorIDX; -} - -/** - * Calculate Delta Oscillator Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateDelta( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iClose = close[barIndex]; - double iOpen = open[barIndex]; - double iVolume = (double)iVolume(_Symbol, _Period, barIndex); - - // - bool isBullish = iClose > iOpen; - bool isBearish = iClose < iOpen; - - // - // DELTA ... - double lastDelta = - isFirstBar - ? emptyValue - : deltaBuffer[lastBarIndex]; - double iAppliedVolume = - isBullish - ? iVolume - : -1 * iVolume; - double iDelta = - lastDelta + iAppliedVolume; - deltaBuffer[barIndex] = iDelta; - - // - // Calculate Delta Signal ... - int deltaSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - deltaBuffer, - deltaSignalBuffer, - deltaSignalMethod // - ); -} - -/** - * Calculate Trend Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateTrend( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iLow = low[barIndex]; - double iHigh = high[barIndex]; - double iClose = close[barIndex]; - double iTrend = trendBuffer[barIndex]; - - // - bool isBullish = iTrend < iLow; - bool isBearish = iTrend > iHigh; - - // - double iTrendState = - isBullish - ? 1 - : isBearish - ? -1 - : 0; - double iTrendColor = - iTrendState > 0 - ? bullishColorIDX - : iTrendState < 0 - ? bearishColorIDX - : neuturalColorIDX; - trendStateBuffer[barIndex] = iTrendState; - trendColorBuffer[barIndex] = showTrend - ? iTrendColor - : hideColorIDX; -} - -/** - * Calculate Volume Oscillators Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateVolume( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iClose = close[barIndex]; - double iOpen = open[barIndex]; - double iVolume = (double)iVolume(_Symbol, _Period, barIndex); - - // - bool isBullish = iClose > iOpen; - bool isBearish = iClose < iOpen; - - // - double iBullishVolume = emptyValue; - double iBearishVolume = emptyValue; - if (isBullish) - { - iBullishVolume = iVolume; - } - else if (isBearish) - { - iBearishVolume = iVolume; - } - else - { - // - double iHalfVolume = iVolume / 2; - - // - iBullishVolume = iHalfVolume; - iBearishVolume = iHalfVolume; - } - bullishVolumeBuffer[barIndex] = iBullishVolume; - bearishVolumeBuffer[barIndex] = iBearishVolume; - - // - // Calculate Volume Signals ... - - // - int bullishVolumeSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - bullishVolumeBuffer, - bullishVolumeSignalBuffer, - volumeSignalMethod // - ); - - // - int bearishVolumeSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - bearishVolumeBuffer, - bearishVolumeSignalBuffer, - volumeSignalMethod // - ); -} - -/** - * Calculate ATR Band Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateATRBand( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iATR = atrBuffer[barIndex]; - double iAppliedATR = atrMultiplier * iATR; - double iATRUpperPrice = GetAppliedPrice( - atrUpperPriceType, - open, - high, - low, - close, - barIndex // - ); - double iATRLowerPrice = GetAppliedPrice( - atrLowerPriceType, - open, - high, - low, - close, - barIndex // - ); - double iATRUpper = iATRUpperPrice + iAppliedATR; - double iATRLower = iATRLowerPrice - iAppliedATR; - atrUpperRawBuffer[barIndex] = iATRUpper; - atrLowerRawBuffer[barIndex] = iATRLower; - - // - bool canSignalATR = IsValid(atrSignalMethod); - if (canSignalATR) - { - // - // Upper ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - atrUpperRawBuffer, - atrUpperBuffer, - atrSignalMethod // - ); - - // - // Lower ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - atrLowerRawBuffer, - atrLowerBuffer, - atrSignalMethod // - ); - } - else - { - // - atrUpperBuffer[barIndex] = iATRUpper; - atrLowerBuffer[barIndex] = iATRLower; - } -} - -/** - * Calculate Specified Market Cycle Info ... - * - * @param barIndex: Integer, Bar Index ... - * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... - * @param hhBuffer: Highest High Buffer Reference ... - * @param llBuffer: Lowest Low Buffer Reference ... - */ -void CalculateCycle( - int barIndex, - ENUM_X_MARKET_CYCLES cycle, - double &hhBuffer[], - double &llBuffer[] // -) -{ - // - XOHCL bar; - bool isBarInited = bar.Init( - _Symbol, - _Period, - barIndex - // - ); - if (!isBarInited) - { - return; - } - - // - int mLength = 0; - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - mLength = mSCLength; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - mLength = mMCLength; - break; - - // - case X_MARKET_CYCLE_LONG: - mLength = mLCLength; - break; - - // - case X_MARKET_CYCLE_HIND: - mLength = mHCLength; - break; - } - - // - if (mLength == 0) - { - return; - } - - // - // Find Highest High ... - double hhValue = bar.FindHighest( - mLength, - upperMode // - ); - hhBuffer[barIndex] = hhValue; - - // - // Find Lowest Low ... - double llValue = bar.FindLowest( - mLength, - lowerMode // - ); - llBuffer[barIndex] = llValue; - - // - bar.Clean(); -} - -// -// -// - -/** - * Reading Bar Style and Store it ... - */ -void ReadBarStyle() -{ - // - long chartId = ChartID(); - - // - _upColor = GetChartUpColor(chartId); - _downColor = GetChartDownColor(chartId); - _lineColor = GetChartLineColor(chartId); - _bullishColor = GetChartBullishColor(chartId); - _bearishColor = GetChartBearishColor(chartId); -} - -/** - * Show Bars ... - */ -void ShowBars() -{ - // - long chartId = ChartID(); - - // - SetChartUpColor(_upColor, chartId); - SetChartDownColor(_downColor, chartId); - SetChartLineColor(_lineColor, chartId); - SetChartBullishColor(_bullishColor, chartId); - SetChartBearishColor(_bearishColor, chartId); -} - -/** - * Hide Bars ... - */ -void HideBars() -{ - // - long chartId = ChartID(); - - // - SetChartUpColor(CLR_NONE, chartId); - SetChartDownColor(CLR_NONE, chartId); - SetChartLineColor(CLR_NONE, chartId); - SetChartBullishColor(CLR_NONE, chartId); - SetChartBearishColor(CLR_NONE, chartId); -} - -// -// Process Handlers ... -// - -/** - * Prepare Market Conditions ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void PrepareMarketConditions( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Some Requirements ... - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Recieve Bar ... - XOHCL iBar; - XOHCL iPBar; - mHas = iBar.Init( - _Symbol, - _Period, - barIndex - // - ); - mHas = - mHas && - iBar.GetPreviousBar(iPBar); - if (!mHas) - { - return; - } - - // - int cIndex = barIndex; - int pIndex = barIndex + 1; - int p2Index = barIndex + 2; - int p3Index = barIndex + 3; - - // - // Check Required Bars Passed ... - mHas = p3Index <= maxBarIndex; - if (!mHas) - { - return; - } - - // - // Start Preparing Conditions ... - - // - // Liquidities ... - - // - isLiquidity = - mBarAnalyser - .IsRejected( - iBar, - mDir, - true, - true // - ); - isBullishLiquidity = - isLiquidity && - IsBullish(mDir); - isBearishLiquidity = - isLiquidity && - IsBearish(mDir); - - // - // Trigger Bars Conditions ... - - // - // Cond 1 ... - isTriggerBarCond1 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - true, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond1Bullish = - isTriggerBarCond1 && - IsBullish(mDir); - isTriggerBarCond1Bearish = - isTriggerBarCond1 && - IsBearish(mDir); - if (isTriggerBarCond1) - { - mArrowNamePrefix += "1"; - } - - // - // Cond 2 ... - isTriggerBarCond2 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - true, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond2Bullish = - isTriggerBarCond2 && - IsBullish(mDir); - isTriggerBarCond2Bearish = - isTriggerBarCond2 && - IsBearish(mDir); - if (isTriggerBarCond2) - { - mArrowNamePrefix += ",2"; - } - - // - // Cond 3 ... - isTriggerBarCond3 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - false, // Cond 2 ... - true, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond3Bullish = - isTriggerBarCond3 && - IsBullish(mDir); - isTriggerBarCond3Bearish = - isTriggerBarCond3 && - IsBearish(mDir); - if (isTriggerBarCond3) - { - mArrowNamePrefix += ",3"; - } - - // - // Cond 4 ... - isTriggerBarCond4 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - true, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond4Bullish = - isTriggerBarCond4 && - IsBullish(mDir); - isTriggerBarCond4Bearish = - isTriggerBarCond4 && - IsBearish(mDir); - if (isTriggerBarCond4) - { - mArrowNamePrefix += ",4"; - } - - // - // Cond 5 ... - isTriggerBarCond5 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - true, // Cond 5 ... - false, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond5Bullish = - isTriggerBarCond5 && - IsBullish(mDir); - isTriggerBarCond5Bearish = - isTriggerBarCond5 && - IsBearish(mDir); - if (isTriggerBarCond5) - { - mArrowNamePrefix += ",5"; - } - - // - // Cond 6 ... - isTriggerBarCond6 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - true, // Cond 6 ... - false // Cond 7 ... - ); - isTriggerBarCond6Bullish = - isTriggerBarCond6 && - IsBullish(mDir); - isTriggerBarCond6Bearish = - isTriggerBarCond6 && - IsBearish(mDir); - if (isTriggerBarCond6) - { - mArrowNamePrefix += ",6"; - } - - // - // Cond 7 ... - isTriggerBarCond7 = - mBarAnalyser - .IsValidForTrigger( - iPBar, - mDir, - false, // Cond 1 ... - false, // Cond 2 ... - false, // Cond 3 ... - false, // Cond 4 ... - false, // Cond 5 ... - false, // Cond 6 ... - true // Cond 7 ... - ); - isTriggerBarCond7Bullish = - isTriggerBarCond7 && - IsBullish(mDir); - isTriggerBarCond7Bearish = - isTriggerBarCond7 && - IsBearish(mDir); - if (isTriggerBarCond7) - { - mArrowNamePrefix += ",7"; - } - - // - // Summarizing Trigger Bar ... - - // - isTriggerBar = - isTriggerBarCond1 || - isTriggerBarCond2 || - isTriggerBarCond3 || - isTriggerBarCond4 || - isTriggerBarCond5 || - isTriggerBarCond6 || - isTriggerBarCond7; - - // - isTriggerBarBullish = - isTriggerBarCond1Bullish || - isTriggerBarCond2Bullish || - isTriggerBarCond3Bullish || - isTriggerBarCond4Bullish || - isTriggerBarCond5Bullish || - isTriggerBarCond6Bullish || - isTriggerBarCond7Bullish; - - // - isTriggerBarBearish = - isTriggerBarCond1Bearish || - isTriggerBarCond2Bearish || - isTriggerBarCond3Bearish || - isTriggerBarCond4Bearish || - isTriggerBarCond5Bearish || - isTriggerBarCond6Bearish || - isTriggerBarCond7Bearish; - - // - // Resetting Counters Based on Conditions ... - - // - // XPV ... - - // - if (!isSamePeak) - { - // - mSamePeakCount = 0; - mSamePeakGoldenMin = 0; - mSamePeakGoldenMax = 0; - } - - // - if (!isSameVale) - { - // - mSameValeCount = 0; - mSameValeGoldenMin = 0; - mSameValeGoldenMax = 0; - } - - // - if (!isSamePeakGolden) - { - mSamePeakGoldenCount = 0; - } - - // - if (!isSameValeGolden) - { - mSameValeGoldenCount = 0; - } - - // - // XKI ... - - // - if (!isSameKI) - { - mSameKICount = 0; - } - - // - if (!isSameBullishKI) - { - mSameBullishKICount = 0; - } - - // - if (!isSameBearishKI) - { - mSameBearishKICount = 0; - } - - // - // XSB ... - - // - if (isSBSwitchedToBullish) - { - // - mSameSBCount = 0; - mSameBullishSBCount = 0; - } - - // - if (isSBSwitchedToBearish) - { - // - mSameSBCount = 0; - mSameBearishSBCount = 0; - } - - // - // XSAR ... - - // - if (isSarSwitchedToBullish) - { - // - mSameSarCount = 0; - mSameBullishSarCount = 0; - } - - // - if (isSarSwitchedToBearish) - { - // - mSameSarCount = 0; - mSameBearishSarCount = 0; - } - - // - // XHKS ... - - // - if (isHKSSwitchedToBullish) - { - // - mSameHKSCount = 0; - mSameBullishHKSCount = 0; - } - - // - if (isHKSSwitchedToBearish) - { - // - mSameHKSCount = 0; - mSameBearishHKSCount = 0; - } - - // - // XTREND ... - - // - if (isTrendSwitchedToBullish) - { - // - mSameTrendCount = 0; - mSameBullishTrendCount = 0; - } - - // - if (isTrendSwitchedToBearish) - { - // - mSameTrendCount = 0; - mSameBearishTrendCount = 0; - } - - // - // Preparing Conditions ... - - // - // XPV ... - - // - isSamePeak = peakBuffer[pIndex] == peakBuffer[p2Index]; - isSamePeakP = peakBuffer[p2Index] == peakBuffer[p3Index]; - - // - isSameVale = valeBuffer[pIndex] == valeBuffer[p2Index]; - isSameValeP = valeBuffer[p2Index] == valeBuffer[p3Index]; - - // - isPeakOverLast = peakBuffer[pIndex] > peakBuffer[p2Index]; - isPeakUnderLast = peakBuffer[pIndex] < peakBuffer[p2Index]; - - // - isValeOverLast = valeBuffer[pIndex] > valeBuffer[p2Index]; - isValeUnderLast = valeBuffer[pIndex] < valeBuffer[p2Index]; - - // - isSamePeakOverLast = - isSamePeakP && - isPeakOverLast; - isSamePeakUnderLast = - isSamePeakP && - isPeakUnderLast; - - // - isSameValeOverLast = - isSameValeP && - isValeOverLast; - isSameValeUnderLast = - isSameValeP && - isValeUnderLast; - - // - isSamePeakGolden = peakGoldenBuffer[pIndex] == peakGoldenBuffer[p2Index]; - isSamePeakGoldenP = peakGoldenBuffer[p2Index] == peakGoldenBuffer[p3Index]; - - // - isSameValeGolden = valeGoldenBuffer[pIndex] == valeGoldenBuffer[p2Index]; - isSameValeGoldenP = valeGoldenBuffer[p2Index] == valeGoldenBuffer[p3Index]; - - // - isPeakGoldenOverLast = peakGoldenBuffer[pIndex] > peakGoldenBuffer[p2Index]; - isPeakGoldenUnderLast = peakGoldenBuffer[pIndex] < peakGoldenBuffer[p2Index]; - - // - isValeGoldenOverLast = valeGoldenBuffer[pIndex] > valeGoldenBuffer[p2Index]; - isValeGoldenUnderLast = valeGoldenBuffer[pIndex] < valeGoldenBuffer[p2Index]; - - // - isSamePeakGoldenOverLast = - isSamePeakGoldenP && - isPeakGoldenOverLast; - isSamePeakGoldenUnderLast = - isSamePeakGoldenP && - isPeakGoldenUnderLast; - - // - isSameValeGoldenOverLast = - isSameValeGoldenP && - isValeGoldenOverLast; - isSameValeGoldenUnderLast = - isSameValeGoldenP && - isSameValeGoldenUnderLast; - - // - // XSAR ... - - // - isSarBullish = sarStateBuffer[pIndex] > 0; - isSarBullishP = sarStateBuffer[p2Index] > 0; - - // - isSarBearish = sarStateBuffer[pIndex] < 0; - isSarBearishP = sarStateBuffer[p2Index] < 0; - - // - isSarSwitchedToBullish = - isSarBullish && - !isSarBullishP; - isSarSwitchedToBearish = - isSarBearish && - !isSarBearishP; - - // - // XSB ... - - // - isSBBullish = sBarCloseBuffer[pIndex] > sBarOpenBuffer[pIndex]; - isSBBullishP = sBarCloseBuffer[p2Index] > sBarOpenBuffer[p2Index]; - - // - isSBBearish = sBarCloseBuffer[pIndex] < sBarOpenBuffer[pIndex]; - isSBBearishP = sBarCloseBuffer[p2Index] < sBarOpenBuffer[p2Index]; - - // - isSBSwitchedToBullish = - isSBBullish && - !isSBBullishP; - isSBSwitchedToBearish = - isSBBearish && - !isSBBearishP; - - // - mSBMin = MathMin(sBarCloseBuffer[pIndex], sBarOpenBuffer[pIndex]); - mSBMax = MathMax(sBarCloseBuffer[pIndex], sBarOpenBuffer[pIndex]); - - // - mSBPMin = MathMin(sBarCloseBuffer[p2Index], sBarOpenBuffer[p2Index]); - mSBPMax = MathMax(sBarCloseBuffer[p2Index], sBarOpenBuffer[p2Index]); - - // - // XHKS ... - - // - isHKSBullish = hkSBarCloseBuffer[pIndex] > hkSBarOpenBuffer[pIndex]; - isHKSBullishP = hkSBarCloseBuffer[p2Index] > hkSBarOpenBuffer[p2Index]; - - // - isHKSBearish = hkSBarCloseBuffer[pIndex] < hkSBarOpenBuffer[pIndex]; - isHKSBearishP = hkSBarCloseBuffer[p2Index] < hkSBarOpenBuffer[p2Index]; - - // - isHKSSwitchedToBullish = - isHKSBullish && - !isHKSBullishP; - isHKSSwitchedToBearish = - isHKSBearish && - !isHKSBearishP; - - // - mHKSMin = MathMin(hkSBarCloseBuffer[pIndex], hkSBarOpenBuffer[pIndex]); - mHKSMax = MathMax(hkSBarCloseBuffer[pIndex], hkSBarOpenBuffer[pIndex]); - - // - mHKSPMin = MathMin(hkSBarCloseBuffer[p2Index], hkSBarOpenBuffer[p2Index]); - mHKSPMax = MathMax(hkSBarCloseBuffer[p2Index], hkSBarOpenBuffer[p2Index]); - - // - // XKI ... - - // - isKIBullish = kiStateBuffer[pIndex] > 0; - isKIBullishP = kiStateBuffer[p2Index] > 0; - - // - isKIBearish = kiStateBuffer[pIndex] < 0; - isKIBearishP = kiStateBuffer[p2Index] < 0; - - // - isSameKI = kiBuffer[pIndex] == kiBuffer[p2Index]; - isSameBullishKI = - isSameKI && - isKIBullish; - isSameBearishKI = - isSameKI && - isKIBearish; - - // - isKISwitchedToBullish = - isKIBullish && - !isKIBullishP; - isKISwitchedToBearish = - isKIBearish && - !isKIBearishP; - - // - // XTREND ... - - // - isTrendBullish = trendStateBuffer[pIndex] > 0; - isTrendBullishP = trendStateBuffer[p2Index] > 0; - - // - isTrendBearish = trendStateBuffer[pIndex] < 0; - isTrendBearishP = trendStateBuffer[p2Index] < 0; - - // - isTrendSwitchedToBullish = - isTrendBullish && - !isTrendBullishP; - isTrendSwitchedToBearish = - isTrendBearish && - !isTrendBearishP; - - // - // Detecting Counters and Direction Shifts and it's related Conditions ... - - // - // XPV Counters ... - - // - if (isSamePeak) - { - // - mSamePeakCount++; - mSamePeakGoldenMin = - mSamePeakGoldenMin == 0 - ? peakGoldenBuffer[pIndex] - : MathMin(mSamePeakGoldenMin, peakGoldenBuffer[pIndex]); - mSamePeakGoldenMax = - mSamePeakGoldenMax == 0 - ? peakGoldenBuffer[pIndex] - : MathMax(mSamePeakGoldenMax, peakGoldenBuffer[pIndex]); - } - - // - if (isSameVale) - { - // - mSameValeCount++; - mSameValeGoldenMin = - mSameValeGoldenMin == 0 - ? valeGoldenBuffer[pIndex] - : MathMin(mSameValeGoldenMin, valeGoldenBuffer[pIndex]); - mSameValeGoldenMax = - mSameValeGoldenMax == 0 - ? valeGoldenBuffer[pIndex] - : MathMax(mSameValeGoldenMax, valeGoldenBuffer[pIndex]); - } - - // - if (isSamePeakGolden) - { - mSamePeakGoldenCount++; - } - - // - if (isSameValeGolden) - { - mSameValeGoldenCount++; - } - - // - // XSB Shifts ... - - // - // Detection ... - if (isSBSwitchedToBullish || - isSBSwitchedToBearish) - { - // - mDirShift.at = iPBar.time; - mDirShift.symbol = _Symbol; - mDirShift.period = _Period; - - // - mDirShift.type = "XSBSHFT"; - - // - mDirShift.after = 0; - mDirShift.before = 0; - - // - if (isSBSwitchedToBullish) - { - // - mDirShift.after = mSBMax; - mDirShift.before = mSBPMax; - mDirShift.shiftTo = X_DIRECTION_BULLISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBullishSBChanges // - ); - } - } - - // - if (isSBSwitchedToBearish) - { - // - mDirShift.after = mSBMin; - mDirShift.before = mSBPMin; - mDirShift.shiftTo = X_DIRECTION_BEARISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBearishSBChanges // - ); - } - } - - // - mDirShift.Clean(); - } - - // - // Parsers ... - - // - mHas = isSBBullish && - HasChild(mBearishSBChanges); - if (mHas) - { - isBullishSBBreakedLast = mSBMin > mBearishSBChanges[ArraySize(mBearishSBChanges) - 1].after; - } - - // - mHas = isSBBearish && - HasChild(mBullishSBChanges); - if (mHas) - { - isBearishSBBreakedLast = mSBMax < mBullishSBChanges[ArraySize(mBullishSBChanges) - 1].after; - } - - // - // Counters ... - - // - if (!isSBSwitchedToBullish && - !isSBSwitchedToBearish) - { - // - bool isDBullish = - isSBBullish && - isSBBullishP; - if (isDBullish) - { - mSameBullishSBCount++; - } - - // - bool isDBearish = - isSBBearish && - isSBBearishP; - if (isDBearish) - { - mSameBearishSBCount++; - } - - // - if (isDBullish || - isDBearish) - { - mSameSBCount++; - } - } - - // - // XSAR Shifts ... - - // - // Detection ... - if (isSarSwitchedToBullish || - isSarSwitchedToBearish) - { - // - mDirShift.at = iPBar.time; - mDirShift.symbol = _Symbol; - mDirShift.period = _Period; - - // - mDirShift.type = "XSARSHFT"; - - // - mDirShift.after = sarBuffer[pIndex]; - mDirShift.before = sarBuffer[p2Index]; - - // - if (isSarSwitchedToBullish) - { - // - mDirShift.shiftTo = X_DIRECTION_BULLISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBullishSarChanges // - ); - } - } - - // - if (isSarSwitchedToBearish) - { - // - mDirShift.shiftTo = X_DIRECTION_BEARISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBearishSarChanges // - ); - } - } - - // - mDirShift.Clean(); - } - - // - // Parsers ... - - // - mHas = isSarBullish && - HasChild(mBearishSarChanges); - if (mHas) - { - isBullishSarBreakedLast = sarBuffer[pIndex] > mBearishSarChanges[ArraySize(mBearishSarChanges) - 1].after; - } - - // - mHas = isSarBearish && - HasChild(mBullishSarChanges); - if (mHas) - { - isBearishSarBreakedLast = sarBuffer[pIndex] < mBullishSarChanges[ArraySize(mBullishSarChanges) - 1].after; - } - - // - // Counters ... - - // - if (!isSarSwitchedToBullish && - !isSarSwitchedToBearish) - { - // - bool isDBullish = - isSarBullish && - isSarBullishP; - if (isDBullish) - { - mSameBullishSarCount++; - } - - // - bool isDBearish = - isSarBearish && - isSarBearishP; - if (isDBearish) - { - mSameBearishSarCount++; - } - - // - if (isDBullish || - isDBearish) - { - mSameSarCount++; - } - } - - // - // XHKS Shifts ... - - // - // Detection ... - if (isHKSSwitchedToBullish || - isHKSSwitchedToBearish) - { - // - mDirShift.at = iPBar.time; - mDirShift.symbol = _Symbol; - mDirShift.period = _Period; - - // - mDirShift.type = "XHKSSHFT"; - - // - mDirShift.after = 0; - mDirShift.before = 0; - - // - if (isHKSSwitchedToBullish) - { - // - mDirShift.after = mHKSMax; - mDirShift.before = mHKSPMax; - mDirShift.shiftTo = X_DIRECTION_BULLISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBullishHKSChanges // - ); - } - } - - // - if (isHKSSwitchedToBearish) - { - // - mDirShift.after = mHKSMin; - mDirShift.before = mHKSPMin; - mDirShift.shiftTo = X_DIRECTION_BEARISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBearishHKSChanges // - ); - } - } - - // - mDirShift.Clean(); - } - - // - // Parsers ... - - // - mHas = isHKSBullish && - HasChild(mBearishHKSChanges); - if (mHas) - { - isBullishHKSBreakedLast = mHKSMin > mBearishHKSChanges[ArraySize(mBearishHKSChanges) - 1].after; - } - - // - mHas = isHKSBearish && - HasChild(mBullishHKSChanges); - if (mHas) - { - isBearishHKSBreakedLast = mHKSMax < mBullishHKSChanges[ArraySize(mBullishHKSChanges) - 1].after; - } - - // - // Counters ... - - // - if (!isHKSSwitchedToBullish && - !isHKSSwitchedToBearish) - { - // - bool isDBullish = - isHKSBullish && - isHKSBullishP; - if (isDBullish) - { - mSameBullishHKSCount++; - } - - // - bool isDBearish = - isHKSBearish && - isHKSBearishP; - if (isDBearish) - { - mSameBearishHKSCount++; - } - - // - if (isDBullish || - isDBearish) - { - mSameHKSCount++; - } - } - - // - // XKI Shifts ... - - // - // Detection ... - if (isKISwitchedToBullish || - isKISwitchedToBearish) - { - // - mDirShift.at = iPBar.time; - mDirShift.symbol = _Symbol; - mDirShift.period = _Period; - - // - mDirShift.type = "XKISHFT"; - - // - mDirShift.after = kiBuffer[pIndex]; - mDirShift.before = kiBuffer[p2Index]; - - // - if (isKISwitchedToBullish) - { - // - mDirShift.shiftTo = X_DIRECTION_BULLISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBullishKIChanges // - ); - } - } - - // - if (isKISwitchedToBearish) - { - // - mDirShift.shiftTo = X_DIRECTION_BEARISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBearishKIChanges // - ); - } - } - - // - mDirShift.Clean(); - } - - // - // Parsers ... - - // - mHas = isKIBullish && - HasChild(mBearishKIChanges); - if (mHas) - { - isBullishKIBreakedLast = kiBuffer[pIndex] > mBearishKIChanges[ArraySize(mBearishKIChanges) - 1].after; - } - - // - mHas = isKIBearish && - HasChild(mBullishKIChanges); - if (mHas) - { - isBearishKIBreakedLast = kiBuffer[pIndex] < mBullishKIChanges[ArraySize(mBullishKIChanges) - 1].after; - } - - // - // Counters ... - - // - if (isSameKI) - { - mSameKICount++; - } - - // - if (isSameBullishKI) - { - mSameBullishKICount++; - } - - // - if (isSameBearishKI) - { - mSameBearishKICount++; - } - - // - // XTREND Shifts ... - - // - // Detection ... - if (isTrendSwitchedToBullish || - isTrendSwitchedToBearish) - { - // - mDirShift.at = iPBar.time; - mDirShift.symbol = _Symbol; - mDirShift.period = _Period; - - // - mDirShift.type = "XTRENDSHFT"; - - // - mDirShift.after = trendBuffer[pIndex]; - mDirShift.before = trendBuffer[p2Index]; - - // - if (isTrendSwitchedToBullish) - { - // - mDirShift.shiftTo = X_DIRECTION_BULLISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBullishTrendChanges // - ); - } - } - - // - if (isTrendSwitchedToBearish) - { - // - mDirShift.shiftTo = X_DIRECTION_BEARISH; - - // - if (mDirShift.IsValid()) - { - // - AddIfNotExists( - mDirShift, - mBearishTrendChanges // - ); - } - } - - // - mDirShift.Clean(); - } - - // - // Parsers ... - - // - mHas = isTrendBullish && - HasChild(mBearishTrendChanges); - if (mHas) - { - isBullishTrendBreakedLast = trendBuffer[pIndex] > mBearishTrendChanges[ArraySize(mBearishTrendChanges) - 1].after; - } - - // - mHas = isTrendBearish && - HasChild(mBullishTrendChanges); - if (mHas) - { - isBearishTrendBreakedLast = trendBuffer[pIndex] < mBullishTrendChanges[ArraySize(mBullishTrendChanges) - 1].after; - } - - // - // Counters ... - - // - if (!isTrendSwitchedToBullish && - !isTrendSwitchedToBearish) - { - // - bool isDBullish = - isTrendBullish && - isTrendBullishP; - if (isDBullish) - { - mSameBullishTrendCount++; - } - - // - bool isDBearish = - isTrendBearish && - isTrendBearishP; - if (isDBearish) - { - mSameBearishTrendCount++; - } - - // - if (isDBullish || - isDBearish) - { - mSameTrendCount++; - } - } - - // - // - // - - // - // Cleanup Resources ... - - // - iBar.Clean(); - iPBar.Clean(); - mDirShift.Clean(); -} - -/** - * Detect POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DetectPOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Some Requirements ... - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Recieve Bar ... - XOHCL iBar; - XOHCL iPBar; - mHas = iBar.Init( - _Symbol, - _Period, - barIndex - // - ); - mHas = - mHas && - iBar.GetPreviousBar(iPBar); - if (!mHas) - { - return; - } - - // - // Liquidities ... - if (mDetectLiquidities) - { - // - if (isLiquidity) - { - // - XBoxZone iLiq; - - // - iLiq.type = "XLIQ"; - iLiq.symbol = _Symbol; - iLiq.period = _Period; - - // - if (isBullishLiquidity) - { - // - iLiq.at = iBar.time; - iLiq.lower = iBar.low; - iLiq.to = iBar.NextAt(); - iLiq.from = iBar.BeforeOn(); - iLiq.upper = iBar.GetDown(); - iLiq.dir = X_DIRECTION_BULLISH; - - // - if (iLiq.IsValid()) - { - // - AddIfNotExists( - iLiq, - mBullishLiquidities // - ); - } - } - - // - if (isBearishLiquidity) - { - // - iLiq.at = iBar.time; - iLiq.upper = iBar.high; - iLiq.to = iBar.NextAt(); - iLiq.lower = iBar.GetUp(); - iLiq.from = iBar.BeforeOn(); - iLiq.dir = X_DIRECTION_BEARISH; - - // - if (iLiq.IsValid()) - { - // - AddIfNotExists( - iLiq, - mBearishLiquidities // - ); - } - } - - // - iLiq.Clean(); - } - } - - // - // Range Breakes ... - int mRangeBreakesMinLength = 5; - if (mDetectRangeBreakes) - { - // - XBoxZone iRB; - - // - iRB.type = "XRNGB"; - iRB.at = iPBar.time; - iRB.to = iPBar.time; - iRB.symbol = _Symbol; - iRB.period = _Period; - - // - // Bullish ... - bool isBullishPeakPOI = - (isSamePeakOverLast && - mSamePeakCount >= mRangeBreakesMinLength); - bool isBullishValePOI = - (isSameValeOverLast && - mSameValeCount >= mRangeBreakesMinLength); - mHas = - isBullishPeakPOI || - isBullishValePOI; - if (mHas) - { - // - if (isBullishPeakPOI) - { - // - iRB.lower = mSamePeakGoldenMax; - iRB.upper = peakBuffer[barIndex + 1]; - - // - iRB.from = iPBar.time - (mSamePeakCount * PeriodSeconds(_Period)); - } - - // - if (isBullishValePOI) - { - // - iRB.upper = mSameValeGoldenMin; - iRB.lower = valeBuffer[barIndex + 1]; - - // - iRB.from = iPBar.time - (mSameValeCount * PeriodSeconds(_Period)); - } - - // - iRB.dir = X_DIRECTION_BULLISH; - - // - if (iRB.IsValid()) - { - // - AddIfNotExists( - iRB, - mBullishRangeBreakes // - ); - } - } - - // - // Bearish ... - bool isBearishPeakPOI = - (isSamePeakUnderLast && - mSamePeakCount >= mRangeBreakesMinLength); - bool isBearishValePOI = - (isSameValeUnderLast && - mSameValeCount >= mRangeBreakesMinLength); - mHas = - isBearishPeakPOI || - isBearishValePOI; - if (mHas) - { - // - if (isBearishPeakPOI) - { - // - iRB.lower = mSamePeakGoldenMax; - iRB.upper = peakBuffer[barIndex + 1]; - - // - iRB.from = iPBar.time - (mSamePeakCount * PeriodSeconds(_Period)); - } - - // - if (isBearishValePOI) - { - // - iRB.upper = mSameValeGoldenMin; - iRB.lower = valeBuffer[barIndex + 1]; - - // - iRB.from = iPBar.time - (mSameValeCount * PeriodSeconds(_Period)); - } - - // - iRB.dir = X_DIRECTION_BEARISH; - - // - if (iRB.IsValid()) - { - // - AddIfNotExists( - iRB, - mBearishRangeBreakes // - ); - } - } - - // - iRB.Clean(); - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - iPBar.Clean(); -} - -/** - * Validate Detected POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void ValidatePOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int barsLength = 3; - - // - // Liquidities ... - - // - // Bullish ... - mHas = HasChild(mBullishLiquidities); - if (mHas) - { - // - ValidateBoxes( - mBullishLiquidities, - barIndex, - barsLength // - ); - } - - // - // Bearish ... - mHas = HasChild(mBearishLiquidities); - if (mHas) - { - // - ValidateBoxes( - mBearishLiquidities, - barIndex, - barsLength // - ); - } - - // - // Range Breakes ... - - // - // Bullish ... - mHas = HasChild(mBullishRangeBreakes); - if (mHas) - { - // - ValidateBoxes( - mBullishRangeBreakes, - barIndex, - barsLength // - ); - } - - // - // Bearish ... - mHas = HasChild(mBearishRangeBreakes); - if (mHas) - { - // - ValidateBoxes( - mBearishRangeBreakes, - barIndex, - barsLength // - ); - } - - // -} - -/** - * Draw Detected POI(s) ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DrawPOIs( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - datetime to = GetBarTime( - _Symbol, - _Period, - barIndex // - ); - - // - // Liquidities ... - if (mDrawLiquidities) - { - // - // Bullish ... - mCount = ArraySize(mBullishLiquidities); - mHas = IsValidSize(mCount); - if (mHas) - { - // - for (int i = 0; i < mCount; i++) - { - // - XBoxZone iBox = mBullishLiquidities[i]; - iBox.to = to; - - // - XCBoxObject *iBObj; - mHas = mDrawer.DrawBox( - iBox, - iBObj // - ); - if (mHas) - { - // - if (iBox.IsBullish()) - { - // - mDrawer.ApplyStyle( - iBObj, - mBullishLiquidityStyle // - ); - } - else - { - // - mDrawer.ApplyStyle( - iBObj, - mBearishLiquidityStyle // - ); - } - - // - mObjects.Add(iBObj); - } - - // - iBox.Clean(); - } - } - - // - // Bearish ... - mCount = ArraySize(mBearishLiquidities); - mHas = IsValidSize(mCount); - if (mHas) - { - // - for (int i = 0; i < mCount; i++) - { - // - XBoxZone iBox = mBearishLiquidities[i]; - iBox.to = to; - - // - XCBoxObject *iBObj; - mHas = mDrawer.DrawBox( - iBox, - iBObj // - ); - if (mHas) - { - // - if (iBox.IsBullish()) - { - // - mDrawer.ApplyStyle( - iBObj, - mBullishLiquidityStyle // - ); - } - else - { - // - mDrawer.ApplyStyle( - iBObj, - mBearishLiquidityStyle // - ); - } - - // - mObjects.Add(iBObj); - } - - // - iBox.Clean(); - } - } - } - - // - // Range Breakes ... - if (mDrawRangeBreakes) - { - // - // Bullish ... - mCount = ArraySize(mBullishRangeBreakes); - mHas = IsValidSize(mCount); - if (mHas) - { - // - for (int i = 0; i < mCount; i++) - { - // - XBoxZone iBox = mBullishRangeBreakes[i]; - iBox.to = to; - - // - XCBoxObject *iBObj; - mHas = mDrawer.DrawBox( - iBox, - iBObj // - ); - if (mHas) - { - // - if (iBox.IsBullish()) - { - // - mDrawer.ApplyStyle( - iBObj, - mBullishRangeBreakStyle // - ); - } - else - { - // - mDrawer.ApplyStyle( - iBObj, - mBearishRangeBreakStyle // - ); - } - - // - mObjects.Add(iBObj); - } - - // - iBox.Clean(); - } - } - - // - // Bearish ... - mCount = ArraySize(mBearishRangeBreakes); - mHas = IsValidSize(mCount); - if (mHas) - { - // - for (int i = 0; i < mCount; i++) - { - // - XBoxZone iBox = mBearishRangeBreakes[i]; - iBox.to = to; - - // - XCBoxObject *iBObj; - mHas = mDrawer.DrawBox( - iBox, - iBObj // - ); - if (mHas) - { - // - if (iBox.IsBullish()) - { - // - mDrawer.ApplyStyle( - iBObj, - mBullishRangeBreakStyle // - ); - } - else - { - // - mDrawer.ApplyStyle( - iBObj, - mBearishRangeBreakStyle // - ); - } - - // - mObjects.Add(iBObj); - } - - // - iBox.Clean(); - } - } - } -} - -/** - * Process Custom Analysing Senarios ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void DoProcess( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Here we Can Detect Conditions ... - - // - // Check Some Requirements ... - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Recieve Bar ... - XOHCL iBar; - XOHCL iPBar; - mHas = iBar.Init( - _Symbol, - _Period, - barIndex - // - ); - mHas = - mHas && - iBar.GetPreviousBar(iPBar); - if (!mHas) - { - return; - } - - // - // Trigger Bar's Conditions ... - - // - // Bullish ... - bool isTBBullish = - // - iBar.IsBullish() && - isTriggerBarBullish && - iBar.low > iPBar.low - // - ; - - // - // Bearish ... - bool isTBBearish = - // - iBar.IsBearish() && - isTriggerBarBearish && - iBar.high < iPBar.high - // - ; - - // - // KI Breakes Validation Conditions ... - - // - // Bullish ... - bool isKIBullishBreakes = - // - isKIBullish && - iBar.IsBullish() && - iPBar.IsBreaked( - kiBuffer[barIndex + 1], - X_DIRECTION_BULLISH, - X_FIBO_LEVEL_500, // Fibo Level ... - X_BOUNDARY_PRICE_HIGH_LOW // Boundary Type ... - ) - // - ; - - // - // Bearish ... - bool isKIBearishBreakes = - // - isKIBearish && - iBar.IsBearish() && - iPBar.IsBreaked( - kiBuffer[barIndex + 1], - X_DIRECTION_BEARISH, - X_FIBO_LEVEL_500, // Fibo Level ... - X_BOUNDARY_PRICE_HIGH_LOW // Boundary Type ... - ) - // - ; - - // - // Conditions By ... - // - Rejecting Trend Line; - // - Trend Line is Over HK; - // - SAR Directional; - // - KI Directional; - // - HKS Directional; - - // - bool isTrendsBasedBullish = - // - isKIBullish && - isSarBullish && - isHKSBullish && - // - // TODO: Implement Trend Line is Over HKS MAX ... - // - // Rejectiong Trend Line ... - iPBar.IsBullish() && - iPBar.low < trendBuffer[barIndex + 1] && - iPBar.GetDown() > trendBuffer[barIndex + 1] - // - ; - - // - bool isTrendBasedBearish = - // - isKIBearish && - isSarBearish && - isHKSBearish && - // - // TODO: Implement Trend Line is Under HKS MIN ... - // - // Rejecting Trend Line ... - iPBar.IsBearish() && - iPBar.high > trendBuffer[barIndex + 1] && - iPBar.GetUp() < trendBuffer[barIndex + 1] - // - ; - - // - // Summarization Conditions ... - - // - // Bullish ... - mIsBullish = - // - // false - // isTBBullish && - // isKIBullishBreakes - isTrendsBasedBullish - // - ; - - // - // Bearish ... - mIsBearish = - // - // false - // isTBBearish && - // isKIBearishBreakes - isTrendBasedBearish - // - ; - - // - // Signal Summarize ... - mHasSignal = - mIsBullish || - mIsBearish; - - // - // Handling Signal ... - if (mHasSignal) - { - // - // Creating Signal Box ... - mSignalBox.type = "XSGB"; - mSignalBox.at = iBar.time; - mSignalBox.to = iBar.time; - mSignalBox.symbol = _Symbol; - mSignalBox.period = _Period; - mSignalBox.lower = iPBar.low; - mSignalBox.from = iPBar.time; - mSignalBox.upper = iPBar.high; - mSignalBox.dir = - mIsBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Converting Box to Signal ... - double rrs[] = { - 1, - 1.5, - 2, - 3 // - }; - mHas = ToSignal( - mSignalBox, - mSignal, - rrs, // Risk To Reward Ratios ... - 0 // Additional SL ... - ); - - // - // Draw Signal Box ... - if (mDrawSignalBoxes) - { - // - mHas = mSignalBox.IsValid(); - if (mHas) - { - // - XCBoxObject *iSignalBoxObj; - mHas = mDrawer.DrawBox( - mSignalBox, - iSignalBoxObj, - !mDrawSignalBoxAtLines // - ); - - // - if (mHas) - { - // - // Styling Object ... - if (mSignalBox.IsBullish()) - { - // - mDrawer.ApplyStyle( - iSignalBoxObj, - mBullishSignalBoxStyle // - ); - } - else - { - // - mDrawer.ApplyStyle( - iSignalBoxObj, - mBearishSignalBoxStyle // - ); - } - - // - // Storing Object ... - mObjects.Add(iSignalBoxObj); - } - - // - ZeroMemory(iSignalBoxObj); - } - } - - // - // Draw Signal ... - if (mDrawSignals) - { - // - mHas = mSignal.IsValid(); - if (mHas) - { - // - XCSignalObject *iSignalObj; - mHas = mDrawer.DrawSignal( - mSignal, - iSignalObj, - 3 // - ); - - // - if (mHas) - { - mObjects.Add(iSignalObj); - } - - // - ZeroMemory(iSignalObj); - } - } - - // - // Draw Arrows ... - if (mDrawSignalArrows) - { - // - int arrowWidth = 3; - int arrowCode = - mIsBullish - ? _bullishArrowCode - : _bearishArrowCode; - ENUM_X_PRICE arrowPriceType = - mIsBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - color arrowColor = - mIsBullish - ? _bullishArrowColor - : _bearishArrowColor; - ENUM_ARROW_ANCHOR arrowAnchor = - mIsBullish - ? mBullishAnchor - : mBearishAnchor; - - // - XCBarArrowObject *iSignalArrowObj; - mHas = mDrawer.CreateBarArrow( - iBar, - iSignalArrowObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - mArrowNamePrefix // - ); - if (mHas) - { - mObjects.Add(iSignalArrowObj); - } - - // - ZeroMemory(iSignalArrowObj); - } - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - iPBar.Clean(); - mSignal.Clean(); - mSignalBox.Clean(); - - // - mArrowNamePrefix = NULL; -} - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x121.xki.signaller.class.mq5 b/Documents/BKP/x-saherelm.x121.xki.signaller.class.mq5 deleted file mode 100644 index 0d4dcab7..00000000 --- a/Documents/BKP/x-saherelm.x121.xki.signaller.class.mq5 +++ /dev/null @@ -1,1184 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCX121XKISignaller ... -// Description: X121XKI Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121XKI Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.x121.xki.helper.mq5" -#include "../Classes/x-saherelm.x121.xki.parser.class.mq5" -#include "../Classes/x-saherelm.x121.xki.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.x121.xki.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base X121XKI base Signaller ... -class XCX121XKIBaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - CArrayObj drawnObjects; // Drawing Objects Holder ... - X121XKIInputs kiInputs; // X121XKI Inputs ... - XCX121XKIHelper *kiHelper; // X121XKI Indicator Helper ... - XCX121XKIPOIDrawer *poiDrawer; // X121XKI POI Drawer ... - XCX121XKIPOIDetector *poiDetector; // X121XKI POI Detector ... - XCX121XKIHelperParser *kiParser; // X121XKI Helper Parser ... - - // - // Constructor ... - XCX121XKIBaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - X121XKIInputs &_kiInputs, // X121XKIInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating X121XKI Indicator Helper Class ... - if (_kiInputs.IsValid()) - { - // - kiHelper = new XCX121XKIHelper(); - bool isInited = kiHelper.Init( - _symbol, - _period, - _kiInputs // - ); - if (isInited) - { - kiInputs = _kiInputs; - } - else - { - // - delete kiHelper; - ZeroMemory(kiHelper); - } - } - - // - // Instantiate X121XKI Helper Parser ... - kiParser = new XCX121XKIHelperParser(kiHelper); - - // - poiDrawer = new XCX121XKIPOIDrawer(); - poiDetector = new XCX121XKIPOIDetector(kiHelper, kiParser); - } - - // - // Deconstructor ... - ~XCX121XKIBaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - kiInputs.Clean(); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - delete kiHelper; - ZeroMemory(kiHelper); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = kiInputs.IsValid() && - kiHelper != NULL && - poiDetector != NULL; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// X121XKI Strategy 1 Signaller Class ... -class XCX121XKIStrategy1Signaller : public XCX121XKIBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor ... - XCX121XKIStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - X121XKIInputs &_kiInputs, // X121XKIInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCX121XKIBaseSignaller("X121XKI1", - _symbol, - _period, - _kiInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - } - - // - // Deconstructor ... - ~XCX121XKIStrategy1Signaller() - { - // - Destroy(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Strategy X ... - has = HasSignal( - iBar, - iZone, - iTargets, - iDir // - ); - - // - // Handle Resting Signals ... - has = HasDirection(iDir) && - iZone.IsValid(); - - // - // Prepare Signal ... - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, iDir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Signal ... - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - sl, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - } - - // - // Notify On Signal Event ... - if (has) - { - NotifySignalEventListeners(iSignal); - } - - // - // Cleanup ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - XClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - XClean(guards); - return result; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Requirements ... - XGuard iGuard; - bool has = false; - int samePeaks = 0; - int sameVales = 0; - double iValue = 0; - double points10 = 0; - double points50 = 0; - double points100 = 0; - int samePVValidation = 5; - bool isPeakOverLast = false; - bool isValeUnderLast = false; - - // - for (int i = 0; i < positionsCount; i++) - { - // - points10 = 10 * positions[i].GetPointsValue(); - points50 = 50 * positions[i].GetPointsValue(); - points100 = 100 * positions[i].GetPointsValue(); - - // - // Near to TP Guard ... - has = positions[i].profit > 0; - if (has) - { - } - } - - // - result = ArraySize(guards); - - // - // Cleanup ... - iGuard.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - // Private ... - private: - // - // Props ... - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy X ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - // Configuration Flags ... - - // - // Signaller Flags ... - bool useSignaller1 = true; - bool useSignaller2 = false; - bool useSignaller3 = false; - bool useSignaller4 = false; - bool useSignaller5 = false; - - // - XBoxZone tmpZone; - string provider = NULL; - ENUM_X_DIRECTION tmpDir; - - // - bool signaller1HasSignal = false; - bool signaller2HasSignal = false; - bool signaller3HasSignal = false; - bool signaller4HasSignal = false; - bool signaller5HasSignal = false; - - // - // Validator Flags ... - bool validateByOrderFlow = false; - - // - // Target Flags ... - bool hasPartialCloseOnTp1 = false; - - // - bool doRFOnEntryOnTP1 = false; - - // - // Draw Flags ... - bool draw = true; - - // - // Signal Checking ... - - // - // Signal Detection Flags ... - - // - // Signaller 1 ... - if (useSignaller1) - { - // - signaller1HasSignal = Strategy1HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller1HasSignal) - { - // - provider += "1"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 2 ... - if (useSignaller2) - { - // - signaller2HasSignal = Strategy2HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller2HasSignal) - { - // - provider += "2"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 3 ... - if (useSignaller3) - { - // - signaller3HasSignal = Strategy3HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller3HasSignal) - { - // - provider += "3"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 4 ... - if (useSignaller4) - { - // - signaller4HasSignal = Strategy4HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller4HasSignal) - { - // - provider += "4"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Signaller 5 ... - if (useSignaller5) - { - // - signaller5HasSignal = Strategy5HasSignal( - bar, - tmpZone, - targets, - tmpDir // - ); - - // - if (signaller5HasSignal) - { - // - provider += "5"; - - // - if (!zone.IsValid()) - { - // - dir = tmpDir; - zone = tmpZone; - } - } - - // - tmpZone.Clean(); - tmpDir = X_DIRECTION_NONE; - } - - // - // Summarize Signallers Result ... - result = signaller1HasSignal || - signaller2HasSignal || - signaller3HasSignal || - signaller4HasSignal || - signaller5HasSignal; - - // - // Signal Validating ... - - // - // Targets, Restrictions and Risk Management ... - if (result) - { - // - // Requirements ... - XTarget iTarget; - - // - // Checking Direction of Signal ... - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Provided SL ... - double points = GetPoints(symbol); - double spread = GetSpread(symbol); - double entry = GetEntry(symbol, dir); - - // - // Calculate SL Addition ... - double slAddition = - slAdditionDistance <= 0 - ? 0 - : slAdditionDistance * points; - - // - // Calculate SL Price ... - double sl = - isBullish - ? zone.lower - slAddition - : zone.upper + slAddition; - - // - // Calculate Risk ... - double risk = MathAbs(entry - sl); - - // - // Calculate Reward ... - double reward = defaultSignalR2R * risk; - - // - // Calculate TP1 ... - double tp1 = isBullish - ? entry + risk - : entry - risk; - double tp2 = isBullish - ? entry + (2 * risk) - : entry - (2 * risk); - - // - // Calculate TP ... - double tp = isBullish - ? entry + reward - : entry - reward; - - // - // Check Max Allowed Risk ... - bool hasTooMuchRisk = maxAllowedRiskDistance <= 0 - ? false - : risk >= (maxAllowedRiskDistance * points); - if (hasTooMuchRisk) - { - // - // Clean Signal if Too much Risk ... - zone.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Common Targets ... - - // - // Partial Close on TP 1 ... - if (hasPartialCloseOnTp1) - { - // - iTarget.Clean(); - iTarget.target = tp1; - iTarget.actingDistance = 5; - iTarget.volumeMultiplier = 0.8; - iTarget.doRFOnEntry = doRFOnEntryOnTP1; - - // - AddRef(iTarget, targets); - } - - // - // Custom Signaller Targets ... - - // - // Restrictions Handling ... - if (risk > 0 && HasRestrictions()) - { - // - // Reset Restricitons if necessary ... - ResetRestrictions(); - - // - // Handle Custom Restrictions Senario ... - } - - // - // Ignore Targets ... - if (ignoreTargets) - { - XClean(targets); - } - - // - // Summarize Result ... - result = zone.IsValid() && - HasDirection(dir); - - // - // Cleanup ... - iTarget.Clean(); - } - - // - // Draws ... - if (result && draw) - { - // - // Other Drawing Materials ... - XPOIDrawConfig drawConfig; - drawConfig.Default(); - - // - poiDrawer.DrawZone(zone, drawConfig); - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - - // - // Cleanup ... - tmpZone.Clean(); - - // - return result; - } - - // - // Custom Signal Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * Pattern‑based reversal: - * - Detects Pin Bar or Signal Key Bar. - * - Confirms with POI detector. - * - Good for reversals at support/resistance. - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = poiDetector.IsBullishPOI(bar.Index()); - bool isBearish = poiDetector.IsBearishPOI(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - result = ToBox(bar, zone, dir, X_BAR_PATTERN_SIGNALKEY); - result = - result && - zone.IsValid() && - HasDirection(dir); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 2 ... - * - * Trend‑following: - * - Requires KI Fast + KI Slow alignment. - * - Confirms with MA crossover. - * - RSI filter to avoid false signals. - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = kiParser.IsBullishMomentumTrend(bar.Index()); - bool isBearish = kiParser.IsBearishMomentumTrend(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - result = ToBox(bar, zone, dir, X_BAR_PATTERN_MOMENTUM); - result = - result && - zone.IsValid() && - HasDirection(dir); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * Breakout: - * - Detects price breaking KI bands with ATR confirmation. - * - Confirms with Momentum Bar pattern. - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = poiDetector.IsBullishBreakoutPOI(bar.Index()); - bool isBearish = poiDetector.IsBearishBreakoutPOI(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - result = ToBox(bar, zone, dir, X_BAR_PATTERN_TRUE_GAPED); - result = - result && - zone.IsValid() && - HasDirection(dir); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * Exhaustion: - * - Strong trend + RSI extreme + volatility low. - * - Confirms with Piercing/Dark Cloud Cover candlestick. - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = poiDetector.IsBullishTrendExhaustedPOI(bar.Index()); - bool isBearish = poiDetector.IsBearishTrendExhaustedPOI(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - result = ToBox(bar, zone, dir, X_BAR_PATTERN_PIERCING); - result = - result && - zone.IsValid() && - HasDirection(dir); - - // - return result; - } - - - /** - * Check Bar Has Signal Based on Strategy 5 ... - * - * Continuation: - * - Requires strong trend confirmation (KI fast/slow + MA crossover + RSI filter). - * - Confirms with continuation candlestick patterns (Flag or Rising pattern). - * - Ensures zone validity for entry. - * - * @return ( bool ) - */ - bool Strategy5HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir // - ) - { - // - bool result = false; - - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = kiParser.IsTrendStrongBullish(bar.Index()); - bool isBearish = kiParser.IsTrendStrongBearish(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - // Confirm Direction by Candlestick Continuation Patterns ... - isBullish = - isBullish && - poiDetector.IsBullishContinuationPOI(bar.Index()); - isBearish = - isBearish && - poiDetector.IsBearishContinuationPOI(bar.Index()); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - result = ToBox(bar, zone, dir, X_BAR_PATTERN_PIERCING); - result = - result && - zone.IsValid() && - HasDirection(dir); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.backtester.ea copy.mq5 b/Documents/BKP/x-saherelm.xfima.backtester.ea copy.mq5 deleted file mode 100644 index a2ff4f56..00000000 --- a/Documents/BKP/x-saherelm.xfima.backtester.ea copy.mq5 +++ /dev/null @@ -1,1899 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XTest MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XBackTester -// Description: a Backtest Tools Strategy Tester -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -//////////////////////////////////////////////////////x -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XBackTester" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -#define ShortName "XBackTester" - -// -// Imports ... -#include "../Classes/x-saherelm.x-backtester.expert.class.mq5" -#include "../XFIMAEA/Classes/x-saherelm.xfima.signaller.class.mq5" - -// -// Definitions ... - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Alert ... -// Here we Provider All Requirements for -// Configuring Alert Provider ... -input group "Alert"; -input bool eaEnableAlerts = true; // Enable Alerts -input bool eaLogAlerts = true; // Log Alerts -input bool eaMailAlerts = false; // Mail Alerts -input bool eaPushAlerts = false; // Push Alerts -input bool eaTerminalAlerts = false; // Terminal Alerts - -// -// Configurations ... -input group "Configuration"; -input bool eaProcessAllTicks = false; // Process All Ticks -input double eaSignallerR2R = 2.0; // Risk To Reward Ratio -input double eaSignallerVolume = 0.01; // Default Volume -input double eaSignallerRiskInPoint = 50; // Default Risk In Point - -// -// Indicator Inputs ... -// -input group "Calculation"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// PV ... -input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method - -// -// Others ... -input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Middle Zone Level -input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level -input double sarStep = 0.02; // SAR Step -input double sarMax = 0.2; // SAR Maximum -input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To -input int maFastLength = 7; // Fast MA Length -input int maSlowLength = 20; // Slow MA Length -input int maBandLength = 7; // MA Band Length -input int zigzagDepth = 12; // ZigZag Depth -input int zigzagDeviation = 5; // ZigZag Deviation -input int zigzagBackStep = 3; // ZigZag Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - -// -input group "Bar Timer"; -input int barTimeFontSize = 10; // Font Size -input string barTimeFont = "Arial"; // Font -input color barTimeColor = clrYellow; // Text Color -input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show PV -input bool showHK = true; // Show HK -input bool showSAR = true; // Show Sar -input bool showMAFast = true; // Show MA Fast -input bool showMASlow = true; // Show MA Slow -input bool showMABand = true; // Show MA Band -input bool showBarTime = true; // Show Bar Time -input bool showZigZag = true; // Show ZigZag -input bool showFiboZone = true; // Show Fibo Zone - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -input int sarArrowCode = 159; // Parabolic Sar Arrow Code -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Define Local Variables ... - -// -// Requirements ... -string eaLogTag; // EA Log Prefix ... -XCBackTesterEA *eaExpert; // EA Expert ... - -// -// Registered Signallers ... -XCXFIMAStrategy1Signaller *fima1Signaller; // XFIMA1 Signaller ... - -// -XFIMAMarketStructure marketStructure; // POI Analysis Result ... -XFIMAPatternDetectorConfig detectorConfig; // POI Detector Config ... -XFIMAMarketStructureDrawerConfig marketStructureDrawerConfig; // POI Drawer Config ... - -// -// Drawer and eaDraws ... -CArrayObj eaDraws; // Drawn Objects ... -CArrayObj *marketStructureObjects; // Market Structure Objects ... - -// -XBarTracker eaBarTracker; // EA Bar Traker ... - -// -// Registered Handlers ... -int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ... - -// -bool eaIsNewBar; // Check New Bar ... - -// -// Define Indicators Here ... - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Preparing Tags ... - string eaTag = - (IsValid(eaLogSuffix) - ? eaLogSuffix + "_" - : "") + - ShortName; - - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Timer ... - if (!InitTimer()) - { - return INIT_FAILED; - } - - // - // Configure EA Expert Class ... - eaExpert = new XCBackTesterEA(); - - // - // Symbol / Period ... - eaExpert.symbol = _Symbol; - eaExpert.period = _Period; - - // - // Common ... - eaExpert.eaMagicNumber = eaMagicNumber; - eaExpert.eaSlippage = eaSlippage; - eaExpert.eaLogSuffix = eaTag; - - // - // Alert ... - eaExpert.eaEnableAlerts = eaEnableAlerts; - eaExpert.eaLogAlerts = eaLogAlerts; - eaExpert.eaMailAlerts = eaMailAlerts; - eaExpert.eaPushAlerts = eaPushAlerts; - eaExpert.eaTerminalAlerts = eaTerminalAlerts; - - // - // Attach Event Handlers ... - eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged); - eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered); - eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged); - eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); - eaExpert.AddOnModifyPositionEventHandler(OnPositionModified); - eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged); - eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged); - eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed); - eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed); - - // - // Configure Other Requirements ... - eaExpert.allowedTPSLStep = 10; - eaExpert.minAllowedRiskInPoint = 20; - eaExpert.volume = eaSignallerVolume; - eaExpert.riskToRewardRatio = eaSignallerR2R; - eaExpert.riskInPoint = eaSignallerRiskInPoint; - - // - // Try to Initialize eaExpert ... - bool isInited = eaExpert.HandleOnInit(); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Here Instantiate Signaller Class ... - - // - // Preparing Indicator Inputs ... - XFIMAInputs fimaInputs; - - // - // This is Default Configuration ... - fimaInputs.Default(); - fimaInputs.Hide(); - - // - // Here we Attach Inputs to Indicator ... - fimaInputs.scMethod = scMethod; - fimaInputs.scPeriod = scPeriod; - fimaInputs.mcMethod = mcMethod; - fimaInputs.mcPeriod = mcPeriod; - fimaInputs.lcMethod = lcMethod; - fimaInputs.lcPeriod = lcPeriod; - fimaInputs.hcMethod = hcMethod; - fimaInputs.hcPeriod = hcPeriod; - fimaInputs.upperMode = upperMode; - fimaInputs.lowerMode = lowerMode; - fimaInputs.fiboUpperZoneLevel = fiboUpperZoneLevel; - fimaInputs.fiboMiddleZoneLevel = fiboMiddleZoneLevel; - fimaInputs.fiboLowerZoneLevel = fiboLowerZoneLevel; - fimaInputs.sarStep = sarStep; - fimaInputs.sarMax = sarMax; - fimaInputs.maMethod = maMethod; - fimaInputs.maAppliedTo = maAppliedTo; - fimaInputs.maFastLength = maFastLength; - fimaInputs.maSlowLength = maSlowLength; - fimaInputs.maBandLength = maBandLength; - fimaInputs.zigzagDepth = zigzagDepth; - fimaInputs.zigzagDeviation = zigzagDeviation; - fimaInputs.zigzagBackStep = zigzagBackStep; - fimaInputs.zigzagUppersMode = zigzagUppersMode; - fimaInputs.zigzagLowersMode = zigzagLowersMode; - fimaInputs.showPV = showPV; - fimaInputs.showHK = showHK; - fimaInputs.showSAR = showSAR; - fimaInputs.showMAFast = showMAFast; - fimaInputs.showMASlow = showMASlow; - fimaInputs.showMABand = showMABand; - fimaInputs.showZigZag = showZigZag; - fimaInputs.showFiboZone = showFiboZone; - fimaInputs.startCalculationForLastBars = startCalculationForLastBars; - fimaInputs.sarArrowCode = sarArrowCode; - fimaInputs.peakArrowCode = peakArrowCode; - fimaInputs.valeArrowCode = valeArrowCode; - - // - // Instantiate Signaller ... - - // - // XFIMA1 Signaller ... - fima1Signaller = new XCXFIMAStrategy1Signaller( - _Symbol, - _Period, - fimaInputs, - eaProcessAllTicks, // Process All Ticks ... - eaSignallerR2R, // Signaller Risk to Reward Ratio ... - eaSignallerRiskInPoint, // Default Risk In Points ... - eaSignallerVolume // Defaul Volume ... - ); - fima1Signaller.AddOnSignalEventHandler(OnSignalTriggered); - - // - isInited = - fima1Signaller.IsValid(); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Candle Timer Handler ... - eaCTHandler = iCustom( - _Symbol, - _Period, - "x-saherelm.x121.xct", - // - // Inputs ... - barTimeFontSize, // Font Size ... - barTimeFont, // Font ... - barTimeColor, // Text Color ... - barTimeCorner, // Text Position ... - // - // Presentation ... - "", - showBarTime // Show Candle Time - // - ); - isInited = eaCTHandler != INVALID_HANDLE; - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Bar Tracker ... - isInited = eaBarTracker.Init( - _Symbol, - _Period // - ); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Configure XFIMA POI Detector / Drawer ... - detectorConfig.Default(); - detectorConfig.FullDetect(); - marketStructureDrawerConfig.FullDraw(); - - // - Print(ShortName, ": Initialized Successfully ..."); - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Destroy Timer ... - eaExpert.HandleOnDeInit(); - - // - // De Init Indicator ... - IndicatorRelease(eaCTHandler); - - // - eaBarTracker.Clean(); - - // - delete fima1Signaller; - ZeroMemory(fima1Signaller); - - // - delete eaExpert; - ZeroMemory(eaExpert); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - eaIsNewBar = eaBarTracker.IsNewBar(); - bool canProcess = eaProcessAllTicks - ? true - : eaIsNewBar; - // - eaExpert.HandleOnTick(); - - // - if (!canProcess) - { - return; - } - - // - // Bar Index ... - int barIndex = 1; - - // - fima1Signaller.OnTick(barIndex); - - // - // AnalyseMarket(barIndex); -} - -// -// Handle On Trade Event ... -void OnTrade() -{ - eaExpert.HandleOnTrade(); -} - -// -// On Timer ... -void OnTimer() -{ - eaExpert.HandleOnTimer(); -} - -// -// Chart Event Handler ... -void OnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // -) -{ - eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam); -} - -// -// Custom Functions ... - -/** - * Validate all Inputs of Expert Adviser ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - eaSlippage > 0 && - eaMagicNumber > 0 && - // - // Indicator Inputs ... - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ); - if (!isCommonValid) - { - // - errMessage += "common configurations error;" + "\n"; - } - - // - result = - // - // Common ... - isCommonValid && - // - // Otere ... - true - // - ; - - // - if (!result) - { - // - // Since here Logger not Initiallized, we Use Raw Print Command ... - Print(ShortName + " Errors: \n", errMessage); - } - - // - return result; -} - -/** - * Initialize Timer ... - * - * @return ( bool ) - */ -bool InitTimer() -{ - // - bool result = false; - - // - // TODO: Initialize Timer if necessary ... - // result = EventSetTimer(1); - // result = EventSetMillisecondTimer(100); - result = true; - - // - return result; -} - -/** - * Destroy Timer ... - */ -void DestroyTimer() -{ - // - // TODO: Use This ... - // EventKillTimer(); -} - -/** - * Trigger OnSignal Event ... - * - * @param signal: XSignal - */ -void OnSignalTriggered(XSignal &signal) -{ - // - // Validate Signal ... - if (!signal.IsValid()) - { - return; - } - - // - // TODO: Fix this ... - // return; - - // - // Draw Signal on Chart ... - XCSignalObject *iSignalObj; - bool has = fima1Signaller.poiDrawer.DrawSignal( - signal, - iSignalObj, - 7 // - ); - - // - if (has) - { - // - ENUM_X_SIGNAL_EXECUTION_RESULT result; - eaExpert.eaTrader.ExecuteSignal( - signal, - result // - ); - - // - Print("Signal Issued: ", signal.GetObjectID()); - } - - // - // Try to Execute Signal ... - - // - // Draw Signal Vertical Line ... - - // // - // CChartObjectVLine *iObj = new CChartObjectVLine(); - - // // - // string iName = signal.GetObjectID(); - // color iColor = IsLong(signal.type) ? clrLime : clrRed; - - // // - // bool has = iObj.Create( - // fima2Signaller.poiDrawer.ChartIdentification(), - // iName, - // fima2Signaller.poiDrawer.SubWindowIdentification(), - // signal.time // - // ); - // if (has) - // { - // // - // iObj.Width(2); - // iObj.Color(iColor); - - // // - // // eaDraws.Add(iObj); - // } - - // // - // // Alert Issued Signal ... - // string message = signal.GetMessage(); - - // - // int signalBarIndex = GetBarIndex( - // signal.symbol, - // signal.period, - // signal.time // - // ); - // AnalyseMarket(signalBarIndex); -} - -// -// Trade Event Handlers ... - -/** - * Handle StopLoss Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnStopLossTriggered(const XDeal &deal) -{ - eaExpert.HandleOnStopLossTriggered(deal); -} - -/** - * Handle Take Profit Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnTakeProfitTriggered(const XDeal &deal) -{ - eaExpert.HandleOnTakeProfitTriggered(deal); -} - -/** - * Handle Force Close a Position ... - * - * @param ticket: ULONG ... - * @param position: XPosition instance ... - * @param comment: String ... - */ -void OnPositionForceClosed( - const ulong ticket, - const XPosition &position, - const string comment // -) -{ - // - eaExpert.HandleOnPositionForceClosed( - ticket, - position, - comment // - ); -} - -/** - * Handle Deals Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnDealsChanged(int count) -{ - eaExpert.HandleOnDealsChanged(count); -} - -/** - * Handle Orders Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnOrdersChanged(int count) -{ - eaExpert.HandleOnOrdersChanged(count); -} - -/** - * Handle Positions Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnPositionsChanged(int count) -{ - eaExpert.HandleOnPositionsChanged(count); -} - -/** - * Handle Position Modified ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionModified( - const ulong ticket, - const double profit, - const string comment // -) -{ - // - eaExpert.HandleOnPositionModified( - ticket, - profit, - comment // - ); -} - -/** - * Handle Position Partial Closed ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionPartialClosed( - const ulong ticket, - const double profit, - const string comment // -) -{ - // - eaExpert.HandleOnPositionPartialClosed( - ticket, - profit, - comment // - ); -} - -/** - * Handle Trade State Changed ... - * - * @param state: XOnTradeHandlerState instance ... - */ -void OnTradeStateChanged(const XOnTradeHandlerState &state) -{ - eaExpert.HandleOnTradeStateChanged(state); -} - -// -void AnalyseMarket(int barIndex = 0) -{ - // - bool has = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - string symbol = fima1Signaller.symbol; - ENUM_TIMEFRAMES period = fima1Signaller.period; - - // - // Retrieve Signal Bar ... - XOHCL bar; - has = bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // TODO: Remove this and add in OnInit() Method ... - - // - // Configuring Detector ... - - // - detectorConfig.detectOB = true; - detectorConfig.detectFVG = true; - - // - detectorConfig.detectSupport = true; - detectorConfig.detectResistance = true; - detectorConfig.detectSwingTrend = true; - - // - detectorConfig.detectPinned = true; - detectorConfig.detectMomentum = true; - detectorConfig.detectEngulfed = true; - detectorConfig.detectTrueGaped = true; - - // - detectorConfig.detectStarPattern = true; - detectorConfig.detectFlagPattern = true; - detectorConfig.detectRisingPattern = true; - detectorConfig.detectPiercingPattern = true; - detectorConfig.detectSignalKeyBarPattern = true; - - // - detectorConfig.analyseFIMAPVPivots = true; - detectorConfig.analyseFIMASARPivots = false; - detectorConfig.analyseFIMAZigZagPivots = true; - - // - // Configure Drawer ... - - // - marketStructureDrawerConfig.drawOB = false; - marketStructureDrawerConfig.drawFVG = false; - - // - marketStructureDrawerConfig.drawPinned = false; - marketStructureDrawerConfig.drawEngulfed = true; - marketStructureDrawerConfig.drawTrueGaped = false; - marketStructureDrawerConfig.drawMomentum = false; - marketStructureDrawerConfig.drawFlagPattern = false; - marketStructureDrawerConfig.drawStarPattern = false; - marketStructureDrawerConfig.drawRisingPattern = false; - marketStructureDrawerConfig.drawPiercingPattern = false; - marketStructureDrawerConfig.drawSignalKeyBarPattern = true; - - // - // Recents ... - marketStructureDrawerConfig.drawRecentPatterns = false; - marketStructureDrawerConfig.drawFakeBreakedZone = false; - marketStructureDrawerConfig.drawRecentlyTestedZones = false; - marketStructureDrawerConfig.drawRecentlyBreakedZones = false; - - // - // XPV ... - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysis = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisZones = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisTrends = true; - marketStructureDrawerConfig.drawFIMAPVPivotsAnalysisPivots = true; - - // - // XSAR ... - marketStructureDrawerConfig.drawFIMASARPivotsAnalysis = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisZones = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisTrends = false; - marketStructureDrawerConfig.drawFIMASARPivotsAnalysisPivots = false; - - // - // XZigZag ... - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysis = true; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisZones = true; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisTrends = false; - marketStructureDrawerConfig.drawFIMAZigZagPivotsAnalysisPivots = false; - - // - // Analyse Market on Signalling Bar ... - fima1Signaller.poiDetector.AnalyseMarket( - bar, - marketStructure, - detectorConfig // - ); - - // - XFIMASIgballer2First(bar); - // HandleLookupSignal(bar); - - // - bar.Clean(); -} - -// -// Handle Signal Looking Up ... -// Register it as XFIMA Signaller 2 ... -void XFIMASIgballer2First(XOHCL &bar) -{ - // - bool has = - bar.IsValid(); - if (!has) - { - return; - } - - // - XBoxZone iZone; - XSignal iSignal; - string iName = NULL; - XBoxZone supports[]; - XBoxZone resistances[]; - bool isBullish = false; - int barIndex = bar.Index(); - double iPrice = EMPTY_VALUE; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(marketStructure.pinnedDir); - bool hasEngulfedBar = HasDirection(marketStructure.engulfedDir); - bool hasFlagPattern = HasDirection(marketStructure.flagPatternDir); - bool hasStarPattern = HasDirection(marketStructure.starPatternDir); - bool hasRisingPattern = HasDirection(marketStructure.risingPatternDir); - bool hasPiercingPattern = HasDirection(marketStructure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(marketStructure.signalKeyBarPatternDir); - - // - // PV Trend Line ... - string pvTrendName = "XPVTrend"; - CChartObjectTrend *pvTrendLine = NULL; - ENUM_X_DIRECTION pvTrend = X_DIRECTION_NONE; - - // - // ZigZag Trend Line ... - string zgTrendName = "XZGTrend"; - CChartObjectTrend *zgTrendLine = NULL; - ENUM_X_DIRECTION zgTrend = X_DIRECTION_NONE; - - // - // Check PV Analysis ... - bool hasPVAnalysis = marketStructure.pvAnalysis.IsValid(); - if (hasPVAnalysis) - { - // - // Support ... - XBoxZone supportBox; - XCBoxObject *iSupportObj; - has = marketStructure.pvAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - has = fima2Signaller.poiDrawer.DrawBox( - supportBox, - iSupportObj, - true, // Ignore At ... - supportBox.type // Name ... - ); - if (has) - { - // - XPOIStyle iStyle; - fima2Signaller.poiDrawer.GetBoxStyle( - iStyle, - supportBox.dir // - ); - fima2Signaller.poiDrawer.ApplyBoxStyle( - iSupportObj, - iStyle // - ); - iStyle.Clean(); - } - } - - // - // Resistance ... - XBoxZone resistanceBox; - XCBoxObject *iResistanceObj; - has = marketStructure.pvAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - has = fima2Signaller.poiDrawer.DrawBox( - resistanceBox, - iResistanceObj, - true, // Ignore At ... - resistanceBox.type // Name ... - ); - if (has) - { - // - XPOIStyle iStyle; - fima2Signaller.poiDrawer.GetBoxStyle( - iStyle, - resistanceBox.dir // - ); - fima2Signaller.poiDrawer.ApplyBoxStyle( - iResistanceObj, - iStyle // - ); - iStyle.Clean(); - } - } - - // - // Pivots ... - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractPVPivots( - pivots, - barIndex, - 50 // - ); - has = IsValidSize(pivotsCount); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - pvTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(pvTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(pvTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = fima2Signaller.poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - pvTrendLine, - pvTrendName, - true // Ray Right ... - ); - if (has) - { - pvTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - pivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Check ZigZag Analysis ... - bool hasZGAnalysis = marketStructure.zigzagAnalysis.IsValid(); - if (hasZGAnalysis) - { - // - // Support ... - XBoxZone supportBox; - XCBoxObject *iSupportObj; - has = marketStructure.zigzagAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - has = fima2Signaller.poiDrawer.DrawBox( - supportBox, - iSupportObj, - true, // Ignore At ... - supportBox.type // Name ... - ); - if (has) - { - // - XPOIStyle iStyle; - fima2Signaller.poiDrawer.GetBoxStyle( - iStyle, - supportBox.dir // - ); - fima2Signaller.poiDrawer.ApplyBoxStyle( - iSupportObj, - iStyle // - ); - iStyle.Clean(); - } - } - - // - // Resistance ... - XBoxZone resistanceBox; - XCBoxObject *iResistanceObj; - has = marketStructure.zigzagAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - has = fima2Signaller.poiDrawer.DrawBox( - resistanceBox, - iResistanceObj, - true, // Ignore At ... - resistanceBox.type // Name ... - ); - if (has) - { - // - XPOIStyle iStyle; - fima2Signaller.poiDrawer.GetBoxStyle( - iStyle, - resistanceBox.dir // - ); - fima2Signaller.poiDrawer.ApplyBoxStyle( - iResistanceObj, - iStyle // - ); - iStyle.Clean(); - } - } - - // - // Pivots ... - XPivot pivots[]; - int pivotsCount = fima2Signaller.poiDetector.ExtractZigZagPivots( - pivots, - barIndex, - 10 // - ); - has = IsValidSize(pivotsCount); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - zgTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(zgTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(zgTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = fima2Signaller.poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - zgTrendLine, - zgTrendName, - true // Ray Right ... - ); - if (has) - { - zgTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - pivotsCount = fima2Signaller.poiDrawer.DrawPivots( - pivots, - drawnPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Support ... - bool hasSupport = marketStructure.support.IsValid(); - if (hasSupport) - { - // - AddIfNotExists( - marketStructure.support, - supports // - ); - - // - XCBoxObject *iObj; - has = fima2Signaller.poiDrawer.DrawBox( - marketStructure.support, - iObj); - if (has) - { - } - } - - // - // Resistance ... - bool hasResistance = marketStructure.resistance.IsValid(); - if (hasResistance) - { - // - AddIfNotExists( - marketStructure.resistance, - resistances // - ); - - // - XCBoxObject *iObj; - has = fima2Signaller.poiDrawer.DrawBox( - marketStructure.resistance, - iObj); - if (has) - { - } - } - - // - // Check Bar Pattern Exists ... - has = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - - // - // Select Pattern Direction and Price and Price Type ... - if (has) - { - // - if (hasPinnedBar) - { - // - iDir = marketStructure.pinnedDir; - iName = "pinned" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - iDir = marketStructure.engulfedDir; - iName = "engulfed" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - iDir = marketStructure.flagPatternDir; - iName = "flagPattern" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - iDir = marketStructure.starPatternDir; - iName = "starPattern" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - iDir = marketStructure.risingPatternDir; - iName = "risingPattern" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - iDir = marketStructure.piercingPatternDir; - iName = "piercingPattern" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - iDir = marketStructure.signalKeyBarPatternDir; - iName = "signalKeyBarPattern" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - - // - isBullish = IsSpecifiedBullish(iDir); - - // - // Retrieve Price Type for Validate ... - iPriceType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - iPrice = bar.GetPrice(iPriceType); - - // - has = HasDirection(iDir); - } - - // - // Validate Patterns based on MA Band ... - if (has) - { - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fima2Signaller.fimaHelper.GetMABandUpper(barIndex); - double iMABandLower = fima2Signaller.fimaHelper.GetMABandLower(barIndex); - - // - // Validate ... - has = isBullish - ? iPrice < iMABandLower - : iPrice > iMABandUpper; - } - - // - // Select a Zone which Price inside it ... - - // - // Validate Happens in Zone ... - int insideZoneIDX = -1; - has = has && - (isBullish - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : HasInside( - insideZoneIDX, - bar, - resistances // - )); - - // - // Validate Selected Inside Zone ... - // whith Bars Edge ... - has = IsValidIndex(insideZoneIDX); - if (has) - { - // - if (isBullish) - { - iZone = supports[insideZoneIDX]; - } - else - { - iZone = resistances[insideZoneIDX]; - } - - // - has = isBullish - ? bar.high > supports[insideZoneIDX].upper - : bar.low < resistances[insideZoneIDX].lower; - } - - // - // Checking Liquidities ... - - // - // Draw Selected and Validated Bar and Selected Zone ... - if (has) - { - // - int iWidth = 1; - int iCode = 159; - color iClr = isBullish - ? clrYellow - : clrDarkOrange; - ENUM_ARROW_ANCHOR iAnchor = isBullish - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - - // - XCBoxObject *iZoneObj; - XCBarArrowObject *iPatternObj; - - // - has = fima2Signaller.poiDrawer.DrawBarArrow( - bar, - iPatternObj, - iPriceType, - iCode, - iClr, - iWidth, - iAnchor, - iName, - true, // Ignore Bar Tag ... - 10 // Threshold ... - ); - if (has) - { - } - - // - has = fima2Signaller.poiDrawer.DrawBox( - iZone, - iZoneObj, - true, // Ignore At ... - iZone.type // Name ... - ); - if (has) - { - // - XPOIStyle iStyle; - fima2Signaller.poiDrawer.GetBoxStyle( - iStyle, - iZone.dir // - ); - iStyle.width = 2; - iStyle.clr = iClr; - fima2Signaller.poiDrawer.ApplyBoxStyle( - iZoneObj, - iStyle // - ); - } - } - - // - // Preparing Signal ... - if (has) - { - // - iSignal.time = bar.time; - iSignal.provider = "XFima"; - iSignal.symbol = bar.symbol; - iSignal.period = bar.period; - iSignal.mode = X_ORDER_MODE_MARKET; - iSignal.entry = GetEntry(bar.symbol, iDir); - iSignal.type = isBullish - ? POSITION_TYPE_BUY - : POSITION_TYPE_SELL; - - // - iSignal.volume = 0.01; - - // - double _r2r = 2.0; - double _slDistanceInPoint = 5; - double _point = GetPoints(iSignal.symbol); - double _riskDistance = _slDistanceInPoint * _point; - double _risk = _riskDistance + MathAbs((isBullish ? iZone.lower : iZone.upper) - iSignal.entry); - double _reward = GetSpread(iSignal.symbol) + (_risk * _r2r); - - // - double sl = isBullish - ? iSignal.entry - _risk - : iSignal.entry + _risk; - double tp = isBullish - ? iSignal.entry + _reward - : iSignal.entry - _reward; - - // - iSignal.sl = sl; - iSignal.tp = tp; - - // - has = iSignal.IsValid(); - if (has) - { - // - XCSignalObject *iSignalObj; - has = fima2Signaller.poiDrawer.DrawSignal( - iSignal, - iSignalObj, - 7 // - ); - } - } - - // - // For Logging ... - if (has) - { - // - ENUM_X_SIGNAL_EXECUTION_RESULT eResult; - has = eaExpert.eaTrader.ExecuteSignal(iSignal, eResult); - Print("Detect a Potential Place for Price Movement: ", ToXString(iDir), ", Time: ", bar.time); - } - - // - // Cleanup Resources ... - iZone.Clean(); - iSignal.Clean(); - SpecifiedClean(supports); - SpecifiedClean(resistances); -} - -// -void HandleLookupSignal(XOHCL &bar) -{ - // - bool has = - bar.IsValid(); - if (!has) - { - return; - } - - // - XBoxZone iZone; - XSignal iSignal; - string iName = NULL; - bool isBullish = false; - bool isBearish = false; - int barIndex = bar.Index(); - double iPrice = EMPTY_VALUE; - XFIMAConditions fimaConditions; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - int cIDX = 0; - int pIDX = cIDX + 1; - - // - // Check for a Cross ... - - // - // fima2Signaller.fimaHelper.Update(barIndex); - has = fima2Signaller.fimaHelper.GetConditions( - fimaConditions, - barIndex, - 5 // - ); - - // - double cSlowMA = fimaConditions.maSlowBuffer[cIDX]; - double pSlowMA = fimaConditions.maSlowBuffer[pIDX]; - - // - double cMAUpper = fimaConditions.maBandUpperBuffer[cIDX]; - double cMALower = fimaConditions.maBandLowerBuffer[cIDX]; - - // - double pMAUpper = fimaConditions.maBandUpperBuffer[pIDX]; - double pMALower = fimaConditions.maBandLowerBuffer[pIDX]; - - // - bool isCrossedOver = cSlowMA > cMALower && - pSlowMA < pMALower; - - // - bool isCrossedUnder = cSlowMA < cMAUpper && - cSlowMA > pMAUpper; - - // - has = isCrossedOver || - isCrossedUnder; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - - // - if (has) - { - // - isBullish = isCrossedOver; - isBearish = isCrossedUnder; - } - - // - iDir = (isBullish && !isBearish) - ? X_DIRECTION_BULLISH - : (isBearish && !isBullish) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(iDir); - if (has) - { - Print("Conditions Detected ..."); - } - - // - // Cleanup Resources ... - fimaConditions.Clean(); -} - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 b/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 deleted file mode 100644 index 41328ec1..00000000 --- a/Documents/BKP/x-saherelm.xfima.backtester.ea.mq5 +++ /dev/null @@ -1,1053 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XTest MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XBackTester -// Description: a Backtest Tools Strategy Tester -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -//////////////////////////////////////////////////////x -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XBackTester" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -#define ShortName "XBackTester" - -// -// Imports ... -#include "../Classes/x-saherelm.x-backtester.expert.class.mq5" -#include "../Classes/x-saherelm.x-market.pattern.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Helpers/x-saherelm.xom1.helper.mq5" - -// -// Definitions ... - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Alert ... -// Here we Provider All Requirements for -// Configuring Alert Provider ... -input group "Alert"; -input bool eaEnableAlerts = true; // Enable Alerts -input bool eaLogAlerts = true; // Log Alerts -input bool eaMailAlerts = false; // Mail Alerts -input bool eaPushAlerts = false; // Push Alerts -input bool eaTerminalAlerts = false; // Terminal Alerts - -// -// Indicator Inputs ... -// -input group "Calculation"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// PV ... -input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method - -// -// Others ... -input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Middle Zone Level -input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level -input double sarStep = 0.02; // SAR Step -input double sarMax = 0.2; // SAR Maximum -input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To -input int maFastLength = 7; // Fast MA Length -input int maSlowLength = 20; // Slow MA Length -input int zigzagDepth = 12; // ZigZag Depth -input int zigzagDeviation = 5; // ZigZag Deviation -input int zigzagBackStep = 3; // ZigZag Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - -// -input group "Bar Timer"; -input int barTimeFontSize = 10; // Font Size -input string barTimeFont = "Arial"; // Font -input color barTimeColor = clrYellow; // Text Color -input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show PV -input bool showSAR = true; // Show Sar -input bool showMAFast = true; // Show MA Fast -input bool showMASlow = true; // Show MA Slow -input bool showBarTime = true; // Show Bar Time -input bool showZigZag = true; // Show ZigZag -input bool showFiboZone = true; // Show Fibo Zone - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -input int sarArrowCode = 159; // Parabolic Sar Arrow Code -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Define Local Variables ... - -// -string eaLogTag; // EA Log Prefix ... -XCBackTesterEA *eaExpert; // EA Expert ... -XCMarketPatternDetector *eaPatternDetector; // EA Pattern Detector ... - -// -XCPOIDrawer *eaDrawer; // Ea POI Drawer ... -CArrayObj draws; // Drawn Objects ... - -// -XBarTracker eaBarTracker; // EA Bar Traker ... - -// -int eaHandler = INVALID_HANDLE; // Indicator Handler ... -int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ... - -// -ENUM_X_DIRECTION trendDir = X_DIRECTION_NONE; - -// -// Define Indicators Here ... - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Preparing Tags ... - string eaTag = - (IsValid(eaLogSuffix) - ? eaLogSuffix + "_" - : "") + - ShortName; - - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Timer ... - if (!InitTimer()) - { - return INIT_FAILED; - } - - // - // Configure EA Expert Class ... - eaExpert = new XCBackTesterEA(); - - // - // Symbol / Period ... - eaExpert.symbol = _Symbol; - eaExpert.period = _Period; - - // - // Common ... - eaExpert.eaMagicNumber = eaMagicNumber; - eaExpert.eaSlippage = eaSlippage; - eaExpert.eaLogSuffix = eaTag; - - // - // Alert ... - eaExpert.eaEnableAlerts = eaEnableAlerts; - eaExpert.eaLogAlerts = eaLogAlerts; - eaExpert.eaMailAlerts = eaMailAlerts; - eaExpert.eaPushAlerts = eaPushAlerts; - eaExpert.eaTerminalAlerts = eaTerminalAlerts; - - // - // Attach Event Handlers ... - eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged); - eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered); - eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged); - eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); - eaExpert.AddOnModifyPositionEventHandler(OnPositionModified); - eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged); - eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged); - eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed); - eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed); - - // - // Configure Other Requirements ... - eaExpert.volume = 0.01; - eaExpert.riskInPoint = 200; - eaExpert.allowedTPSLStep = 10; - eaExpert.riskToRewardRatio = 2; - eaExpert.minAllowedRiskInPoint = 20; - - // - // Try to Initialize eaExpert ... - bool isInited = eaExpert.HandleOnInit(); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initial Indicator Handler ... - eaHandler = iCustom( - _Symbol, - _Period, - "x-saherelm.xfima", - "", // Calculation ... - scMethod, - scPeriod, - mcMethod, - mcPeriod, - lcMethod, - lcPeriod, - hcMethod, - hcPeriod, - upperMode, - lowerMode, - fiboUpperZoneLevel, - fiboMiddleZoneLevel, - fiboLowerZoneLevel, - sarStep, - sarMax, - maMethod, - maAppliedTo, - maFastLength, - maSlowLength, - zigzagDepth, - zigzagDeviation, - zigzagBackStep, - zigzagUppersMode, - zigzagLowersMode, - "", // Presentation ... - showPV, - showSAR, - showMAFast, - showMASlow, - showZigZag, - showFiboZone, - startCalculationForLastBars, - sarArrowCode, - peakArrowCode, - valeArrowCode - // - ); - isInited = eaHandler != INVALID_HANDLE; - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Candle Timer Handler ... - eaCTHandler = iCustom( - _Symbol, - _Period, - "x-saherelm.x121.xct", - // - // Inputs ... - barTimeFontSize, // Font Size ... - barTimeFont, // Font ... - barTimeColor, // Text Color ... - barTimeCorner, // Text Position ... - // - // Presentation ... - "", - showBarTime // Show Candle Time - // - ); - isInited = eaCTHandler != INVALID_HANDLE; - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Initialize Bar Tracker ... - isInited = eaBarTracker.Init( - _Symbol, - _Period // - ); - if (!isInited) - { - // - Print(ShortName, ": Initialization Failed ..."); - return INIT_FAILED; - } - - // - // Instantiate Market Pattern Detector ... - eaPatternDetector = new XCMarketPatternDetector(); - - // - // Instantiate POI Drawer ... - eaDrawer = new XCPOIDrawer(); - - // - Print(ShortName, ": Initialized Successfully ..."); - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Destroy Timer ... - eaExpert.HandleOnDeInit(); - - // - // De Init Indicator ... - IndicatorRelease(eaHandler); - - // - eaBarTracker.Clean(); - - // - delete eaDrawer; - ZeroMemory(eaDrawer); - - // - delete eaPatternDetector; - ZeroMemory(eaPatternDetector); - - // - delete eaExpert; - ZeroMemory(eaExpert); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - eaExpert.HandleOnTick(); - - // - DetectPatterns(); -} - -// -// Handle On Trade Event ... -void OnTrade() -{ - eaExpert.HandleOnTrade(); -} - -// -// On Timer ... -void OnTimer() -{ - eaExpert.HandleOnTimer(); -} - -// -// Chart Event Handler ... -void OnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // -) -{ - eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam); -} - -// -// Custom Functions ... - -/** - * Validate all Inputs of Expert Adviser ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - eaSlippage > 0 && - eaMagicNumber > 0 && - // - // Indicator Inputs ... - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ); - if (!isCommonValid) - { - // - errMessage += "common configurations error;" + "\n"; - } - - // - result = - // - // Common ... - isCommonValid && - // - // Otere ... - true - // - ; - - // - if (!result) - { - // - // Since here Logger not Initiallized, we Use Raw Print Command ... - Print(ShortName + " Errors: \n", errMessage); - } - - // - return result; -} - -/** - * Initialize Timer ... - * - * @return ( bool ) - */ -bool InitTimer() -{ - // - bool result = false; - - // - // TODO: Initialize Timer if necessary ... - // result = EventSetTimer(1); - // result = EventSetMillisecondTimer(100); - result = true; - - // - return result; -} - -/** - * Destroy Timer ... - */ -void DestroyTimer() -{ - // - // TODO: Use This ... - // EventKillTimer(); -} - -// -// Trade Event Handlers ... - -/** - * Handle StopLoss Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnStopLossTriggered(const XDeal &deal) -{ - eaExpert.HandleOnStopLossTriggered(deal); -} - -/** - * Handle Take Profit Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnTakeProfitTriggered(const XDeal &deal) -{ - eaExpert.HandleOnTakeProfitTriggered(deal); -} - -/** - * Handle Force Close a Position ... - * - * @param ticket: ULONG ... - * @param position: XPosition instance ... - * @param comment: String ... - */ -void OnPositionForceClosed( - const ulong ticket, - const XPosition &position, - const string comment // -) -{ - // - eaExpert.HandleOnPositionForceClosed( - ticket, - position, - comment // - ); -} - -/** - * Handle Deals Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnDealsChanged(int count) -{ - eaExpert.HandleOnDealsChanged(count); -} - -/** - * Handle Orders Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnOrdersChanged(int count) -{ - eaExpert.HandleOnOrdersChanged(count); -} - -/** - * Handle Positions Changes ... - * - * @param count: Integer, Number of Changes ... - */ -void OnPositionsChanged(int count) -{ - eaExpert.HandleOnPositionsChanged(count); -} - -/** - * Handle Position Modified ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionModified( - const ulong ticket, - const double profit, - const string comment // -) -{ - // - eaExpert.HandleOnPositionModified( - ticket, - profit, - comment // - ); -} - -/** - * Handle Position Partial Closed ... - * - * @param ticket: ulong, Position Ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ -void OnPositionPartialClosed( - const ulong ticket, - const double profit, - const string comment // -) -{ - // - eaExpert.HandleOnPositionPartialClosed( - ticket, - profit, - comment // - ); -} - -/** - * Handle Trade State Changed ... - * - * @param state: XOnTradeHandlerState instance ... - */ -void OnTradeStateChanged(const XOnTradeHandlerState &state) -{ - eaExpert.HandleOnTradeStateChanged(state); -} - -/** - * Check Market Conditions for Pattern Detection ... - */ -void DetectPatterns() -{ - // - bool isNewBar = eaBarTracker.IsNewBar(); - if (!isNewBar) - { - return; - } - - // - // Initialize 1 Indexed Bar ... - XOHCL cBar; - bool has = cBar.Init( - _Symbol, - _Period, - 1 // - ); - if (!has) - { - return; - } - - // - // Do Analysis ... - - // - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Define Detection Flags ... - - // - bool detectPinned = false; - bool detectMomentum = false; - bool detectEngulfed = false; - bool detectTrueGaped = false; - - // - bool detectStarPattern = false; - bool detectFlagPattern = false; - bool detectRisingPattern = false; - bool detectPiercingPattern = false; - bool detectSignalKeyBarPattern = false; - - // - bool detectSwingTrend = false; - bool detectSwingTrendBreakes = false; - - // - bool detectSupports = false; - bool detectResistance = false; - - // - // Checking Momentum Bar ... - if (detectMomentum) - { - // - bool isMomentum = eaPatternDetector.IsMomentumBar( - cBar, - iDir // - ); - bool isBullishMomentum = isMomentum && - IsSpecifiedBullish(iDir); - bool isBearishMomentum = isMomentum && - IsSpecifiedBearish(iDir); - if (isMomentum) - { - Print(ToXString(iDir), " Momentum Bar: ", cBar.time); - } - } - - // - // Checking Engulfed Bar ... - if (detectEngulfed) - { - // - bool isEngulfed = eaPatternDetector.IsEngulfedBar( - cBar, - iDir // - ); - bool isBullishEngulfed = isEngulfed && - IsSpecifiedBullish(iDir); - bool isBearishEngulfed = isEngulfed && - IsSpecifiedBearish(iDir); - if (isEngulfed) - { - Print(ToXString(iDir), " Engulfed Bar: ", cBar.time); - } - } - - // - // Checking TruGaped Bar ... - if (detectTrueGaped) - { - // - bool isTrueGaped = eaPatternDetector.IsTrueGapedBar( - cBar, - iDir // - ); - bool isBullishTrueGaped = isTrueGaped && - IsSpecifiedBullish(iDir); - bool isBearishTrueGaped = isTrueGaped && - IsSpecifiedBearish(iDir); - if (isTrueGaped) - { - Print(ToXString(iDir), " TrueGapped Bar: ", cBar.time); - } - } - - // - // Checking Pinned Bar ... - if (detectPinned) - { - bool isPinned = eaPatternDetector.IsPinnedBar( - cBar, - iDir // - ); - bool isBullishPinned = isPinned && - IsSpecifiedBullish(iDir); - bool isBearishPinned = isPinned && - IsSpecifiedBearish(iDir); - if (isPinned) - { - Print(ToXString(iDir), " Pinned Bar: ", cBar.time); - } - } - - // - // Checking Star Pattern ... - if (detectStarPattern) - { - bool isStarPattern = eaPatternDetector.IsStartPattern( - cBar, - iDir // - ); - bool isBullishStarPattern = isStarPattern && - IsSpecifiedBullish(iDir); - bool isBearishStarPattern = isStarPattern && - IsSpecifiedBearish(iDir); - if (isStarPattern) - { - Print(ToXString(iDir), " Star Pattern: ", cBar.time); - } - } - - // - // Checking Piercing Pattern ... - if (detectPiercingPattern) - { - // - bool isPiercingPattern = eaPatternDetector.IsPiercingPattern( - cBar, - iDir // - ); - bool isBullishPiercingPattern = isPiercingPattern && - IsSpecifiedBullish(iDir); - bool isBearishPiercingPattern = isPiercingPattern && - IsSpecifiedBearish(iDir); - if (isPiercingPattern) - { - Print(ToXString(iDir), " Piercing Pattern: ", cBar.time); - } - } - - // - // Checking Rising Pattern ... - if (detectRisingPattern) - { - // - bool isRisingPattern = eaPatternDetector.IsRisingPattern( - cBar, - iDir // - ); - bool isBullishRisingPattern = isRisingPattern && - IsSpecifiedBullish(iDir); - bool isBearishRisingPattern = isRisingPattern && - IsSpecifiedBearish(iDir); - if (isRisingPattern) - { - Print(ToXString(iDir), " Rising Pattern: ", cBar.time); - } - } - - // - // Checking Flag Pattern ... - if (detectFlagPattern) - { - // - XOHCL swingBar; - bool isFlagPattern = eaPatternDetector.IsFlagPattern( - cBar, - iDir, - swingBar // - ); - bool isBullishFlagPattern = isFlagPattern && - IsSpecifiedBullish(iDir); - bool isBearishFlagPattern = isFlagPattern && - IsSpecifiedBearish(iDir); - if (isFlagPattern) - { - Print(ToXString(iDir), " Flag Pattern: ", cBar.time, ", Swing: ", swingBar.time); - } - swingBar.Clean(); - } - - // - // Detect SignalKey Bar Pattern ... - if (detectSignalKeyBarPattern) - { - // - bool isSignalKeyBar = eaPatternDetector.IsSignalKeyBarPattern( - cBar, - iDir // - ); - bool isBullishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBullish(iDir); - bool isBearishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBearish(iDir); - if (isSignalKeyBar) - { - Print(ToXString(iDir), " SignalKey Bar Pattern: ", cBar.time); - } - } - - // - // Detect Swing Trend ... - if (detectSwingTrend) - { - // - XOHCL swings[]; - bool hasSwingTrend = eaPatternDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - Print(ToXString(iDir), " Swing Trend: ", cBar.time); - - // - CChartObjectTrend *iObj; - has = eaDrawer.DrawSwingTrend( - swings, - iDir, - iObj, - true // Ray Right ... - ); - if (has) - { - draws.Add(iObj); - } - } - SpecifiedClean(swings); - } - - // - // Swing Trend Breakes ... - if (detectSwingTrendBreakes) - { - // - XOHCL swings[]; - bool hasSwingTrend = eaPatternDetector.HasSwingTrend( - cBar, - iDir, - swings // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - if (!HasDirection(trendDir)) - { - trendDir = iDir; - } - } - - // - // Breaked Detection ... - if (trendDir != iDir) - { - // - Print("Trend Dir Breaked to: ", ToXString(iDir)); - trendDir = iDir; - } - - // - SpecifiedClean(swings); - } - - // - // Detect Supports ... - if (detectSupports) - { - // - XOHCL support; - bool hasSupport = eaPatternDetector.HasSupport( - cBar, - support // - ); - if (hasSupport) - { - // - XBoxZone supportBox; - has = ToSupportBox(support, supportBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = eaDrawer.DrawBox( - supportBox, - iObj // - ); - if (has) - { - // - // Apply Style ... - eaDrawer.ApplyStyle( - iObj, - eaDrawer.boxBullishStyle // - ); - - // - draws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - supportBox.Clean(); - } - support.Clean(); - } - - // - // Detect Resistance ... - if (detectResistance) - { - // - XOHCL resistance; - bool hasResistance = eaPatternDetector.HasResistance( - cBar, - resistance // - ); - if (hasResistance) - { - // - XBoxZone resistanceBox; - has = ToResistanceBox(resistance, resistanceBox); - if (has) - { - // - // Draw Box ... - XCBoxObject *iObj; - has = eaDrawer.DrawBox( - resistanceBox, - iObj // - ); - if (has) - { - // - // Apply Style ... - eaDrawer.ApplyStyle( - iObj, - eaDrawer.boxBearishStyle // - ); - - // - draws.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - resistanceBox.Clean(); - } - resistance.Clean(); - } - - // - cBar.Clean(); -} - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.helper copy 2.mq5 b/Documents/BKP/x-saherelm.xfima.helper copy 2.mq5 deleted file mode 100644 index a175d65d..00000000 --- a/Documents/BKP/x-saherelm.xfima.helper copy 2.mq5 +++ /dev/null @@ -1,8413 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XCXFIMAHelper -// Description: provides all Indicator -// Helper requirements ... -// -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.x-helper.class.mq5" -#include "../Classes/x-saherelm.x-market.pattern.class.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Definitions ... - -// -// Buffers ... -enum ENUM_XFIMA_BUFFERS -{ - // - // Plot Buffers ... - XFIMA_MA_FAST_LINE = 0, - XFIMA_MA_FAST_COLOR_LINE = 1, - XFIMA_MA_SLOW_LINE = 2, - XFIMA_MA_SLOW_COLOR_LINE = 3, - XFIMA_SAR_LINE = 4, - XFIMA_SAR_COLOR_LINE = 5, - XFIMA_PEAK_LINE = 6, - XFIMA_VALE_LINE = 7, - XFIMA_FIBO_UPPER_LINE = 8, - XFIMA_FIBO_MIDDLE_LINE = 9, - XFIMA_FIBO_LOWER_LINE = 10, - XFIMA_ZIGZAG_LINE = 11, - XFIMA_MA_BAND_UPPER_LINE = 12, - XFIMA_MA_BAND_LOWER_LINE = 13, - XFIMA_HK_OPEN_LINE = 14, - XFIMA_HK_HIGH_LINE = 15, - XFIMA_HK_LOW_LINE = 16, - XFIMA_HK_CLOSE_LINE = 17, - XFIMA_HK_COLOR_LINE = 18, - XFIMA_HK_BAND_UPPER_LINE = 19, - XFIMA_HK_BAND_LOWER_LINE = 20, - XFIMA_PB_BAND_UPPER_LINE = 21, - XFIMA_PB_BAND_LOWER_LINE = 22, - XFIMA_ATR_BAND_UPPER_LINE = 23, - XFIMA_ATR_BAND_LOWER_LINE = 24, - // - // Data Buffers ... - XFIMA_MA_FAST_STATE_LINE = 25, - XFIMA_MA_SLOW_STATE_LINE = 26, - XFIMA_SAR_STATE_LINE = 27, - XFIMA_SC_HH_LINE = 28, - XFIMA_SC_LL_LINE = 29, - XFIMA_MC_HH_LINE = 30, - XFIMA_MC_LL_LINE = 31, - XFIMA_LC_HH_LINE = 32, - XFIMA_LC_LL_LINE = 33, - XFIMA_HC_HH_LINE = 34, - XFIMA_HC_LL_LINE = 35, - XFIMA_ZIGZAG_HIGHS_LINE = 36, - XFIMA_ZIGZAG_HIGHS_TIME_LINE = 37, - XFIMA_ZIGZAG_LOWS_LINE = 38, - XFIMA_ZIGZAG_LOWS_TIME_LINE = 39, - XFIMA_HK_RAW_OPEN_LINE = 40, - XFIMA_HK_RAW_HIGH_LINE = 41, - XFIMA_HK_RAW_LOW_LINE = 42, - XFIMA_HK_RAW_CLOSE_LINE = 43, - XFIMA_PB_BAND_RAW_UPPER_LINE = 44, - XFIMA_PB_BAND_RAW_LOWER_LINE = 45, - XFIMA_ATR_LINE = 46, - XFIMA_ATR_BAND_RAW_UPPER_LINE = 47, - XFIMA_ATR_BAND_RAW_LOWER_LINE = 48, -}; - -// -// Input Models ... -struct XFIMAInputs -{ - // - // Props ... - - // - // Calculation ... - ENUM_X_PERIOD_METHOD scMethod; // How to Find Short Period - ENUM_TIMEFRAMES scPeriod; // Short Period - ENUM_X_PERIOD_METHOD mcMethod; // How to Find Medium Period - ENUM_TIMEFRAMES mcPeriod; // Medium Period - ENUM_X_PERIOD_METHOD lcMethod; // How to Find Long Period - ENUM_TIMEFRAMES lcPeriod; // Long Period - ENUM_X_PERIOD_METHOD hcMethod; // How to Find Hind Period - ENUM_TIMEFRAMES hcPeriod; // Hind Period - ENUM_SERIESMODE upperMode; // Peak Method - ENUM_SERIESMODE lowerMode; // Vale Method - ENUM_X_FIBO_LEVELS fiboUpperZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboLowerZoneLevel; // Lower Zone Level - double sarStep; // SAR Step - double sarMax; // SAR Maximum - ENUM_MA_METHOD maMethod; // MA Method - ENUM_APPLIED_PRICE maAppliedTo; // MA Applied To - int maFastLength; // Fast MA Length - int maSlowLength; // Slow MA Length - int maBandLength; // MA Band Length - int zigzagDepth; // ZigZag Depth - int zigzagDeviation; // ZigZag Deviation - int zigzagBackStep; // ZigZag Back Step - ENUM_X_PRICE zigzagUppersMode; // ZigZag High Detect Mode - ENUM_X_PRICE zigzagLowersMode; // ZigZag Low Detect Mode - bool hkIgnoreShadows; // HK Remove noises - int hkSmoothingLength; // HK Smoothing Length - ENUM_X_MA_METHOD hkSmoothingMode; // HK Smoothing Method - int atrLength; // ATR Length - double atrMultiplier; // ATR Band Multiplier - int atrSmoothingLength; // ATR Smoothing Length - ENUM_X_PRICE atrUpperPriceType; // ATR Upper Zone Applied To - ENUM_X_PRICE atrLowerPriceType; // ATR Lower Zone Applied To - ENUM_X_MA_METHOD atrSmoothingMode; // ATR Smoothing Method - - // - // Presentation ... - bool showPV; // Show PV - bool showHK; // Show HK - bool showSAR; // Show Sar - bool showMAFast; // Show MA Fast - bool showMASlow; // Show MA Slow - bool showMABand; // Show MA Band - bool showHKBand; // Show HK Band - bool showATRBand; // Show ATR Band - bool showZigZag; // Show ZigZag - bool showFiboZone; // Show Fibo Zone - int startCalculationForLastBars; // Calculate Last n Bars - int sarArrowCode; // Parabolic Sar Arrow Code - int peakArrowCode; // Peaks Arrow Code - int valeArrowCode; // Vales Arrow Code - - // - // Constructor(s) ... - XFIMAInputs() - { - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - ZeroMemory(this); - } - - // - // Default ... - void Default() - { - // - // Calculations ... - scMethod = X_PERIOD_AUTO; // How to Find Short Period - scPeriod = NULL; // Short Period - mcMethod = X_PERIOD_AUTO; // How to Find Medium Period - mcPeriod = NULL; // Medium Period - lcMethod = X_PERIOD_AUTO; // How to Find Long Period - lcPeriod = NULL; // Long Period - hcMethod = X_PERIOD_AUTO; // How to Find Hind Period - hcPeriod = NULL; // Hind Period - upperMode = MODE_HIGH; // Peak Method - lowerMode = MODE_LOW; // Vale Method - fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level - fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Upper Zone Level - fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level - sarStep = 0.02; // SAR Step - sarMax = 0.2; // SAR Maximum - maMethod = MODE_EMA; // MA Method - maAppliedTo = PRICE_CLOSE; // MA Applied To - maFastLength = 7; // Fast MA Length - maSlowLength = 20; // Slow MA Length - maBandLength = 7; // MA Band Length - zigzagDepth = 12; // ZigZag Depth - zigzagDeviation = 5; // ZigZag Deviation - zigzagBackStep = 3; // ZigZag Back Step - zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode - zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - hkIgnoreShadows = true; // HK Remove noises - hkSmoothingLength = 21; // HK Smoothing Length - hkSmoothingMode = X_MA_MODE_EMA; // HK Smoothing Method - atrLength = 14; // ATR Length - atrMultiplier = 1.5; // ATR Band Multiplier - atrSmoothingLength = 21; // ATR Smoothing Length - atrUpperPriceType = X_PRICE_HIGH; // ATR Upper Zone Applied To - atrLowerPriceType = X_PRICE_LOW; // ATR Lower Zone Applied To - atrSmoothingMode = X_MA_MODE_EMA; // ATR Smoothing Method - - // - // Presentation ... - showPV = true; // Show PV - showHK = true; // Show HK - showSAR = true; // Show Sar - showMAFast = true; // Show MA Fast - showMASlow = true; // Show MA Slow - showMABand = true; // Show MA Band - showHKBand = true; // Show HK Band - showATRBand = true; // Show ATR Band - showZigZag = true; // Show ZigZag - showFiboZone = true; // Show Fibo Zone - startCalculationForLastBars = 1500; // Calculate Last n Bars - sarArrowCode = 159; // Parabolic Sar Arrow Code - peakArrowCode = 159; // Peaks Arrow Code - valeArrowCode = 159; // Vales Arrow Code - } - - // - // Hide all Visible Buffers ... - void Hide() - { - // - showPV = false; - showHK = false; - showSAR = false; - showMAFast = false; - showMASlow = false; - showMABand = false; - showHKBand = false; - showATRBand = false; - showZigZag = false; - showFiboZone = false; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maBandLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // ATR ... - atrLength > 0 && - atrMultiplier >= 1 && - IsXValid(atrUpperPriceType) && - IsXValid(atrLowerPriceType) && - // - // CYCLES ... - (IsSpecifiedValid(scMethod, scPeriod) && - IsSpecifiedValid(mcMethod, mcPeriod) && - IsSpecifiedValid(lcMethod, lcPeriod) && - IsSpecifiedValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; - } -}; - -// -// Conditions ... -struct XFIMAConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - datetime to; - datetime from; - XOHCL bars[]; - - // - // Buffers ... - double maFastBuffer[]; - double maFastColorBuffer[]; - double maFastStateBuffer[]; - double maSlowBuffer[]; - double maSlowColorBuffer[]; - double maSlowStateBuffer[]; - double maBandUpperBuffer[]; - double maBandLowerBuffer[]; - double sarBuffer[]; - double sarColorBuffer[]; - double sarStateBuffer[]; - double peakBuffer[]; - double valeBuffer[]; - double fiboUpperBuffer[]; - double fiboMiddleBuffer[]; - double fiboLowerBuffer[]; - double zigzagBuffer[]; - double sHHBuffer[]; - double sLLBuffer[]; - double mHHBuffer[]; - double mLLBuffer[]; - double lHHBuffer[]; - double lLLBuffer[]; - double hHHBuffer[]; - double hLLBuffer[]; - double highsBuffer[]; - double highsTimeBuffer[]; - double lowsBuffer[]; - double lowsTimeBuffer[]; - double hkOpenBuffer[]; - double hkHighBuffer[]; - double hkLowBuffer[]; - double hkCloseBuffer[]; - double hkColorBuffer[]; - - // - // Conditions ... - - // - // Constructor ... - XFIMAConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - // Commons ... - to = NULL; - from = NULL; - time = NULL; - symbol = NULL; - period = NULL; - - // - // Buffers ... - - // - SpecifiedClean(bars); - - // - SpecifiedClean(maFastBuffer); - SpecifiedClean(maFastColorBuffer); - SpecifiedClean(maFastStateBuffer); - SpecifiedClean(maSlowBuffer); - SpecifiedClean(maSlowColorBuffer); - SpecifiedClean(maSlowStateBuffer); - SpecifiedClean(maBandUpperBuffer); - SpecifiedClean(maBandLowerBuffer); - SpecifiedClean(sarBuffer); - SpecifiedClean(sarColorBuffer); - SpecifiedClean(sarStateBuffer); - SpecifiedClean(peakBuffer); - SpecifiedClean(valeBuffer); - SpecifiedClean(fiboUpperBuffer); - SpecifiedClean(fiboMiddleBuffer); - SpecifiedClean(fiboLowerBuffer); - SpecifiedClean(zigzagBuffer); - SpecifiedClean(sHHBuffer); - SpecifiedClean(sLLBuffer); - SpecifiedClean(mHHBuffer); - SpecifiedClean(mLLBuffer); - SpecifiedClean(lHHBuffer); - SpecifiedClean(lLLBuffer); - SpecifiedClean(hHHBuffer); - SpecifiedClean(hLLBuffer); - SpecifiedClean(highsBuffer); - SpecifiedClean(highsTimeBuffer); - SpecifiedClean(lowsBuffer); - SpecifiedClean(lowsTimeBuffer); - SpecifiedClean(hkOpenBuffer); - SpecifiedClean(hkHighBuffer); - SpecifiedClean(hkLowBuffer); - SpecifiedClean(hkCloseBuffer); - SpecifiedClean(hkColorBuffer); - - // - // Conditions ... - - // - ArraySetAsSeries(bars, true); - - // - ArraySetAsSeries(maFastBuffer, true); - ArraySetAsSeries(maFastColorBuffer, true); - ArraySetAsSeries(maFastStateBuffer, true); - ArraySetAsSeries(maSlowBuffer, true); - ArraySetAsSeries(maSlowColorBuffer, true); - ArraySetAsSeries(maSlowStateBuffer, true); - ArraySetAsSeries(maBandUpperBuffer, true); - ArraySetAsSeries(maBandLowerBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(sarColorBuffer, true); - ArraySetAsSeries(sarStateBuffer, true); - ArraySetAsSeries(peakBuffer, true); - ArraySetAsSeries(valeBuffer, true); - ArraySetAsSeries(fiboUpperBuffer, true); - ArraySetAsSeries(fiboMiddleBuffer, true); - ArraySetAsSeries(fiboLowerBuffer, true); - ArraySetAsSeries(zigzagBuffer, false); // Fix this ... - ArraySetAsSeries(sHHBuffer, true); - ArraySetAsSeries(sLLBuffer, true); - ArraySetAsSeries(mHHBuffer, true); - ArraySetAsSeries(mLLBuffer, true); - ArraySetAsSeries(lHHBuffer, true); - ArraySetAsSeries(lLLBuffer, true); - ArraySetAsSeries(hHHBuffer, true); - ArraySetAsSeries(hLLBuffer, true); - ArraySetAsSeries(highsBuffer, true); - ArraySetAsSeries(highsTimeBuffer, true); - ArraySetAsSeries(lowsBuffer, true); - ArraySetAsSeries(lowsTimeBuffer, true); - ArraySetAsSeries(hkOpenBuffer, true); - ArraySetAsSeries(hkHighBuffer, true); - ArraySetAsSeries(hkLowBuffer, true); - ArraySetAsSeries(hkCloseBuffer, true); - ArraySetAsSeries(hkColorBuffer, true); - - // - ZeroMemory(this); - } - - /** - * Generate Conditions Scores ... - * - * @param bullishScore: Double, Directional Scores Reference ... - * @param bearishScore: Double, Directional Scores Reference ... - */ - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - } - - /** - * Generate Summary String for Represent Conditions State ... - * - * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... - * @param onlyConditions: Boolean, Just Generate Only Conditions ... - * @param includeScores: Boolean, Attach Scores Representations on Result ... - * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... - * @param separator: String, Separate Lines ... - * - * @return ( string ) - */ - string GenerateSummary( - bool onlyCommons = false, - bool onlyConditions = false, - bool includeScores = true, - bool ignoreFalseConditions = true, - string separator = "\n" // - ) - { - return ""; - } - - /** - * Retrieve Unique Tag Identifier ... - * - * @return ( string ) - */ - string GetTag() - { - return GetToken(this); - } -}; - -// -// Class ... -class XCXFIMAHelper : public XCBaseHelper -{ - // - // Public ... - public: - // - // Props ... - XCMarketPatternDetector *patternDetector; - - // - // Constructors ... - XCXFIMAHelper() - : XCBaseHelper(_Symbol, _Period) - { - patternDetector = new XCMarketPatternDetector(); - } - - // - // Deconstructor ... - ~XCXFIMAHelper() - { - // - delete patternDetector; - ZeroMemory(patternDetector); - } - - // - // Tools ... - - // - // Initialize Helper Cleass ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XFIMAInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xfima", - "", // Calculation ... - mInputs.scMethod, - mInputs.scPeriod, - mInputs.mcMethod, - mInputs.mcPeriod, - mInputs.lcMethod, - mInputs.lcPeriod, - mInputs.hcMethod, - mInputs.hcPeriod, - mInputs.upperMode, - mInputs.lowerMode, - mInputs.fiboUpperZoneLevel, - mInputs.fiboMiddleZoneLevel, - mInputs.fiboLowerZoneLevel, - mInputs.sarStep, - mInputs.sarMax, - mInputs.maMethod, - mInputs.maAppliedTo, - mInputs.maFastLength, - mInputs.maSlowLength, - mInputs.maBandLength, - mInputs.zigzagDepth, - mInputs.zigzagDeviation, - mInputs.zigzagBackStep, - mInputs.zigzagUppersMode, - mInputs.zigzagLowersMode, - mInputs.hkIgnoreShadows, - mInputs.hkSmoothingLength, - mInputs.hkSmoothingMode, - mInputs.atrLength, - mInputs.atrMultiplier, - mInputs.atrSmoothingLength, - mInputs.atrUpperPriceType, - mInputs.atrLowerPriceType, - mInputs.atrSmoothingMode, - "", // Presentation ... - mInputs.showPV, - mInputs.showHK, - mInputs.showSAR, - mInputs.showMAFast, - mInputs.showMASlow, - mInputs.showMABand, - mInputs.showHKBand, - mInputs.showATRBand, - mInputs.showZigZag, - mInputs.showFiboZone, - mInputs.startCalculationForLastBars, - mInputs.sarArrowCode, - mInputs.peakArrowCode, - mInputs.valeArrowCode - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XFIMAInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XFIMAInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs // - ); - } - - // - // Tools ... - - // - bool GetConditions( - XFIMAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = true; - - // - if (loopback < 5) - { - loopback = 5; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - // Filling Bars ... - int barsCount = GetBars( - conditions.bars, - mSymbol, - mPeriod, - barIndex, - loopback // - ); - result = barsCount == loopback; - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - conditions.to = conditions.bars[0].time; - conditions.from = conditions.bars[ArraySize(conditions.bars) - 1].time; - - // - int zIndex = barIndex; - - // - // Buffers ... - - // - CopyMAFast( - zIndex, - loopback, - conditions.maFastBuffer // - ); - - // - CopyMAFastState( - zIndex, - loopback, - conditions.maFastStateBuffer // - ); - - // - CopyMASlow( - zIndex, - loopback, - conditions.maSlowBuffer // - ); - - // - CopyMASlowState( - zIndex, - loopback, - conditions.maSlowStateBuffer // - ); - - // - CopyMABandUpper( - zIndex, - loopback, - conditions.maBandUpperBuffer // - ); - - // - CopyMABandLower( - zIndex, - loopback, - conditions.maBandLowerBuffer // - ); - - // - CopySar( - zIndex, - loopback, - conditions.sarBuffer // - ); - - // - CopySarState( - zIndex, - loopback, - conditions.sarStateBuffer // - ); - - // - CopyPeak( - zIndex, - loopback, - conditions.peakBuffer // - ); - - // - CopyVale( - zIndex, - loopback, - conditions.valeBuffer // - ); - - // - CopyFiboUpper( - zIndex, - loopback, - conditions.fiboUpperBuffer // - ); - - // - CopyFiboMiddle( - zIndex, - loopback, - conditions.fiboMiddleBuffer // - ); - - // - CopyFiboLower( - zIndex, - loopback, - conditions.fiboLowerBuffer // - ); - - // - CopyZigZag( - zIndex, - loopback, - conditions.zigzagBuffer // - ); - - // - CopySHH( - zIndex, - loopback, - conditions.sHHBuffer // - ); - - // - CopySLL( - zIndex, - loopback, - conditions.sLLBuffer // - ); - - // - CopyMHH( - zIndex, - loopback, - conditions.mHHBuffer // - ); - - // - CopyMLL( - zIndex, - loopback, - conditions.mLLBuffer // - ); - - // - CopyLHH( - zIndex, - loopback, - conditions.lHHBuffer // - ); - - // - CopyLLL( - zIndex, - loopback, - conditions.lLLBuffer // - ); - - // - CopyHHH( - zIndex, - loopback, - conditions.hHHBuffer // - ); - - // - CopyHLL( - zIndex, - loopback, - conditions.hLLBuffer // - ); - - // - CopyHKOpen( - zIndex, - loopback, - conditions.hkOpenBuffer // - ); - - // - CopyHKHigh( - zIndex, - loopback, - conditions.hkHighBuffer // - ); - - // - CopyHKLow( - zIndex, - loopback, - conditions.hkLowBuffer // - ); - - // - CopyHKClose( - zIndex, - loopback, - conditions.hkCloseBuffer // - ); - - // - CopyHKColor( - zIndex, - loopback, - conditions.hkColorBuffer // - ); - - // - // Conditions ... - - // - return result; - } - - // - // Pivot Actions ... - - /** - * Check Specified Bar has MA Cross or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * - * @return ( bool ) - */ - bool HasMACross( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - double validCrossDiffMultiplier = 1 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast[]; - int fastCount = CopyMAFast(barIndex, 2, fast); - - // - double slow[]; - int slowCount = CopyMASlow(barIndex, 2, slow); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - int count = MathMin(fastCount, slowCount); - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(fast[0]) && - NotEmptyZero(fast[1]) && - NotEmptyZero(slow[0]) && - NotEmptyZero(slow[1]); - - // - isBullish = - notEmpty && - fast[0] > slow[0] && - fast[1] < slow[1]; - - // - isBearish = - notEmpty && - fast[0] < slow[0] && - fast[1] > slow[1]; - - // - result = - isBullish || - isBearish; - - // - // Validate Direction Change ... - if (result && - validCrossDiffMultiplier > 0) - { - // - double _points = GetPoints(GetSymbol()); - double diff = MathAbs(fast[0] - slow[0]); - - // - result = diff >= (validCrossDiffMultiplier * _points); - } - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - - // - return result; - } - - /** - * Check Specified Bar Price is In Boundary or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsInBoundary( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Bar ... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - // Read Boundary Values ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - result = value < max && - value > min; - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar Price is Over Boundary Min ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsOverBoundaryMin( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Boundary ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - return result; - } - - // - // Retrieve Bar .... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - result = value > min; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar Price is Under Boundary Max ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsUnderBoundaryMax( - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Retrieve Boundary ... - double min; - double max; - result = GetBoundaryValues(min, max, barIndex); - if (!result) - { - return result; - } - - // - // Retrieve Bar .... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - double value = bar.GetPrice(priceType); - - // - result = value < max; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check Boundary Fake Breaked or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param overMaxPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * @param underMinPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * - * @return ( bool ) - */ - bool IsBoundaryFakeBreaked( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - ENUM_X_PRICE overMaxPriceType = X_PRICE_NONE, - ENUM_X_PRICE underMinPriceType = X_PRICE_NONE // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(overMaxPriceType)) - { - overMaxPriceType = X_PRICE_CLOSE; - } - if (!IsXValid(underMinPriceType)) - { - underMinPriceType = X_PRICE_CLOSE; - } - - // - // Initial Bars ... - XOHCL bar; - XOHCL pBar; - double min; - double max; - double pMin; - double pMax; - double boundaryValues[]; - result = - bar.Init( - mSymbol, - mPeriod, - barIndex // - ) && - bar.GetPreviousBar(pBar) && - GetBoundaryValues(min, max, barIndex) && - GetBoundaryValues(pMin, pMax, barIndex + 1) && - FillBoundaryValues(boundaryValues, barIndex) > 0; - - // - bool isBullish = - result && - pBar.IsBearish() && - bar.IsBullish() && - pBar.GetPrice(underMinPriceType) < pMin && - bar.GetPrice(underMinPriceType) > min && - (bar.GetPrice(underMinPriceType) > FindLesserThan(max, boundaryValues) || - bar.GetPrice(underMinPriceType) > FindBiggerThan(min + ((max - min) / 2), boundaryValues)); - - // - bool isBearish = - result && - pBar.IsBullish() && - bar.IsBearish() && - pBar.GetPrice(overMaxPriceType) > pMax && - bar.GetPrice(overMaxPriceType) < max && - (bar.GetPrice(overMaxPriceType) < FindBiggerThan(min, boundaryValues) || - bar.GetPrice(overMaxPriceType) < FindLesserThan(min + ((max - min) / 2), boundaryValues)); - - // - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Cleanup ... - bar.Clean(); - pBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar's Price in Hot Place or Not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param overMaxPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * @param underMinPriceType: ENUM_X_PRICE, which price of Specified bar to Check ... - * - * @return ( bool ) - */ - bool IsInHotPlace( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - ENUM_X_PRICE overMaxPriceType = X_PRICE_NONE, - ENUM_X_PRICE underMinPriceType = X_PRICE_NONE // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - if (!IsXValid(overMaxPriceType)) - { - overMaxPriceType = X_PRICE_LOW; - } - if (!IsXValid(underMinPriceType)) - { - underMinPriceType = X_PRICE_HIGH; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Initialize Bar ... - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double overMaxPrice = bar.GetPrice(overMaxPriceType); - double underMinPrice = bar.GetPrice(underMinPriceType); - - // - // Reading Boundary Value ... - double min; - double max; - result = GetBoundaryValues( - min, - max, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - bool isBullish = underMinPrice < min; - bool isBearish = overMaxPrice > max; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - bar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar price Crossed in Boundary or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold Crossed in Dir ... - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsCrossedInBoundary( - ENUM_X_DIRECTION &dir, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - int pBarIndex = barIndex + 1; - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Check PrevBar Is in Hot Place ... - result = IsInHotPlace( - dir, - pBarIndex, - X_PRICE_LOW, - X_PRICE_HIGH // - ); - if (!result) - { - // - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - // Current Bar must Into Boundary ... - result = IsInBoundary(priceType, barIndex); - if (!result) - { - dir = X_DIRECTION_NONE; - } - - // - result = HasDirection(dir); - - // - return result; - } - - /** - * Check Specified Bar price Crossed out Boundary or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold Crossed in Dir ... - * @param priceType: ENUM_X_PRICE, Specified Price type of Bar ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsCrossedOutBoundary( - ENUM_X_DIRECTION &dir, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - int pBarIndex = barIndex + 1; - - // - if (!IsXValid(priceType)) - { - priceType = X_PRICE_CLOSE; - } - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Prev Bar Must in Boundary ... - bool isBullish = IsInBoundary(X_PRICE_LOW, pBarIndex); - bool isBearish = IsInBoundary(X_PRICE_HIGH, pBarIndex); - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - // Current Bar must Out of Boundary ... - - XOHCL bar; - result = bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - - // - isBullish = - result && - isBullish && - bar.IsBullish() && - !IsInBoundary(priceType, barIndex); - - // - isBearish = - result && - isBearish && - bar.IsBearish() && - !IsInBoundary(priceType, barIndex); - - // - result = isBullish || - isBearish; - if (!result) - { - // - bar.Clean(); - return result; - } - - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = HasDirection(dir); - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar has Boundary Trend or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasBoundaryTrend( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - result = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower); - if (!result) - { - return result; - } - - // - bool isBullish = - fast > hkBandLower && - slow > hkBandLower && - maBandUpper > hkBandLower && - maBandLower > hkBandLower && - pbBandUpper > hkBandLower && - pbBandLower > hkBandLower; - bool isBearish = - fast < hkBandUpper && - slow < hkBandUpper && - maBandUpper < hkBandUpper && - maBandLower < hkBandUpper && - pbBandUpper < hkBandUpper && - pbBandLower < hkBandUpper; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - return result; - } - - /** - * Check Specified Bar has Boundary Trend Switched or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasBoundarySwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - result = HasBoundaryTrend( - dir, - barIndex // - ); - if (!result) - { - return result; - } - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - result = HasBoundaryTrend( - dir, - barIndex + 1 // - ); - if (!result) - { - return result; - } - bool isPBullish = IsXBullish(dir); - bool isPBearish = IsXBearish(dir); - - // - bool isSwitchedToBullish = - isBullish && !isPBullish; - bool isSwitchedToBearish = - isBearish && !isPBearish; - result = isSwitchedToBullish || - isSwitchedToBearish; - if (result) - { - // - dir = isSwitchedToBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - return result; - } - - /** - * Check Fibo Section is Changed or not ... - * - * @param dir: reference to hold section change direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsFiboSectionChanged( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - bool isBullish = false; - bool isBearish = false; - - // - // Reading Values ... - - // - double iFiboUpper = GetFiboUpper(barIndex); - double pFiboUpper = GetFiboUpper(barIndex + 1); - - // - double iFiboMiddle = GetFiboMiddle(barIndex); - double pFiboMiddle = GetFiboMiddle(barIndex + 1); - - // - double iFiboLower = GetFiboLower(barIndex); - double pFiboLower = GetFiboLower(barIndex + 1); - - // - isBullish = iFiboLower >= pFiboMiddle && - iFiboMiddle >= pFiboUpper; - isBearish = iFiboUpper <= pFiboMiddle && - iFiboMiddle <= pFiboLower; - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (!result) - { - return result; - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - return result; - } - - /** - * Check for Fibo Push Exists or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to hold result ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, Validation Length ... - * - * @return ( bool ) - */ - bool HasFiboPush( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 3); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - XOHCL iBar; - bool isBullish = false; - bool isBearish = false; - - // - double iFiboUpper = EMPTY_VALUE; - double pFiboUpper = EMPTY_VALUE; - - // - double iFiboMiddle = EMPTY_VALUE; - double pFiboMiddle = EMPTY_VALUE; - - // - double iFiboLower = EMPTY_VALUE; - double pFiboLower = EMPTY_VALUE; - - // - // Check Zone Validation ... - int start = barIndex; - int end = start + validationLength; - for (int i = start; i < end; i++) - { - // - // Reading Values ... - - // - iFiboUpper = GetFiboUpper(i); - pFiboUpper = GetFiboUpper(i + 1); - - // - iFiboMiddle = GetFiboMiddle(i); - pFiboMiddle = GetFiboMiddle(i + 1); - - // - iFiboLower = GetFiboLower(i); - pFiboLower = GetFiboLower(i + 1); - - // - result = iFiboUpper == pFiboUpper; - if (!result) - { - break; - } - } - - // - if (result) - { - // - result = iBar.Init( - mSymbol, - mPeriod, - barIndex // - ); - - // - if (result) - { - // - iFiboUpper = GetFiboUpper(barIndex); - iFiboMiddle = GetFiboMiddle(barIndex); - iFiboLower = GetFiboLower(barIndex); - - // - isBullish = iBar.IsBullish() && - iBar.close > iFiboLower && - iBar.low < iFiboLower; - isBearish = iBar.IsBearish() && - iBar.close < iFiboUpper && - iBar.high > iFiboUpper; - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; - } - - /** - * Check Has Higher Low Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagHigherLow( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot vales[]; - count = ExtractPivots( - vales, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - vales[0].value > vales[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open > vales[0].value && - bar.close > vales[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - /** - * Check Has Lower Low Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagLowerLow( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot vales[]; - count = ExtractPivots( - vales, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - vales[0].value < vales[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open < vales[0].value && - bar.close < vales[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(vales); - XClean(pivots); - - // - return result; - } - - /** - * Check Has Higher High Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagHigherHigh( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot peaks[]; - count = ExtractPivots( - peaks, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - peaks[0].value > peaks[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open > peaks[0].value && - bar.close > peaks[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - /** - * Check Has Lower High Based On ZigZag ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagLowerHigh( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - XOHCL bar; - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - - // - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot peaks[]; - count = ExtractPivots( - peaks, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 2; - if (!result) - { - // - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - // - // Check Result ... - result = - peaks[0].value < peaks[1].value; - if (forceBarValidation) - { - // - result = - result && - bar.open < peaks[0].value && - bar.close < peaks[0].value; - } - - // - // Cleanup ... - bar.Clean(); - XClean(peaks); - XClean(pivots); - - // - return result; - } - - // - // SAR ... - - /** - * Check Specified Bar has SAR Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasSARSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double sars[]; - int count = CopySarState(barIndex, 2, sars); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - isBullish = - sars[0] >= 1 && - sars[1] <= -1; - - // - isBearish = - sars[0] <= -1 && - sars[1] >= 1; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(sars); - - // - return result; - } - - bool IsSarBullish(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double state = GetSarState(barIndex); - result = state >= 1; - - // - return result; - } - - bool IsSarBearish(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double state = GetSarState(barIndex); - result = state <= -1; - - // - return result; - } - - bool IsSarSwitchedToBullish(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - int pBarIndex = barIndex + 1; - - // - bool isBullish = IsSarBullish(barIndex); - bool isPBullish = IsSarBullish(pBarIndex); - - // - result = isBullish && - !isPBullish; - - // - return result; - } - - bool IsSarSwitchedToBearish(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - int pBarIndex = barIndex + 1; - - // - bool isBearish = IsSarBearish(barIndex); - bool isPBearish = IsSarBearish(pBarIndex); - - // - result = isBearish && - !isPBearish; - - // - return result; - } - - // - // PV ... - - bool IsPeakSame(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double iC = GetPeak(barIndex); - double iP = GetPeak(barIndex + 1); - - // - result = iC == iP && - NotEmptyZero(iC); - - // - return result; - } - - bool IsValeSame(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double iC = GetVale(barIndex); - double iP = GetVale(barIndex + 1); - - // - result = iC == iP && - NotEmptyZero(iC); - - // - return result; - } - - /** - * Check Peak Happens over Last ... - * - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsPeakOverLast(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Reading Values ... - - // - double iPeak = GetPeak(barIndex); - double pPeak = GetPeak(barIndex + 1); - - // - result = NotEmptyZero(iPeak) && - iPeak > pPeak; - - // - return result; - } - - /** - * Check Vale Happens over Last ... - * - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsValeOverLast(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Reading Values ... - - // - double iVale = GetVale(barIndex); - double pVale = GetVale(barIndex + 1); - - // - result = NotEmptyZero(iVale) && - iVale > pVale; - - // - return result; - } - - /** - * Check Peak Happens under Last ... - * - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsPeakUnderLast(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Reading Values ... - - // - double iPeak = GetPeak(barIndex); - double pPeak = GetPeak(barIndex + 1); - - // - result = NotEmptyZero(iPeak) && - iPeak < pPeak; - - // - return result; - } - - /** - * Check Vale Happens under Last ... - * - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool IsValeUnderLast(int barIndex = 0) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Reading Values ... - - // - double iVale = GetVale(barIndex); - double pVale = GetVale(barIndex + 1); - - // - result = NotEmptyZero(iVale) && - iVale < pVale; - - // - return result; - } - - /** - * Detect Last Peak Change ... - * - * @param index: int, reference to hold change index ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastPeakOverLast( - int &index, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Loop ... - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsPeakOverLast(idx); - if (result) - { - // - index = idx; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Detect Last Peak Change ... - * - * @param index: int, reference to hold change index ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastPeakUnderLast( - int &index, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Loop ... - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsPeakUnderLast(idx); - if (result) - { - // - index = idx; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Detect Last Vale Change ... - * - * @param index: int, reference to hold change index ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastValeOverLast( - int &index, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Loop ... - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsValeOverLast(idx); - if (result) - { - // - index = idx; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Detect Last Vale Change ... - * - * @param index: int, reference to hold change index ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastValeUnderLast( - int &index, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Loop ... - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsValeUnderLast(idx); - if (result) - { - // - index = idx; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Count Same Peaks ... - * - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountSamePeaks( - int barIndex = 0, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - double iPeak = EMPTY_VALUE; - double peak = GetPeak(barIndex); - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - iPeak = GetPeak(idx); - has = peak == iPeak; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - /** - * Count Same Vales ... - * - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountSameVales( - int barIndex = 0, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - double iVale = EMPTY_VALUE; - double vale = GetVale(barIndex); - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - iVale = GetVale(idx); - has = vale == iVale; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - bool HasPVConsolidationZone( - XBoxZone &zone, - int barIndex = 0, - bool forcePVBreak = false, - bool forceHasSarSwitch = false // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - bool isPeakSame = IsPeakSame(barIndex); - bool isValeSame = IsValeSame(barIndex); - result = !(isPeakSame && - isValeSame); - if (!result) - { - return result; - } - - // - double iPeak = EMPTY_VALUE; - double iVale = EMPTY_VALUE; - - // - int idx = barIndex; - bool canLookup = true; - while (canLookup) - { - // - idx++; - isPeakSame = IsPeakSame(idx); - isValeSame = IsValeSame(idx); - result = isPeakSame && - isValeSame; - if (!result) - { - // - zone.from = GetBarTime(mSymbol, mPeriod, idx); - break; - } - - // - if (idx == barIndex + 1) - { - // - zone.to = GetBarTime( - mSymbol, - mPeriod, - idx // - ); - } - - // - zone.from = GetBarTime( - mSymbol, - mPeriod, - idx // - ); - - // - iPeak = GetPeak(idx); - iVale = GetVale(idx); - - // - zone.lower = - !NotEmptyZero(zone.lower) - ? iVale - : MathMin(zone.lower, iVale); - - // - zone.upper = - !NotEmptyZero(zone.upper) - ? iPeak - : MathMax(zone.upper, iPeak); - } - - // - // Validating Zone Params ... - result = - // - IsXValid(zone.to) && - IsXValid(zone.from) && - zone.from < zone.to && - // - NotEmptyZero(zone.lower) && - NotEmptyZero(zone.upper) && - zone.upper > zone.lower - // - ; - - // - // Prepare Zone ... - if (result) - { - // - iPeak = GetPeak(barIndex); - iVale = GetVale(barIndex); - bool isPeakOverLast = IsPeakOverLast(barIndex); - bool isValeUnderLast = IsValeUnderLast(barIndex); - bool isValeBreak = iVale < zone.lower; - bool isPeakBreak = iPeak > zone.upper; - bool isPVBreak = isPeakBreak || - isValeBreak; - - // - zone.at = GetBarTime(mSymbol, mPeriod, barIndex); - zone.symbol = mSymbol; - zone.period = mPeriod; - zone.dir = (isPeakOverLast && !isValeUnderLast && isPVBreak) - ? X_DIRECTION_BULLISH - : (isValeUnderLast && !isPeakOverLast && isPVBreak) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - zone.type = ToXString(X_BAR_PATTERN_CONSOLIDATION); - - // - // Refine Zone Upper and Lower ... - if (zone.IsValid()) - { - // - XOHCL iBar; - int zoneLoopback = zone.FromIndex() - zone.ToIndex(); - result = zone.ToBar(iBar) && - IsValidSize(zoneLoopback); - if (result) - { - // - double zoneLL = iBar.FindLowest(zoneLoopback, MODE_LOW); - double zoneHH = iBar.FindHighest(zoneLoopback, MODE_HIGH); - result = NotEmptyZero(zoneLL) && - NotEmptyZero(zoneHH); - if (result) - { - // - zone.lower = zone.lower == zoneLL - ? zone.lower - : MathMax(zone.lower, zoneLL); - - // - zone.upper = zone.upper == zoneHH - ? zone.upper - : MathMin(zone.upper, zoneHH); - } - } - - // - iBar.Clean(); - } - - // - // Validate ... - result = zone.IsValid(); - } - - // - // Validate Zones From ... - if (result) - { - // - int idx = zone.FromIndex(); - - // - iPeak = GetPeak(idx); - iVale = GetVale(idx); - - // - bool isValeOverLast = IsValeOverLast(idx); - bool isPeakUnderLast = IsPeakUnderLast(idx); - - // - result = - result && - (zone.IsBullish() - ? !isPeakUnderLast - : zone.IsBearish() - ? !isValeOverLast - : false); - } - - // - // Apply Forces ... - - // - // PV Break ... - // Peak or Vale must Breaked at Bar ... - if (result && forcePVBreak) - { - // - bool isPVBreaked = - (zone.IsBullish() && IsPeakOverLast(barIndex)) || - (zone.IsBearish() && IsValeUnderLast(barIndex)); - - // - result = result && - isPVBreaked; - } - - // - // Other Loop based Forces ... - if (result && (forceHasSarSwitch)) - { - - // - bool hasSarSwitch = false; - - // - int start = zone.ToIndex(); - int end = zone.FromIndex(); - for (int i = start; i <= end; i++) - { - // - // Check Sar Switches ... - if (forceHasSarSwitch && !hasSarSwitch) - { - // - hasSarSwitch = - zone.IsBullish() - ? IsSarSwitchedToBullish(i) - : IsSarSwitchedToBearish(i); - } - } - - // - // Validate Forces ... - if (forceHasSarSwitch) - { - // - result = - result && - hasSarSwitch; - } - } - - // - // Cleanup ... - if (!result) - { - zone.Clean(); - } - - // - return result; - } - - // - // HK ... - - /** - * Check Specified Bar has HK Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasHKSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - double open[]; - int openCount = CopyHKOpen(barIndex, 2, open); - - // - double close[]; - int closeCount = CopyHKClose(barIndex, 2, close); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - int count = MathMin(openCount, closeCount); - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - - // - isBullish = - notEmpty && - open[0] < close[0] && - open[1] > close[1]; - - // - isBearish = - notEmpty && - open[0] > close[0] && - open[1] < close[1]; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - - // - return result; - } - - /** - * Check Specified Bar has HK Band Based Trend or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to holds trend direction, if exists ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, validation of trend ... - * - * @return ( bool ) - */ - bool HasHKBasedTrend( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 1); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - // Define Requirements ... - XOHCL iBar; - double hkUpper; - double hkLower; - bool has = false; - int bullishCount = 0; - int bearishCount = 0; - bool isBullish = false; - bool isBearish = false; - - // - // Count Bullish/Bearish Directions ... - int start = barIndex + 1; - int end = start + validationLength; - for (int i = start; i < end; i++) - { - // - // Reading Requirements ... - - // - // Read Indexed Bar ... - iBar.Clean(); - result = iBar.Init( - mSymbol, - mPeriod, - i // - ); - if (!result) - { - break; - } - - // - // Reading Values ... - hkUpper = GetHKBandUpper(i); - hkLower = GetHKBandLower(i); - result = NotEmptyZero(hkUpper) && - NotEmptyZero(hkLower); - if (!result) - { - return result; - } - - // - // Check Trend ... - - // - // Bullish ... - isBullish = iBar.low > hkLower; - if (isBullish) - { - bullishCount++; - } - - // - // Bearish ... - isBearish = iBar.high < hkUpper; - if (isBearish) - { - bearishCount++; - } - - // - iBar.Clean(); - - // - } - - // - // Validate Results ... - isBullish = - bullishCount >= validationLength; - isBearish = - bearishCount >= validationLength; - - // - result = (isBullish && !isBearish) || - (isBearish && !isBullish); - - // - // Setting Direction if Has Trend ... - if (result) - { - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup ... - iBar.Clean(); - - // - return result; - } - - /** - * Check Specified Bar has HK Band Based Trend Switch or not ... - * - * @param dir: ENUM_X_DIRECTION, reference to holds trend direction, if exists ... - * @param barIndex: int, Specified Bar Index ... - * @param validationLength: int, validation of trend ... - * - * @return ( bool ) - */ - bool IsHKBasedTrendSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int validationLength = 5 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 1); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // Do ... - - // - bool hasTrend = HasHKBasedTrend( - dir, - barIndex, - validationLength // - ); - bool isBullish = hasTrend && - IsXBullish(dir); - bool isBearish = hasTrend && - IsXBearish(dir); - - // - bool hasPTrend = HasHKBasedTrend( - dir, - barIndex + 1, - validationLength // - ); - bool isPBullish = hasPTrend && - IsXBullish(dir); - bool isPBearish = hasPTrend && - IsXBearish(dir); - - // - dir = X_DIRECTION_NONE; - - // - // Checking Result ... - isBullish = isBullish && !isPBullish; - isBearish = isBearish && !isPBearish; - - // - result = - (isBullish && !isBearish) || - (isBearish && !isBullish); - if (result) - { - // - dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup ... - - // - return result; - } - - /** - * Check if Price Over HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsOverHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandUpper(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price > value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check if Price Over HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsOverHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandLower(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price > value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check if Price Under HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsUnderHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandUpper(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price < value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check if Price Under HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsUnderHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - XOHCL bar; - result = bar.Init(mSymbol, mPeriod, barIndex); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - double price = bar.GetPrice(priceType); - double value = GetHKBandLower(barIndex); - result = NotEmptyZero(price) && - NotEmptyZero(value) && - price < value; - - // - // Cleanup ... - bar.Clean(); - - // - return result; - } - - /** - * Check Price Switched Over HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsSwitchedOverHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsOverHKBandUpper(priceType, barIndex); - bool isPBarPassed = !IsOverHKBandUpper(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; - } - - /** - * Check Price Switched Under HK Band Upper or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsSwitchedUnderHKBandUpper( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsUnderHKBandUpper(priceType, barIndex); - bool isPBarPassed = !IsUnderHKBandUpper(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; - } - - /** - * Check Price Switched Over HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsSwitchedOverHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_LOW, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsOverHKBandLower(priceType, barIndex); - bool isPBarPassed = !IsOverHKBandLower(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; - } - - /** - * Check Price Switched Under HK Band Lower or not ... - * - * @param priceType: ENUM_X_PRICE, Specified Price type ... - * @param barIndex: int, Specified Bar index ... - * - * @return ( bool ) - */ - bool IsSwitchedUnderHKBandLower( - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int pBarIndex = barIndex + 1; - bool isBarPassed = IsUnderHKBandLower(priceType, barIndex); - bool isPBarPassed = !IsUnderHKBandLower(priceType, pBarIndex); - - // - result = isBarPassed && isPBarPassed; - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastOverHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsOverHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastUnderHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsUnderHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastOverHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsOverHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band ... - * - * @param index: int, reference to holds index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastUnderHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsUnderHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastSwitchedOverHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedOverHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastSwitchedUnderHKBandUpper( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedUnderHKBandUpper(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastSwitchedOverHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedOverHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Previous HK Band Switch ... - * - * @param index: int, reference to holds switched index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ - bool FindLastSwitchedUnderHKBandLower( - int &index, - ENUM_X_PRICE priceType = X_PRICE_HIGH, - int barIndex = 0, - int loopback = 500 // - ) - { - // - bool result = false; - - // - // Prepare ... - index = -1; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - IsXValid(priceType); - if (!result) - { - return result; - } - - // - // Do ... - - // - int idx = barIndex; - while (idx < barIndex + loopback) - { - // - idx++; - result = IsSwitchedUnderHKBandLower(priceType, idx); - if (result) - { - // - index = idx - 1; - break; - } - } - - // - result = IsValidIndex(index); - - // - // Cleanup ... - - // - return result; - } - - /** - * Count Over HK Band Bars ... - * - * @param barIndex: int, Specified Bar Index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountOverHKBandLower( - int barIndex = 0, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid() && - IsXValid(priceType); - if (!has) - { - return result; - } - - // - XOHCL iBar; - int idx = barIndex; - double iValue = EMPTY_VALUE; - double iPrice = EMPTY_VALUE; - while (idx < barIndex + loopback) - { - // - idx++; - iBar.Clean(); - has = iBar.Init(mSymbol, mPeriod, idx); - if (!has) - { - break; - } - - // - iValue = GetHKBandLower(idx); - iPrice = iBar.GetPrice(priceType); - - // - has = iPrice > iValue; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - /** - * Count Under HK Band Bars ... - * - * @param barIndex: int, Specified Bar Index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountUnderHKBandLower( - int barIndex = 0, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid() && - IsXValid(priceType); - if (!has) - { - return result; - } - - // - XOHCL iBar; - int idx = barIndex; - double iValue = EMPTY_VALUE; - double iPrice = EMPTY_VALUE; - while (idx < barIndex + loopback) - { - // - idx++; - iBar.Clean(); - has = iBar.Init(mSymbol, mPeriod, idx); - if (!has) - { - break; - } - - // - iValue = GetHKBandLower(idx); - iPrice = iBar.GetPrice(priceType); - - // - has = iPrice < iValue; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - /** - * Count Over HK Band Bars ... - * - * @param barIndex: int, Specified Bar Index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountOverHKBandUpper( - int barIndex = 0, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid() && - IsXValid(priceType); - if (!has) - { - return result; - } - - // - XOHCL iBar; - int idx = barIndex; - double iValue = EMPTY_VALUE; - double iPrice = EMPTY_VALUE; - while (idx < barIndex + loopback) - { - // - idx++; - iBar.Clean(); - has = iBar.Init(mSymbol, mPeriod, idx); - if (!has) - { - break; - } - - // - iValue = GetHKBandUpper(idx); - iPrice = iBar.GetPrice(priceType); - - // - has = iPrice > iValue; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - /** - * Count Under HK Band Bars ... - * - * @param barIndex: int, Specified Bar Index ... - * @param priceType: ENUM_X_PRICE, Specified Price Type ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( int ) - */ - int CountUnderHKBandUpper( - int barIndex = 0, - ENUM_X_PRICE priceType = X_PRICE_CLOSE, - int loopback = 500 // - ) - { - // - int result = 0; - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid() && - IsXValid(priceType); - if (!has) - { - return result; - } - - // - XOHCL iBar; - int idx = barIndex; - double iValue = EMPTY_VALUE; - double iPrice = EMPTY_VALUE; - while (idx < barIndex + loopback) - { - // - idx++; - iBar.Clean(); - has = iBar.Init(mSymbol, mPeriod, idx); - if (!has) - { - break; - } - - // - iValue = GetHKBandUpper(idx); - iPrice = iBar.GetPrice(priceType); - - // - has = iPrice < iValue; - if (has) - { - result++; - } - if (!has) - { - break; - } - } - - // - return result; - } - - // - // ZigZag Pivots With Liquidity ... - - /** - * Check ZigZag has Lower Low by Liquidity or Not ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagLowerLowByLiquidity( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - XOHCL bar; - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsVale(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot selected[]; - count = ExtractPivots( - selected, - pivots, - X_PIVOT_TYPE_VALE // - ); - result = IsValidSize(count) && - count >= 3; - if (!result) - { - // - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - // - // Do Calculations ... - result = - // - // Check Pivot ... - selected[0].value < selected[1].value && - // - // Check Liquidity ... - selected[1].value > selected[2].value && - // - // Check Bar Place ... - (!forceBarValidation - ? true - : bar.open > selected[0].value && - bar.close > selected[0].value); - - // - // Cleanup ... - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - /** - * Check ZigZag has Higher High by Liquidity or Not ... - * - * @param barIndex: int, Specified Bar Index ... - * @param forceBarValidation: bool, Force Bar Price based on Pivot ... - * - * @return ( bool ) - */ - bool HasZigZagHigherHighByLiquidity( - int barIndex = 0, - bool forceBarValidation = false // - ) - { - // - bool result = false; - - // - // Normalize ... - XOHCL bar; - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex // - ); - if (!result) - { - // - bar.Clean(); - return result; - } - - // - // Extract Pivots ... - XPivot pivots[]; - int count = ExtractZigZagPivots( - pivots, - barIndex, - 10, - 200 // - ); - - // - // Validate Pivots and Nearest Pivot is Low ... - result = IsValidSize(count) && - pivots[0].IsPeak(); - if (!result) - { - // - bar.Clean(); - XClean(pivots); - - // - return result; - } - - // - // Extract Directional Pivots ... - XPivot selected[]; - count = ExtractPivots( - selected, - pivots, - X_PIVOT_TYPE_PEAK // - ); - result = IsValidSize(count) && - count >= 3; - if (!result) - { - // - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - // - // Do Calculations ... - result = - // - // Check Pivot ... - selected[0].value > selected[1].value && - // - // Check Liquidity ... - selected[1].value < selected[2].value && - // - // Check Bar Place ... - (!forceBarValidation - ? true - : bar.open < selected[0].value && - bar.close < selected[0].value); - - // - // Cleanup ... - bar.Clean(); - XClean(pivots); - XClean(selected); - - // - return result; - } - - // - // Extractions ... - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( int ) - */ - int ExtractPVPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - bool lookupPeaks = true; - bool lookupVales = true; - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - int samePeaksCount = 0; - int sameValesCount = 0; - double tmpPeaksBuffer[]; - double tmpValesBuffer[]; - string symbol = GetSymbol(); - double iPValue = EMPTY_VALUE; - double iVValue = EMPTY_VALUE; - double pPValue = EMPTY_VALUE; - double pVValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Detecting ... - - // - // Peak ... - if (lookupPeaks) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_PEAK_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpPeaksBuffer // Buffer ... - ); - ArraySetAsSeries(tmpPeaksBuffer, true); - - // - // Reading Values ... - iPValue = tmpPeaksBuffer[0]; - pPValue = tmpPeaksBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iPValue)) - { - // - // Check New Peak ... - has = - !NotEmptyZero(pPValue) - ? true - : iPValue != pPValue; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - iPValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : samePeaksCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iPValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_PV); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - samePeaksCount = 0; - } - else if (iPValue == pPValue) - { - samePeaksCount++; - } - } - } - - // - // Vale ... - if (lookupVales) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_VALE_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpValesBuffer // Buffer ... - ); - ArraySetAsSeries(tmpValesBuffer, true); - - // - // Reading Values ... - iVValue = tmpValesBuffer[0]; - pVValue = tmpValesBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iVValue)) - { - // - // Check New Vale ... - has = - !NotEmptyZero(pVValue) - ? true - : iVValue != pVValue; - if (has) - { - // - // Calculate and Validate Type ... - // Vales Only Valid when Confirmed by Bar Low ... - iType = - iVValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : sameValesCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iVValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_PV); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - sameValesCount = 0; - } - else if (iVValue == pVValue) - { - sameValesCount++; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractMAPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - double validCrossDiffMultiplier = 1, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double fast[]; - double slow[]; - XPivot iPivot; - int count = 0; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - double iFValue = EMPTY_VALUE; - double pFValue = EMPTY_VALUE; - double iSValue = EMPTY_VALUE; - double pSValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - int fastCount = CopyMAFast(idx, 2, fast); - int slowCount = CopyMASlow(idx, 2, slow); - count = MathMin(fastCount, slowCount); - has = IsValidSize(count); - - // - // Reading Values ... - - // - iFValue = fast[0]; - pFValue = fast[1]; - - // - iSValue = slow[0]; - pSValue = slow[1]; - - // - // Validate Value ... - has = - HasMACross( - iDir, - idx, - validCrossDiffMultiplier // - ) && - NotEmptyZero(iFValue) && - NotEmptyZero(iSValue) && - NotEmptyZero(pFValue) && - NotEmptyZero(pSValue); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(iFValue, iSValue) - : MathMin(iFValue, iSValue); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_MA_CROSS); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - iPivot.Clean(); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractHKPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double open[]; - XPivot iPivot; - int count = 0; - double close[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - int openCount = CopyHKOpen(idx, 2, open); - int closeCount = CopyHKClose(idx, 2, close); - count = MathMin(openCount, closeCount); - has = IsValidSize(count); - - // - // Validate Value ... - has = - HasHKSwitch( - iDir, - idx // - ) && - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_HK); - - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(open[0], close[0]) - : MathMin(open[0], close[0]); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - XClean(open); - XClean(close); - iPivot.Clean(); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractSARPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XOHCL pBar; - XPivot iPivot; - bool has = false; - double tmpSarBuffer[]; - int idx = barIndex - 1; - string symbol = GetSymbol(); - double iValue = EMPTY_VALUE; - double pValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - has = - has && - iBar.GetPreviousBar(pBar); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_SAR_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpSarBuffer // Buffer ... - ); - ArraySetAsSeries(tmpSarBuffer, true); - - // - // Reading Values ... - iValue = tmpSarBuffer[0]; - pValue = tmpSarBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iValue)) - { - // - // Check Sar Direction Changed ... - isSwitchedToBullish = iValue < iBar.low && - pValue > pBar.high; - isSwitchedToBearish = iValue > iBar.high && - pValue < pBar.low; - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_SAR_SWITCH); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractZigZagPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - double tmpZigZagBuffer[]; - double iValue = EMPTY_VALUE; - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_ZIGZAG_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 1, // Number of Requirements ... - tmpZigZagBuffer // Buffer ... - ); - ArraySetAsSeries(tmpZigZagBuffer, true); - - // - // Read and Validate Value ... - iValue = tmpZigZagBuffer[0]; - has = NotEmptyZero(iValue); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Type ... - iType = - iValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : iValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Dir ... - iDir = - IsXVale(iType) - ? X_DIRECTION_BULLISH - : IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(iDir); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - iPivot.prefix = ToXString(XFIMA_PIVOT_ZIGZAG); - - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - return result; - } - - /** - * Extract Validated Zones ... - * - * @param zones: XBoxZone, collection reference to holds results ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFZones: int, required Number of Zones ... - * @param breakValidLength: int, Breake Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * @param shadowMultiplier: double a Shadow Multiplier for Validation ... - * @param validationStrength: double, Minimum Strngth Multiplier in Point to Validate ... - * @param validationLength: int, Validation Length of Zones ... - * @param maxAllowedLoopbackLength: int, max Allowed Loopback Length ... - * - * @return ( int ) - */ - int ExtractHKZones( - XBoxZone &zones[], - int barIndex = 0, - int requiredNumberOFZones = 50, - int breakValidLength = 3, - bool validateFakeBreakes = true, - double shadowMultiplier = 3, - double validationStrength = 1, - int validationLength = 21, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(zones); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 7); - shadowMultiplier = NormalizeDouble(shadowMultiplier, 1); - validationStrength = NormalizeDouble(validationStrength, 1); - requiredNumberOFZones = NormalizeInt(requiredNumberOFZones, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 100); - - // - // Reading Values ... - - // - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - double minAllowedStrength = (validationStrength * GetPoints(symbol)); - - // - int count = 0; - XBoxZone zone; - bool has = false; - int start = barIndex; - bool isBullish = false; - bool isBearish = false; - double up = EMPTY_VALUE; - double low = EMPTY_VALUE; - double open = EMPTY_VALUE; - double high = EMPTY_VALUE; - double down = EMPTY_VALUE; - double body = EMPTY_VALUE; - double close = EMPTY_VALUE; - double range = EMPTY_VALUE; - bool lowShadowPassed = false; - bool highShadowPassed = false; - double lowShadow = EMPTY_VALUE; - double highShadow = EMPTY_VALUE; - double startHKLow = EMPTY_VALUE; - double startHKOpen = EMPTY_VALUE; - double startHKHigh = EMPTY_VALUE; - double startHKClose = EMPTY_VALUE; - ENUM_X_DIRECTION dir = X_DIRECTION_NONE; - int end = start + maxAllowedLoopbackLength; - for (int i = start; i < end; i++) - { - // - // Cleanup ... - zone.Clean(); - dir = X_DIRECTION_NONE; - - // - // Reading HK Buffesr ... - low = GetHKLow(i); - open = GetHKOpen(i); - high = GetHKHigh(i); - close = GetHKClose(i); - - // - // Initialized Start Bar ... - if (i == start) - { - // - startHKLow = low; - startHKOpen = open; - startHKHigh = high; - startHKClose = close; - } - - // - // Check Direction ... - isBullish = open < close; - isBearish = open > close; - dir = - (isBullish && !isBearish) - ? X_DIRECTION_BULLISH - : (isBearish && !isBullish) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(dir); - if (!has) - { - continue; - } - - // - // Calculate Requirements for Processing ... - up = isBullish - ? close - : open; - down = isBullish - ? open - : close; - body = MathAbs(up - down); - range = high - low; - highShadow = high - up; - lowShadow = down - low; - - // - // Detecting Shadows ... - - // - // Low Shadow ... - lowShadowPassed = lowShadow >= (shadowMultiplier * highShadow); - - // - // High Shadow ... - highShadowPassed = highShadow >= (shadowMultiplier * lowShadow); - - // - has = (lowShadowPassed && !highShadowPassed) || - (highShadowPassed && !lowShadowPassed); - if (!has) - { - continue; - } - - // - // Filling Zone ... - - // - zone.symbol = symbol; - zone.period = period; - zone.from = GetBarTime( - zone.symbol, - zone.period, - i // - ); - zone.dir = lowShadowPassed - ? X_DIRECTION_BULLISH - : highShadowPassed - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - zone.upper = - IsXBullish(zone.dir) - ? down - : IsXBearish(zone.dir) - ? high - : EMPTY_VALUE; - - // - zone.lower = - IsXBullish(zone.dir) - ? low - : IsXBearish(zone.dir) - ? up - : EMPTY_VALUE; - - // - zone.to = TimeCurrent(); - zone.type = ToXString(XFIMA_PIVOT_HK) + "_" + (IsXBullish(zone.dir) ? "Support" : IsXBearish(zone.dir) ? "Resistance" - : ""); - - // - // Validate ... - has = - zone.IsValid() && - HasDirection(zone.dir) && - NotEmptyZero(zone.upper) && - NotEmptyZero(zone.lower) && - (zone.IsBullish() - ? startHKLow > zone.upper - : startHKHigh < zone.lower) && - (zone.upper - zone.lower) >= minAllowedStrength && - ValidateHKZone(zone, validationLength, breakValidLength, validateFakeBreakes); - if (has) - { - // - AddIfNotExists( - zone, - zones // - ); - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - // Validating ... - result = ArraySize(zones); - has = IsValidSize(result) && - result >= requiredNumberOFZones; - if (has) - { - break; - } - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - return result; - } - - // - // Values Retrievers ... - - /** - * Filling Specified Bar index Boundary Values ... - * - * @param dest: double, reference collection to hold boundary Values ... - * @param barIndex: int, Specified Bar's Index ... - * @param containsFastSlow: bool, Contains XMA Fast / Slow ... - * @param containsMABand: bool, Contains XMA Boundary Upper / Lower ... - * @param containsHKBound: bool, Contains XHK Boundary Upper / Lower ... - * @param containsPBBand: bool, Contains XPB Boundary Upper / Lower ... - * @param containsFiboLevels: nool, Contains XFIBO Levels ... - * - * @return ( int ) - */ - int FillBoundaryValues( - double &dest[], - int barIndex = 0, - bool containsFastSlow = true, - bool containsMABand = true, - bool containsHKBound = true, - bool containsPBBand = true, - bool containsFiboLevels = false // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - // Read and Validate Values ... - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - double fiboUpper = GetFiboUpper(barIndex); - double fiboLower = GetFiboLower(barIndex); - double fiboMiddle = GetFiboMiddle(barIndex); - - // - has = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(fiboLower) && - NotEmptyZero(fiboUpper) && - NotEmptyZero(fiboMiddle) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower); - if (!has) - { - return result; - } - - // - // Fill Dest ... - - // - // XMA Fast / Slow ... - if (containsFastSlow) - { - // - Add(fast, dest); - Add(slow, dest); - } - - // - // XMA Bound ... - if (containsMABand) - { - // - Add(maBandUpper, dest); - Add(maBandLower, dest); - } - - // - // XHK Band ... - if (containsHKBound) - { - // - Add(hkBandUpper, dest); - Add(hkBandLower, dest); - } - - // - // XPB Band ... - if (containsPBBand) - { - // - Add(pbBandUpper, dest); - Add(pbBandLower, dest); - } - - // - // XFIBO Zones ... - if (containsFiboLevels) - { - // - Add(fiboLower, dest); - Add(fiboUpper, dest); - Add(fiboMiddle, dest); - } - - // - result = ArraySize(dest); - - // - return result; - } - - /** - * Retrieve Fast, Slow, MA Band Upper/Lower, HK Band Upper/Lower and PB Band Upper/Lower Min/Max ... - * - * @param min: double, minimum value ... - * @param max: double, maximum value ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool GetBoundaryValues( - double &min, - double &max, - int barIndex = 0, - bool containsFastSlow = true, - bool containsMABand = true, - bool containsHKBound = true, - bool containsPBBand = true, - bool containsFiboLevels = false // - ) - { - // - bool result = false; - - // - // Prepare ... - min = EMPTY_VALUE; - max = EMPTY_VALUE; - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - double fast = GetMAFast(barIndex); - double slow = GetMASlow(barIndex); - - // - double maBandUpper = GetMABandUpper(barIndex); - double maBandLower = GetMABandLower(barIndex); - - // - double pbBandUpper = GetPBBandUpper(barIndex); - double pbBandLower = GetPBBandLower(barIndex); - - // - double hkBandUpper = GetHKBandUpper(barIndex); - double hkBandLower = GetHKBandLower(barIndex); - - // - double fiboUpper = GetFiboUpper(barIndex); - double fiboLower = GetFiboLower(barIndex); - double fiboMiddle = GetFiboMiddle(barIndex); - - // - result = - NotEmptyZero(fast) && - NotEmptyZero(slow) && - NotEmptyZero(fiboLower) && - NotEmptyZero(fiboUpper) && - NotEmptyZero(fiboMiddle) && - NotEmptyZero(maBandUpper) && - NotEmptyZero(maBandLower) && - NotEmptyZero(pbBandUpper) && - NotEmptyZero(pbBandLower) && - NotEmptyZero(hkBandUpper) && - NotEmptyZero(hkBandLower); - if (!result) - { - return result; - } - - // - double values[]; - - // - if (containsFastSlow) - { - // - Add(fast, values); - Add(slow, values); - } - - // - if (containsMABand) - { - // - Add(maBandUpper, values); - Add(maBandLower, values); - } - - // - if (containsHKBound) - { - // - Add(hkBandUpper, values); - Add(hkBandLower, values); - } - - // - if (containsPBBand) - { - // - Add(pbBandUpper, values); - Add(pbBandLower, values); - } - - // - if (containsFiboLevels) - { - // - Add(fiboLower, values); - Add(fiboUpper, values); - Add(fiboMiddle, values); - } - - // - result = HasChild(values); - if (!result) - { - return result; - } - - // - min = GetMin(values); - max = GetMax(values); - - // - result = - NotEmptyZero(min) && - NotEmptyZero(max) && - min < max; - - // - return result; - } - - // - // Fast MA ... - - // - double GetMAFast( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_FAST_LINE, - barIndex // - ); - } - - // - int CopyMAFast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_FAST_LINE, - start, - count, - asSeries // - ); - } - - // - // Fast MA State ... - - // - double GetMAFastState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_FAST_STATE_LINE, - barIndex // - ); - } - - // - int CopyMAFastState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_FAST_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // Slow MA ... - - // - double GetMASlow( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_SLOW_LINE, - barIndex // - ); - } - - // - int CopyMASlow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_SLOW_LINE, - start, - count, - asSeries // - ); - } - - // - // Slow MA State ... - - // - double GetMASlowState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_SLOW_STATE_LINE, - barIndex // - ); - } - - // - int CopyMASlowState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_SLOW_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // Upper MA ... - - // - double GetMABandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_BAND_UPPER_LINE, - barIndex // - ); - } - - // - int CopyMABandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_BAND_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower MA ... - - // - double GetMABandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_BAND_LOWER_LINE, - barIndex // - ); - } - - // - int CopyMABandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_BAND_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // XPB ... - - // - // Upper PB ... - - // - double GetPBBandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PB_BAND_UPPER_LINE, - barIndex // - ); - } - - // - int CopyPBBandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PB_BAND_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower PB ... - - // - double GetPBBandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PB_BAND_LOWER_LINE, - barIndex // - ); - } - - // - int CopyPBBandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PB_BAND_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // Upper PB ... - - // - double GetPBRawBandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PB_BAND_RAW_UPPER_LINE, - barIndex // - ); - } - - // - int CopyPBRawBandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PB_BAND_RAW_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower PB ... - - // - double GetPBRawBandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PB_BAND_RAW_LOWER_LINE, - barIndex // - ); - } - - // - int CopyPBRawBandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PB_BAND_RAW_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // XATR ... - - // - // Upper ATR ... - - // - double GetATRBandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ATR_BAND_UPPER_LINE, - barIndex // - ); - } - - // - int CopyATRBandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ATR_BAND_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower ATR ... - - // - double GetATRBandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ATR_BAND_LOWER_LINE, - barIndex // - ); - } - - // - int CopyATRBandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ATR_BAND_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // ATR ... - - // - double GetATR( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ATR_LINE, - barIndex // - ); - } - - // - int CopyATR( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ATR_LINE, - start, - count, - asSeries // - ); - } - - // - // Upper ATR ... - - // - double GetATRRawBandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ATR_BAND_RAW_UPPER_LINE, - barIndex // - ); - } - - // - int CopyATRRawBandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ATR_BAND_RAW_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower ATR ... - - // - double GetATRRawBandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ATR_BAND_RAW_LOWER_LINE, - barIndex // - ); - } - - // - int CopyATRRawBandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ATR_BAND_RAW_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // SAR ... - - // - double GetSar( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SAR_LINE, - barIndex // - ); - } - - // - int CopySar( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SAR_LINE, - start, - count, - asSeries // - ); - } - - // - // SAR State ... - - // - double GetSarState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SAR_STATE_LINE, - barIndex // - ); - } - - // - int CopySarState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SAR_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // PEAK ... - - // - double GetPeak( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PEAK_LINE, - barIndex // - ); - } - - // - int CopyPeak( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PEAK_LINE, - start, - count, - asSeries // - ); - } - - // - // VALE ... - - // - double GetVale( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_VALE_LINE, - barIndex // - ); - } - - // - int CopyVale( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_VALE_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Zone ... - - // - // FIBO Upper ... - - // - double GetFiboUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_UPPER_LINE, - barIndex // - ); - } - - // - int CopyFiboUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Middle ... - - // - double GetFiboMiddle( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_MIDDLE_LINE, - barIndex // - ); - } - - // - int CopyFiboMiddle( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_MIDDLE_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Lower ... - - // - double GetFiboLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_LOWER_LINE, - barIndex // - ); - } - - // - int CopyFiboLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // ZigZag ... - - // - double GetZigZag( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ZIGZAG_LINE, - barIndex // - ); - } - - // - int CopyZigZag( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ZIGZAG_LINE, - start, - count, - asSeries // - ); - } - - // - // CYCLES Range ... - - // - // SHORT ... - - // - // HH ... - - // - double GetSHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SC_HH_LINE, - barIndex // - ); - } - - // - int CopySHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetSLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SC_LL_LINE, - barIndex // - ); - } - - // - int CopySLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // MEDIUM ... - - // - // HH ... - - // - double GetMHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MC_HH_LINE, - barIndex // - ); - } - - // - int CopyMHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetMLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MC_LL_LINE, - barIndex // - ); - } - - // - int CopyMLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // LONG ... - - // - // HH ... - - // - double GetLHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_LC_HH_LINE, - barIndex // - ); - } - - // - int CopyLHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_LC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetLLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_LC_LL_LINE, - barIndex // - ); - } - - // - int CopyLLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_LC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // HIND ... - - // - // HH ... - - // - double GetHHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HC_HH_LINE, - barIndex // - ); - } - - // - int CopyHHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetHLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HC_LL_LINE, - barIndex // - ); - } - - // - int CopyHLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK ... - - // - // XHK Open ... - - // - double GetHKOpen( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_OPEN_LINE, - barIndex // - ); - } - - // - int CopyHKOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_OPEN_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK High ... - - // - double GetHKHigh( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_HIGH_LINE, - barIndex // - ); - } - - // - int CopyHKHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_HIGH_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Low ... - - // - double GetHKLow( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_LOW_LINE, - barIndex // - ); - } - - // - int CopyHKLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_LOW_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Close ... - - // - double GetHKClose( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_CLOSE_LINE, - barIndex // - ); - } - - // - int CopyHKClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_CLOSE_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Color ... - - // - double GetHKColor( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_COLOR_LINE, - barIndex // - ); - } - - // - int CopyHKColor( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_COLOR_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Raw ... - - // - // XHK Raw Open ... - - // - double GetHKRawOpen( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_RAW_OPEN_LINE, - barIndex // - ); - } - - // - int CopyHKRawOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_RAW_OPEN_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Raw High ... - - // - double GetHKRawHigh( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_RAW_HIGH_LINE, - barIndex // - ); - } - - // - int CopyHKRawHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_RAW_HIGH_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Raw Low ... - - // - double GetHKRawLow( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_RAW_LOW_LINE, - barIndex // - ); - } - - // - int CopyHKRawLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_RAW_LOW_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Raw Close ... - - // - double GetHKRawClose( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_RAW_CLOSE_LINE, - barIndex // - ); - } - - // - int CopyHKRawClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_RAW_CLOSE_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Band ... - - // - // XHK Band Upper ... - - // - double GetHKBandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_BAND_UPPER_LINE, - barIndex // - ); - } - - // - int CopyHKBandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_BAND_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Band Lower ... - - // - double GetHKBandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_BAND_LOWER_LINE, - barIndex // - ); - } - - // - int CopyHKBandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_BAND_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - XFIMAInputs mInputs; // Inputs ... - - // - // XHK Helper ... - - /** - * Validate HK Zone ... - * - * @param zone: XBoxZone, reference to Specified Zone ... - * @param validationLength: int, Validation Length of Zones ... - * @param breakValidLength: int, Break Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * - * @return ( bool ) - */ - bool ValidateHKZone( - XBoxZone &zone, - int validationLength = 1, - int breakValidLength = 3, - bool validateFakeBreakes = true // - ) - { - // - bool result = false; - - // - // Normalize ... - validationLength = NormalizeInt(validationLength, 1); - breakValidLength = NormalizeInt(breakValidLength, 2); - - // - // Validate ... - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - // Requirements ... - double low = EMPTY_VALUE; - double open = EMPTY_VALUE; - double high = EMPTY_VALUE; - double close = EMPTY_VALUE; - - // - int count = 0; - int start = zone.FromIndex() + 1; - int end = start + validationLength; - - // - // Validate Before ... - for (int i = start; i < end; i++) - { - // - // Reading HK ... - low = GetHKLow(i); - high = GetHKHigh(i); - result = - NotEmptyZero(low) && - NotEmptyZero(high); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low > zone.lower - : high < zone.upper; - if (!result) - { - break; - } - } - - // - // Validating After ... - if (result) - { - // - start = zone.ToIndex() + 1; - count = zone.FromIndex() - start; - end = start + count; - for (int i = start; i < end; i++) - { - // - // Read HK ... - low = GetHKLow(i); - high = GetHKHigh(i); - result = - NotEmptyZero(low) && - NotEmptyZero(high); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low > zone.lower - : high < zone.upper; - if (!result) - { - // - // Check For Fake Breake ... - if (validateFakeBreakes && breakValidLength > 0) - { - // - result = i - 1 >= 0; - if (result) - { - // - for (int j = i - 1; j >= zone.ToIndex(); j--) - { - // - // Reading HK ... - close = GetHKClose(j); - result = NotEmptyZero(close); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? close > zone.upper - : close < zone.lower; - if (result) - { - // - result = MathAbs(j - i) <= breakValidLength; - if (result) - { - break; - } - } - } - } - } - - // - if (!result) - { - break; - } - } - } - } - - // - // Cleanup Resource ... - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.helper copy.mq5 b/Documents/BKP/x-saherelm.xfima.helper copy.mq5 deleted file mode 100644 index 00457858..00000000 --- a/Documents/BKP/x-saherelm.xfima.helper copy.mq5 +++ /dev/null @@ -1,3820 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XCXFIMAHelper -// Description: provides all Indicator -// Helper requirements ... -// -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.x-helper.class.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Definitions ... - -// -// Buffers ... -enum ENUM_XFIMA_BUFFERS -{ - XFIMA_MA_FAST_LINE = 0, - XFIMA_MA_FAST_COLOR_LINE = 1, - XFIMA_MA_FAST_STATE_LINE = 19, - XFIMA_MA_SLOW_LINE = 2, - XFIMA_MA_SLOW_COLOR_LINE = 3, - XFIMA_MA_SLOW_STATE_LINE = 20, - XFIMA_SAR_LINE = 4, - XFIMA_SAR_COLOR_LINE = 5, - XFIMA_SAR_STATE_LINE = 21, - XFIMA_PEAK_LINE = 6, - XFIMA_VALE_LINE = 7, - XFIMA_FIBO_UPPER_LINE = 8, - XFIMA_FIBO_MIDDLE_LINE = 9, - XFIMA_FIBO_LOWER_LINE = 10, - XFIMA_ZIGZAG_LINE = 11, - XFIMA_MA_BAND_UPPER_LINE = 12, - XFIMA_MA_BAND_LOWER_LINE = 13, - XFIMA_ZIGZAG_HIGHS_LINE = 30, - XFIMA_ZIGZAG_HIGHS_TIME_LINE = 31, - XFIMA_ZIGZAG_LOWS_LINE = 32, - XFIMA_ZIGZAG_LOWS_TIME_LINE = 33, - // - XFIMA_HK_OPEN_LINE = 14, - XFIMA_HK_HIGH_LINE = 15, - XFIMA_HK_LOW_LINE = 16, - XFIMA_HK_CLOSE_LINE = 17, - XFIMA_HK_COLOR_LINE = 18, - // 19 Ma Fast State - // 20 Ma Slow State - // 21 Sar State - XFIMA_SC_HH_LINE = 22, - XFIMA_SC_LL_LINE = 23, - XFIMA_MC_HH_LINE = 24, - XFIMA_MC_LL_LINE = 25, - XFIMA_LC_HH_LINE = 26, - XFIMA_LC_LL_LINE = 27, - XFIMA_HC_HH_LINE = 28, - XFIMA_HC_LL_LINE = 29, - // 30 ZigZag Highs - // 31 ZigZag Highs Time - // 32 ZigZag Lows - // 33 ZigZag Lows Time -}; - -// -// Input Models ... -struct XFIMAInputs -{ - // - // Props ... - - // - // Calculation ... - ENUM_X_PERIOD_METHOD scMethod; // How to Find Short Period - ENUM_TIMEFRAMES scPeriod; // Short Period - ENUM_X_PERIOD_METHOD mcMethod; // How to Find Medium Period - ENUM_TIMEFRAMES mcPeriod; // Medium Period - ENUM_X_PERIOD_METHOD lcMethod; // How to Find Long Period - ENUM_TIMEFRAMES lcPeriod; // Long Period - ENUM_X_PERIOD_METHOD hcMethod; // How to Find Hind Period - ENUM_TIMEFRAMES hcPeriod; // Hind Period - ENUM_SERIESMODE upperMode; // Peak Method - ENUM_SERIESMODE lowerMode; // Vale Method - ENUM_X_FIBO_LEVELS fiboUpperZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboLowerZoneLevel; // Lower Zone Level - double sarStep; // SAR Step - double sarMax; // SAR Maximum - ENUM_MA_METHOD maMethod; // MA Method - ENUM_APPLIED_PRICE maAppliedTo; // MA Applied To - int maFastLength; // Fast MA Length - int maSlowLength; // Slow MA Length - int maBandLength; // MA Band Length - int zigzagDepth; // ZigZag Depth - int zigzagDeviation; // ZigZag Deviation - int zigzagBackStep; // ZigZag Back Step - ENUM_X_PRICE zigzagUppersMode; // ZigZag High Detect Mode - ENUM_X_PRICE zigzagLowersMode; // ZigZag Low Detect Mode - - // - // Presentation ... - bool showPV; // Show PV - bool showHK; // Show HK - bool showSAR; // Show Sar - bool showMAFast; // Show MA Fast - bool showMASlow; // Show MA Slow - bool showMABand; // Show MA Band - bool showZigZag; // Show ZigZag - bool showFiboZone; // Show Fibo Zone - int startCalculationForLastBars; // Calculate Last n Bars - int sarArrowCode; // Parabolic Sar Arrow Code - int peakArrowCode; // Peaks Arrow Code - int valeArrowCode; // Vales Arrow Code - - // - // Constructor(s) ... - XFIMAInputs() - { - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - ZeroMemory(this); - } - - // - // Default ... - void Default() - { - // - // Calculations ... - scMethod = X_PERIOD_AUTO; // How to Find Short Period - scPeriod = NULL; // Short Period - mcMethod = X_PERIOD_AUTO; // How to Find Medium Period - mcPeriod = NULL; // Medium Period - lcMethod = X_PERIOD_AUTO; // How to Find Long Period - lcPeriod = NULL; // Long Period - hcMethod = X_PERIOD_AUTO; // How to Find Hind Period - hcPeriod = NULL; // Hind Period - upperMode = MODE_HIGH; // Peak Method - lowerMode = MODE_LOW; // Vale Method - fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level - fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Upper Zone Level - fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level - sarStep = 0.02; // SAR Step - sarMax = 0.2; // SAR Maximum - maMethod = MODE_EMA; // MA Method - maAppliedTo = PRICE_CLOSE; // MA Applied To - maFastLength = 7; // Fast MA Length - maSlowLength = 20; // Slow MA Length - maBandLength = 7; // MA Band Length - zigzagDepth = 12; // ZigZag Depth - zigzagDeviation = 5; // ZigZag Deviation - zigzagBackStep = 3; // ZigZag Back Step - zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode - zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - - // - // Presentation ... - showPV = true; // Show PV - showHK = true; // Show HK - showSAR = true; // Show Sar - showMAFast = true; // Show MA Fast - showMASlow = true; // Show MA Slow - showMABand = true; // Show MA Band - showZigZag = true; // Show ZigZag - showFiboZone = true; // Show Fibo Zone - startCalculationForLastBars = 1500; // Calculate Last n Bars - sarArrowCode = 159; // Parabolic Sar Arrow Code - peakArrowCode = 159; // Peaks Arrow Code - valeArrowCode = 159; // Vales Arrow Code - } - - // - // Hide all Visible Buffers ... - void Hide() - { - // - showPV = false; - showHK = false; - showSAR = false; - showMAFast = false; - showMASlow = false; - showMABand = false; - showZigZag = false; - showFiboZone = false; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maBandLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsSpecifiedValid(scMethod, scPeriod) && - IsSpecifiedValid(mcMethod, mcPeriod) && - IsSpecifiedValid(lcMethod, lcPeriod) && - IsSpecifiedValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; - } -}; - -// -// Conditions ... -struct XFIMAConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - datetime to; - datetime from; - XOHCL bars[]; - - // - // Buffers ... - double maFastBuffer[]; - double maFastColorBuffer[]; - double maFastStateBuffer[]; - double maSlowBuffer[]; - double maSlowColorBuffer[]; - double maSlowStateBuffer[]; - double maBandUpperBuffer[]; - double maBandLowerBuffer[]; - double sarBuffer[]; - double sarColorBuffer[]; - double sarStateBuffer[]; - double peakBuffer[]; - double valeBuffer[]; - double fiboUpperBuffer[]; - double fiboMiddleBuffer[]; - double fiboLowerBuffer[]; - double zigzagBuffer[]; - double sHHBuffer[]; - double sLLBuffer[]; - double mHHBuffer[]; - double mLLBuffer[]; - double lHHBuffer[]; - double lLLBuffer[]; - double hHHBuffer[]; - double hLLBuffer[]; - double highsBuffer[]; - double highsTimeBuffer[]; - double lowsBuffer[]; - double lowsTimeBuffer[]; - double hkOpenBuffer[]; - double hkHighBuffer[]; - double hkLowBuffer[]; - double hkCloseBuffer[]; - double hkColorBuffer[]; - - // - // Conditions ... - - // - // Constructor ... - XFIMAConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - // Commons ... - to = NULL; - from = NULL; - time = NULL; - symbol = NULL; - period = NULL; - - // - // Buffers ... - - // - SpecifiedClean(bars); - - // - SpecifiedClean(maFastBuffer); - SpecifiedClean(maFastColorBuffer); - SpecifiedClean(maFastStateBuffer); - SpecifiedClean(maSlowBuffer); - SpecifiedClean(maSlowColorBuffer); - SpecifiedClean(maSlowStateBuffer); - SpecifiedClean(maBandUpperBuffer); - SpecifiedClean(maBandLowerBuffer); - SpecifiedClean(sarBuffer); - SpecifiedClean(sarColorBuffer); - SpecifiedClean(sarStateBuffer); - SpecifiedClean(peakBuffer); - SpecifiedClean(valeBuffer); - SpecifiedClean(fiboUpperBuffer); - SpecifiedClean(fiboMiddleBuffer); - SpecifiedClean(fiboLowerBuffer); - SpecifiedClean(zigzagBuffer); - SpecifiedClean(sHHBuffer); - SpecifiedClean(sLLBuffer); - SpecifiedClean(mHHBuffer); - SpecifiedClean(mLLBuffer); - SpecifiedClean(lHHBuffer); - SpecifiedClean(lLLBuffer); - SpecifiedClean(hHHBuffer); - SpecifiedClean(hLLBuffer); - SpecifiedClean(highsBuffer); - SpecifiedClean(highsTimeBuffer); - SpecifiedClean(lowsBuffer); - SpecifiedClean(lowsTimeBuffer); - SpecifiedClean(hkOpenBuffer); - SpecifiedClean(hkHighBuffer); - SpecifiedClean(hkLowBuffer); - SpecifiedClean(hkCloseBuffer); - SpecifiedClean(hkColorBuffer); - - // - // Conditions ... - - // - ArraySetAsSeries(bars, true); - - // - ArraySetAsSeries(maFastBuffer, true); - ArraySetAsSeries(maFastColorBuffer, true); - ArraySetAsSeries(maFastStateBuffer, true); - ArraySetAsSeries(maSlowBuffer, true); - ArraySetAsSeries(maSlowColorBuffer, true); - ArraySetAsSeries(maSlowStateBuffer, true); - ArraySetAsSeries(maBandUpperBuffer, true); - ArraySetAsSeries(maBandLowerBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(sarColorBuffer, true); - ArraySetAsSeries(sarStateBuffer, true); - ArraySetAsSeries(peakBuffer, true); - ArraySetAsSeries(valeBuffer, true); - ArraySetAsSeries(fiboUpperBuffer, true); - ArraySetAsSeries(fiboMiddleBuffer, true); - ArraySetAsSeries(fiboLowerBuffer, true); - ArraySetAsSeries(zigzagBuffer, false); // Fix this ... - ArraySetAsSeries(sHHBuffer, true); - ArraySetAsSeries(sLLBuffer, true); - ArraySetAsSeries(mHHBuffer, true); - ArraySetAsSeries(mLLBuffer, true); - ArraySetAsSeries(lHHBuffer, true); - ArraySetAsSeries(lLLBuffer, true); - ArraySetAsSeries(hHHBuffer, true); - ArraySetAsSeries(hLLBuffer, true); - ArraySetAsSeries(highsBuffer, true); - ArraySetAsSeries(highsTimeBuffer, true); - ArraySetAsSeries(lowsBuffer, true); - ArraySetAsSeries(lowsTimeBuffer, true); - ArraySetAsSeries(hkOpenBuffer, true); - ArraySetAsSeries(hkHighBuffer, true); - ArraySetAsSeries(hkLowBuffer, true); - ArraySetAsSeries(hkCloseBuffer, true); - ArraySetAsSeries(hkColorBuffer, true); - - // - ZeroMemory(this); - } - - /** - * Generate Conditions Scores ... - * - * @param bullishScore: Double, Directional Scores Reference ... - * @param bearishScore: Double, Directional Scores Reference ... - */ - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - } - - /** - * Generate Summary String for Represent Conditions State ... - * - * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... - * @param onlyConditions: Boolean, Just Generate Only Conditions ... - * @param includeScores: Boolean, Attach Scores Representations on Result ... - * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... - * @param separator: String, Separate Lines ... - * - * @return ( string ) - */ - string GenerateSummary( - bool onlyCommons = false, - bool onlyConditions = false, - bool includeScores = true, - bool ignoreFalseConditions = true, - string separator = "\n" // - ) - { - return ""; - } - - /** - * Retrieve Unique Tag Identifier ... - * - * @return ( string ) - */ - string GetTag() - { - return GetToken(this); - } -}; - -// -// Class ... -class XCXFIMAHelper : public XCBaseHelper -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructors ... - XCXFIMAHelper() - : XCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XCXFIMAHelper() - { - } - - // - // Tools ... - - // - // Initialize Helper Cleass ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XFIMAInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xfima", - "", // Calculation ... - mInputs.scMethod, - mInputs.scPeriod, - mInputs.mcMethod, - mInputs.mcPeriod, - mInputs.lcMethod, - mInputs.lcPeriod, - mInputs.hcMethod, - mInputs.hcPeriod, - mInputs.upperMode, - mInputs.lowerMode, - mInputs.fiboUpperZoneLevel, - mInputs.fiboMiddleZoneLevel, - mInputs.fiboLowerZoneLevel, - mInputs.sarStep, - mInputs.sarMax, - mInputs.maMethod, - mInputs.maAppliedTo, - mInputs.maFastLength, - mInputs.maSlowLength, - mInputs.maBandLength, - mInputs.zigzagDepth, - mInputs.zigzagDeviation, - mInputs.zigzagBackStep, - mInputs.zigzagUppersMode, - mInputs.zigzagLowersMode, - "", // Presentation ... - mInputs.showPV, - mInputs.showHK, - mInputs.showSAR, - mInputs.showMAFast, - mInputs.showMASlow, - mInputs.showMABand, - mInputs.showZigZag, - mInputs.showFiboZone, - mInputs.startCalculationForLastBars, - mInputs.sarArrowCode, - mInputs.peakArrowCode, - mInputs.valeArrowCode - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XFIMAInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XFIMAInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs // - ); - } - - // - // Tools ... - - // - bool GetConditions( - XFIMAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = true; - - // - if (loopback < 5) - { - loopback = 5; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - // Filling Bars ... - int barsCount = GetBars( - conditions.bars, - mSymbol, - mPeriod, - barIndex, - loopback // - ); - result = barsCount == loopback; - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - conditions.to = conditions.bars[0].time; - conditions.from = conditions.bars[ArraySize(conditions.bars) - 1].time; - - // - int zIndex = barIndex; - - // - // Buffers ... - - // - CopyMAFast( - zIndex, - loopback, - conditions.maFastBuffer // - ); - - // - CopyMAFastState( - zIndex, - loopback, - conditions.maFastStateBuffer // - ); - - // - CopyMASlow( - zIndex, - loopback, - conditions.maSlowBuffer // - ); - - // - CopyMASlowState( - zIndex, - loopback, - conditions.maSlowStateBuffer // - ); - - // - CopyMABandUpper( - zIndex, - loopback, - conditions.maBandUpperBuffer // - ); - - // - CopyMABandLower( - zIndex, - loopback, - conditions.maBandLowerBuffer // - ); - - // - CopySar( - zIndex, - loopback, - conditions.sarBuffer // - ); - - // - CopySarState( - zIndex, - loopback, - conditions.sarStateBuffer // - ); - - // - CopyPeak( - zIndex, - loopback, - conditions.peakBuffer // - ); - - // - CopyVale( - zIndex, - loopback, - conditions.valeBuffer // - ); - - // - CopyFiboUpper( - zIndex, - loopback, - conditions.fiboUpperBuffer // - ); - - // - CopyFiboMiddle( - zIndex, - loopback, - conditions.fiboMiddleBuffer // - ); - - // - CopyFiboLower( - zIndex, - loopback, - conditions.fiboLowerBuffer // - ); - - // - CopyZigZag( - zIndex, - loopback, - conditions.zigzagBuffer // - ); - - // - CopySHH( - zIndex, - loopback, - conditions.sHHBuffer // - ); - - // - CopySLL( - zIndex, - loopback, - conditions.sLLBuffer // - ); - - // - CopyMHH( - zIndex, - loopback, - conditions.mHHBuffer // - ); - - // - CopyMLL( - zIndex, - loopback, - conditions.mLLBuffer // - ); - - // - CopyLHH( - zIndex, - loopback, - conditions.lHHBuffer // - ); - - // - CopyLLL( - zIndex, - loopback, - conditions.lLLBuffer // - ); - - // - CopyHHH( - zIndex, - loopback, - conditions.hHHBuffer // - ); - - // - CopyHLL( - zIndex, - loopback, - conditions.hLLBuffer // - ); - - // - CopyHKOpen( - zIndex, - loopback, - conditions.hkOpenBuffer // - ); - - // - CopyHKHigh( - zIndex, - loopback, - conditions.hkHighBuffer // - ); - - // - CopyHKLow( - zIndex, - loopback, - conditions.hkLowBuffer // - ); - - // - CopyHKClose( - zIndex, - loopback, - conditions.hkCloseBuffer // - ); - - // - CopyHKColor( - zIndex, - loopback, - conditions.hkColorBuffer // - ); - - // - // Conditions ... - - // - return result; - } - - // - // Pivot Actions ... - - /** - * Check Specified Bar has MA Cross or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * - * @return ( bool ) - */ - bool HasMACross( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - double validCrossDiffMultiplier = 1 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - double fast[]; - double slow[]; - double upper[]; - double lower[]; - int count = ReadMAValues( - fast, - slow, - upper, - lower, - barIndex, - 2 // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(fast[0]) && - NotEmptyZero(fast[1]) && - NotEmptyZero(slow[0]) && - NotEmptyZero(slow[1]); - - // - isBullish = - notEmpty && - fast[0] > slow[0] && - fast[1] < slow[1]; - - // - isBearish = - notEmpty && - fast[0] < slow[0] && - fast[1] > slow[1]; - - // - result = - isBullish || - isBearish; - - // - // Validate Direction Change ... - if (result && - validCrossDiffMultiplier > 0) - { - // - double _points = GetPoints(GetSymbol()); - double diff = MathAbs(fast[0] - slow[0]); - - // - result = diff >= (validCrossDiffMultiplier * _points); - } - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - XClean(upper); - XClean(lower); - - // - return result; - } - - /** - * Check Specified Bar has HK Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasHKSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - double low[]; - double open[]; - double high[]; - double close[]; - int count = ReadHKBars( - open, - high, - low, - close, - barIndex, - 2 // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - - // - isBullish = - notEmpty && - open[0] < close[0] && - open[1] > close[1]; - - // - isBearish = - notEmpty && - open[0] > close[0] && - open[1] < close[1]; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(low); - XClean(open); - XClean(high); - XClean(close); - - // - return result; - } - - /** - * Check Specified Bar has SAR Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasSARSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - double sars[]; - int count = CopyBuffer( - mHandler, - XFIMA_SAR_STATE_LINE, - barIndex, - 2, - sars // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - isBullish = - sars[0] >= 1 && - sars[1] <= -1; - - // - isBearish = - sars[0] <= -1 && - sars[1] >= 1; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(sars); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( int ) - */ - int ExtractPVPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - bool lookupPeaks = true; - bool lookupVales = true; - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - int samePeaksCount = 0; - int sameValesCount = 0; - double tmpPeaksBuffer[]; - double tmpValesBuffer[]; - string symbol = GetSymbol(); - double iPValue = EMPTY_VALUE; - double iVValue = EMPTY_VALUE; - double pPValue = EMPTY_VALUE; - double pVValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Detecting ... - - // - // Peak ... - if (lookupPeaks) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_PEAK_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpPeaksBuffer // Buffer ... - ); - ArraySetAsSeries(tmpPeaksBuffer, true); - - // - // Reading Values ... - iPValue = tmpPeaksBuffer[0]; - pPValue = tmpPeaksBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iPValue)) - { - // - // Check New Peak ... - has = - !NotEmptyZero(pPValue) - ? true - : iPValue != pPValue; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - iPValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : samePeaksCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iPValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - samePeaksCount = 0; - } - else if (iPValue == pPValue) - { - samePeaksCount++; - } - } - } - - // - // Vale ... - if (lookupVales) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_VALE_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpValesBuffer // Buffer ... - ); - ArraySetAsSeries(tmpValesBuffer, true); - - // - // Reading Values ... - iVValue = tmpValesBuffer[0]; - pVValue = tmpValesBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iVValue)) - { - // - // Check New Vale ... - has = - !NotEmptyZero(pVValue) - ? true - : iVValue != pVValue; - if (has) - { - // - // Calculate and Validate Type ... - // Vales Only Valid when Confirmed by Bar Low ... - iType = - iVValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : sameValesCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iVValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - sameValesCount = 0; - } - else if (iVValue == pVValue) - { - sameValesCount++; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractMAPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - double validCrossDiffMultiplier = 1, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double fast[]; - double slow[]; - XPivot iPivot; - int count = 0; - double upper[]; - double lower[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - double iFValue = EMPTY_VALUE; - double pFValue = EMPTY_VALUE; - double iSValue = EMPTY_VALUE; - double pSValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - count = ReadMAValues( - fast, - slow, - upper, - lower, - idx, - 2 // - ); - has = IsValidSize(count); - - // - // Reading Values ... - - // - iFValue = fast[0]; - pFValue = fast[1]; - - // - iSValue = slow[0]; - pSValue = slow[1]; - - // - // Validate Value ... - has = - HasMACross( - iDir, - idx, - validCrossDiffMultiplier // - ) && - NotEmptyZero(iFValue) && - NotEmptyZero(iSValue) && - NotEmptyZero(pFValue) && - NotEmptyZero(pSValue); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(iFValue, iSValue) - : MathMin(iFValue, iSValue); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractHKPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double low[]; - double open[]; - XPivot iPivot; - int count = 0; - double high[]; - double close[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - count = ReadHKBars( - open, - high, - low, - close, - idx, - 2 // - ); - has = IsValidSize(count); - - // - // Validate Value ... - has = - HasHKSwitch( - iDir, - idx // - ) && - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(open[0], close[0]) - : MathMin(open[0], close[0]); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractSARPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XOHCL pBar; - XPivot iPivot; - bool has = false; - double tmpSarBuffer[]; - int idx = barIndex - 1; - string symbol = GetSymbol(); - double iValue = EMPTY_VALUE; - double pValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - has = - has && - iBar.GetPreviousBar(pBar); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_SAR_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpSarBuffer // Buffer ... - ); - ArraySetAsSeries(tmpSarBuffer, true); - - // - // Reading Values ... - iValue = tmpSarBuffer[0]; - pValue = tmpSarBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iValue)) - { - // - // Check Sar Direction Changed ... - isSwitchedToBullish = iValue < iBar.low && - pValue > pBar.high; - isSwitchedToBearish = iValue > iBar.high && - pValue < pBar.low; - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // TODO: we can also Add other Validations Here ... - - // - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractZigZagPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - double tmpZigZagBuffer[]; - double iValue = EMPTY_VALUE; - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_ZIGZAG_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 1, // Number of Requirements ... - tmpZigZagBuffer // Buffer ... - ); - ArraySetAsSeries(tmpZigZagBuffer, true); - - // - // Read and Validate Value ... - iValue = tmpZigZagBuffer[0]; - has = NotEmptyZero(iValue); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Type ... - iType = - iValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : iValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Dir ... - iDir = - IsXVale(iType) - ? X_DIRECTION_BULLISH - : IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(iDir); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - return result; - } - - /** - * Extract Validated Zones ... - * - * @param zones: XBoxZone, collection reference to holds results ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFZones: int, required Number of Zones ... - * @param breakValidLength: int, Breake Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * @param shadowMultiplier: double a Shadow Multiplier for Validation ... - * @param validationStrength: double, Minimum Strngth Multiplier in Point to Validate ... - * @param validationLength: int, Validation Length of Zones ... - * @param maxAllowedLoopbackLength: int, max Allowed Loopback Length ... - * - * @return ( int ) - */ - int ExtractHKZones( - XBoxZone &zones[], - int barIndex = 0, - int requiredNumberOFZones = 50, - int breakValidLength = 3, - bool validateFakeBreakes = true, - double shadowMultiplier = 3, - double validationStrength = 1, - int validationLength = 21, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(zones); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 7); - shadowMultiplier = NormalizeDouble(shadowMultiplier, 1); - validationStrength = NormalizeDouble(validationStrength, 1); - requiredNumberOFZones = NormalizeInt(requiredNumberOFZones, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 100); - - // - // Reading Values ... - - // - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - double minAllowedStrength = (validationStrength * GetPoints(symbol)); - - // - int count = 0; - XBoxZone zone; - double hkLows[]; - bool has = false; - double hkOpens[]; - double hkHighs[]; - double hkCloses[]; - int start = barIndex; - bool isBullish = false; - bool isBearish = false; - double up = EMPTY_VALUE; - double down = EMPTY_VALUE; - double body = EMPTY_VALUE; - double range = EMPTY_VALUE; - bool lowShadowPassed = false; - bool highShadowPassed = false; - double lowShadow = EMPTY_VALUE; - double highShadow = EMPTY_VALUE; - double startHKLow = EMPTY_VALUE; - double startHKOpen = EMPTY_VALUE; - double startHKHigh = EMPTY_VALUE; - double startHKClose = EMPTY_VALUE; - ENUM_X_DIRECTION dir = X_DIRECTION_NONE; - int end = start + maxAllowedLoopbackLength; - for (int i = start; i < end; i++) - { - // - // Cleanup ... - zone.Clean(); - dir = X_DIRECTION_NONE; - - // - // Reading HK Buffesr ... - count = ReadHKBars( - hkOpens, - hkHighs, - hkLows, - hkCloses, - i, - 1 // - ); - has = IsValidSize(count); - if (!has) - { - continue; - } - - // - // Initialized Start Bar ... - if (i == start) - { - // - startHKLow = hkLows[0]; - startHKOpen = hkOpens[0]; - startHKHigh = hkHighs[0]; - startHKClose = hkCloses[0]; - } - - // - // Check Direction ... - isBullish = hkOpens[0] < hkCloses[0]; - isBearish = hkOpens[0] > hkCloses[0]; - dir = - (isBullish && !isBearish) - ? X_DIRECTION_BULLISH - : (isBearish && !isBullish) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(dir); - if (!has) - { - continue; - } - - // - // Calculate Requirements for Processing ... - up = isBullish - ? hkCloses[0] - : hkOpens[0]; - down = isBullish - ? hkOpens[0] - : hkCloses[0]; - body = MathAbs(up - down); - range = hkHighs[0] - hkLows[0]; - highShadow = hkHighs[0] - up; - lowShadow = down - hkLows[0]; - - // - // Detecting Shadows ... - - // - // Low Shadow ... - lowShadowPassed = lowShadow >= (shadowMultiplier * highShadow); - - // - // High Shadow ... - highShadowPassed = highShadow >= (shadowMultiplier * lowShadow); - - // - has = (lowShadowPassed && !highShadowPassed) || - (highShadowPassed && !lowShadowPassed); - if (!has) - { - continue; - } - - // - // Filling Zone ... - - // - zone.symbol = symbol; - zone.period = period; - zone.from = GetBarTime( - zone.symbol, - zone.period, - i // - ); - zone.dir = lowShadowPassed - ? X_DIRECTION_BULLISH - : highShadowPassed - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - zone.upper = - IsXBullish(zone.dir) - ? down - : IsXBearish(zone.dir) - ? hkHighs[0] - : EMPTY_VALUE; - - // - zone.lower = - IsXBullish(zone.dir) - ? hkLows[0] - : IsXBearish(zone.dir) - ? up - : EMPTY_VALUE; - - // - zone.to = TimeCurrent(); - zone.type = "XHK_" + (IsXBullish(zone.dir) ? "Support" : IsXBearish(zone.dir) ? "Resistance" - : "") + - "_" + ToXString(TimeToSeconds(zone.from)); - - // - // Validate ... - has = - zone.IsValid() && - HasDirection(zone.dir) && - NotEmptyZero(zone.upper) && - NotEmptyZero(zone.lower) && - (zone.IsBullish() - ? startHKLow > zone.upper - : startHKHigh < zone.lower) && - (zone.upper - zone.lower) >= minAllowedStrength && - ValidateHKZone(zone, validationLength, breakValidLength, validateFakeBreakes); - if (has) - { - // - AddIfNotExists( - zone, - zones // - ); - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - // Validating ... - result = ArraySize(zones); - has = IsValidSize(result) && - result >= requiredNumberOFZones; - if (has) - { - break; - } - } - - // - // Cleanup Resources ... - zone.Clean(); - SpecifiedClean(hkLows); - SpecifiedClean(hkOpens); - SpecifiedClean(hkHighs); - SpecifiedClean(hkCloses); - - // - return result; - } - - // - // Values Retrievers ... - - // - // Fast MA ... - - // - double GetMAFast( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_FAST_LINE, - barIndex // - ); - } - - // - int CopyMAFast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_FAST_LINE, - start, - count, - asSeries // - ); - } - - // - // Fast MA State ... - - // - double GetMAFastState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_FAST_STATE_LINE, - barIndex // - ); - } - - // - int CopyMAFastState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_FAST_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // Slow MA ... - - // - double GetMASlow( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_SLOW_LINE, - barIndex // - ); - } - - // - int CopyMASlow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_SLOW_LINE, - start, - count, - asSeries // - ); - } - - // - // Slow MA State ... - - // - double GetMASlowState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_SLOW_STATE_LINE, - barIndex // - ); - } - - // - int CopyMASlowState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_SLOW_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // Upper MA ... - - // - double GetMABandUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_BAND_UPPER_LINE, - barIndex // - ); - } - - // - int CopyMABandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_BAND_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // Lower MA ... - - // - double GetMABandLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MA_BAND_LOWER_LINE, - barIndex // - ); - } - - // - int CopyMABandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MA_BAND_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // SAR ... - - // - double GetSar( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SAR_LINE, - barIndex // - ); - } - - // - int CopySar( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SAR_LINE, - start, - count, - asSeries // - ); - } - - // - // SAR State ... - - // - double GetSarState( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SAR_STATE_LINE, - barIndex // - ); - } - - // - int CopySarState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SAR_STATE_LINE, - start, - count, - asSeries // - ); - } - - // - // PEAK ... - - // - double GetPeak( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_PEAK_LINE, - barIndex // - ); - } - - // - int CopyPeak( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_PEAK_LINE, - start, - count, - asSeries // - ); - } - - // - // VALE ... - - // - double GetVale( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_VALE_LINE, - barIndex // - ); - } - - // - int CopyVale( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_VALE_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Zone ... - - // - // FIBO Upper ... - - // - double GetFiboUpper( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_UPPER_LINE, - barIndex // - ); - } - - // - int CopyFiboUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_UPPER_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Middle ... - - // - double GetFiboMiddle( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_MIDDLE_LINE, - barIndex // - ); - } - - // - int CopyFiboMiddle( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_MIDDLE_LINE, - start, - count, - asSeries // - ); - } - - // - // FIBO Lower ... - - // - double GetFiboLower( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_FIBO_LOWER_LINE, - barIndex // - ); - } - - // - int CopyFiboLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_FIBO_LOWER_LINE, - start, - count, - asSeries // - ); - } - - // - // ZigZag ... - - // - double GetZigZag( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_ZIGZAG_LINE, - barIndex // - ); - } - - // - int CopyZigZag( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_ZIGZAG_LINE, - start, - count, - asSeries // - ); - } - - // - // CYCLES Range ... - - // - // SHORT ... - - // - // HH ... - - // - double GetSHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SC_HH_LINE, - barIndex // - ); - } - - // - int CopySHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetSLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_SC_LL_LINE, - barIndex // - ); - } - - // - int CopySLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_SC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // MEDIUM ... - - // - // HH ... - - // - double GetMHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MC_HH_LINE, - barIndex // - ); - } - - // - int CopyMHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetMLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_MC_LL_LINE, - barIndex // - ); - } - - // - int CopyMLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_MC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // LONG ... - - // - // HH ... - - // - double GetLHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_LC_HH_LINE, - barIndex // - ); - } - - // - int CopyLHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_LC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetLLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_LC_LL_LINE, - barIndex // - ); - } - - // - int CopyLLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_LC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // HIND ... - - // - // HH ... - - // - double GetHHH( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HC_HH_LINE, - barIndex // - ); - } - - // - int CopyHHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HC_HH_LINE, - start, - count, - asSeries // - ); - } - - // - // LL ... - - // - double GetHLL( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HC_LL_LINE, - barIndex // - ); - } - - // - int CopyHLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HC_LL_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK ... - - // - // XHK Open ... - - // - double GetHKOpen( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_OPEN_LINE, - barIndex // - ); - } - - // - int CopyHKOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_OPEN_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK High ... - - // - double GetHKHigh( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_HIGH_LINE, - barIndex // - ); - } - - // - int CopyHKHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_HIGH_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Low ... - - // - double GetHKLow( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_LOW_LINE, - barIndex // - ); - } - - // - int CopyHKLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_LOW_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Close ... - - // - double GetHKClose( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_CLOSE_LINE, - barIndex // - ); - } - - // - int CopyHKClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_CLOSE_LINE, - start, - count, - asSeries // - ); - } - - // - // XHK Color ... - - // - double GetHKColor( - int barIndex // Bar Index - ) - { - // - return ReadValue( - (int)XFIMA_HK_COLOR_LINE, - barIndex // - ); - } - - // - int CopyHKColor( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool asSeries = true // As Series Flag - ) - { - // - return ReadValues( - buffer, - (int)XFIMA_HK_COLOR_LINE, - start, - count, - asSeries // - ); - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - XFIMAInputs mInputs; // Inputs ... - - // - // XHK Helper ... - - // - int ReadHKBars( - double &open[], - double &high[], - double &low[], - double &close[], - int barIndex = 0, - int count = 1 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Normalize ... - count = NormalizeInt(count, 1); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - // Open ... - CopyBuffer( - mHandler, - XFIMA_HK_OPEN_LINE, - barIndex, - count, - open // - ); - - // - // High ... - CopyBuffer( - mHandler, - XFIMA_HK_HIGH_LINE, - barIndex, - count, - high // - ); - - // - // Low ... - CopyBuffer( - mHandler, - XFIMA_HK_LOW_LINE, - barIndex, - count, - low // - ); - - // - // Close ... - CopyBuffer( - mHandler, - XFIMA_HK_CLOSE_LINE, - barIndex, - count, - close // - ); - - // - ArraySetAsSeries(low, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(close, true); - - // - // Min Number of Array Sizes ... - result = MathMin(ArraySize(open), ArraySize(high)); - result = MathMin(result, ArraySize(close)); - result = MathMin(result, ArraySize(low)); - - // - return result; - } - - /** - * Validate HK Zone ... - * - * @param zone: XBoxZone, reference to Specified Zone ... - * @param validationLength: int, Validation Length of Zones ... - * @param breakValidLength: int, Break Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * - * @return ( bool ) - */ - bool ValidateHKZone( - XBoxZone &zone, - int validationLength = 1, - int breakValidLength = 3, - bool validateFakeBreakes = true // - ) - { - // - bool result = false; - - // - // Normalize ... - validationLength = NormalizeInt(validationLength, 1); - breakValidLength = NormalizeInt(breakValidLength, 2); - - // - // Validate ... - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - // Requirements ... - double low[]; - double open[]; - double high[]; - int count = 0; - double close[]; - - // - int start = zone.FromIndex() + 1; - int end = start + validationLength; - - // - // Validate Before ... - for (int i = start; i < end; i++) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - i, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low[0] > zone.lower - : high[0] < zone.upper; - if (!result) - { - break; - } - } - - // - // Validating After ... - if (result) - { - // - start = zone.ToIndex() + 1; - count = zone.FromIndex() - start; - end = start + count; - for (int i = start; i < end; i++) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - i, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low[0] > zone.lower - : high[0] < zone.upper; - if (!result) - { - // - // Check For Fake Breake ... - if (validateFakeBreakes && breakValidLength > 0) - { - // - result = i - 1 >= 0; - if (result) - { - // - for (int j = i - 1; j >= zone.ToIndex(); j--) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - j, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? close[0] > zone.upper - : close[0] < zone.lower; - if (result) - { - // - result = MathAbs(j - i) <= breakValidLength; - if (result) - { - break; - } - } - } - } - } - - // - if (!result) - { - break; - } - } - } - } - - // - // Cleanup Resource ... - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - return result; - } - - // - int ReadMAValues( - double &fast[], - double &slow[], - double &upper[], - double &lower[], - int barIndex = 0, - int count = 0 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Normalize ... - count = NormalizeInt(count, 1); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - CopyBuffer( - mHandler, - XFIMA_MA_FAST_LINE, - barIndex, - count, - fast // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_SLOW_LINE, - barIndex, - count, - slow // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_UPPER_LINE, - barIndex, - count, - upper // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_LOWER_LINE, - barIndex, - count, - lower // - ); - - // - ArraySetAsSeries(fast, true); - ArraySetAsSeries(slow, true); - ArraySetAsSeries(upper, true); - ArraySetAsSeries(lower, true); - - // - result = MathMin(ArraySize(fast), ArraySize(slow)); - result = MathMin(result, ArraySize(upper)); - result = MathMin(result, ArraySize(lower)); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.helper.mq5 b/Documents/BKP/x-saherelm.xfima.helper.mq5 deleted file mode 100644 index f9033b99..00000000 --- a/Documents/BKP/x-saherelm.xfima.helper.mq5 +++ /dev/null @@ -1,4974 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XCXFIMAHelper -// Description: provides all Indicator -// Helper requirements ... -// -// -// 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 - -// -// Imports ... -#include "../Classes/x-saherelm.x-helper.class.mq5" -#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Definitions ... - -// -// Buffers ... -enum ENUM_XFIMA_BUFFERS -{ - XFIMA_MA_FAST_LINE = 0, - XFIMA_MA_FAST_COLOR_LINE = 1, - XFIMA_MA_FAST_STATE_LINE = 19, - XFIMA_MA_SLOW_LINE = 2, - XFIMA_MA_SLOW_COLOR_LINE = 3, - XFIMA_MA_SLOW_STATE_LINE = 20, - XFIMA_SAR_LINE = 4, - XFIMA_SAR_COLOR_LINE = 5, - XFIMA_SAR_STATE_LINE = 21, - XFIMA_PEAK_LINE = 6, - XFIMA_VALE_LINE = 7, - XFIMA_FIBO_UPPER_LINE = 8, - XFIMA_FIBO_MIDDLE_LINE = 9, - XFIMA_FIBO_LOWER_LINE = 10, - XFIMA_ZIGZAG_LINE = 11, - XFIMA_MA_BAND_UPPER_LINE = 12, - XFIMA_MA_BAND_LOWER_LINE = 13, - XFIMA_ZIGZAG_HIGHS_LINE = 30, - XFIMA_ZIGZAG_HIGHS_TIME_LINE = 31, - XFIMA_ZIGZAG_LOWS_LINE = 32, - XFIMA_ZIGZAG_LOWS_TIME_LINE = 33, - // - XFIMA_HK_OPEN_LINE = 14, - XFIMA_HK_HIGH_LINE = 15, - XFIMA_HK_LOW_LINE = 16, - XFIMA_HK_CLOSE_LINE = 17, - XFIMA_HK_COLOR_LINE = 18, - // 19 Ma Fast State - // 20 Ma Slow State - // 21 Sar State - XFIMA_SC_HH_LINE = 22, - XFIMA_SC_LL_LINE = 23, - XFIMA_MC_HH_LINE = 24, - XFIMA_MC_LL_LINE = 25, - XFIMA_LC_HH_LINE = 26, - XFIMA_LC_LL_LINE = 27, - XFIMA_HC_HH_LINE = 28, - XFIMA_HC_LL_LINE = 29, - // 30 ZigZag Highs - // 31 ZigZag Highs Time - // 32 ZigZag Lows - // 33 ZigZag Lows Time -}; - -// -// Input Models ... -struct XFIMAInputs -{ - // - // Props ... - - // - // Calculation ... - ENUM_X_PERIOD_METHOD scMethod; // How to Find Short Period - ENUM_TIMEFRAMES scPeriod; // Short Period - ENUM_X_PERIOD_METHOD mcMethod; // How to Find Medium Period - ENUM_TIMEFRAMES mcPeriod; // Medium Period - ENUM_X_PERIOD_METHOD lcMethod; // How to Find Long Period - ENUM_TIMEFRAMES lcPeriod; // Long Period - ENUM_X_PERIOD_METHOD hcMethod; // How to Find Hind Period - ENUM_TIMEFRAMES hcPeriod; // Hind Period - ENUM_SERIESMODE upperMode; // Peak Method - ENUM_SERIESMODE lowerMode; // Vale Method - ENUM_X_FIBO_LEVELS fiboUpperZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel; // Upper Zone Level - ENUM_X_FIBO_LEVELS fiboLowerZoneLevel; // Lower Zone Level - double sarStep; // SAR Step - double sarMax; // SAR Maximum - ENUM_MA_METHOD maMethod; // MA Method - ENUM_APPLIED_PRICE maAppliedTo; // MA Applied To - int maFastLength; // Fast MA Length - int maSlowLength; // Slow MA Length - int maBandLength; // MA Band Length - int zigzagDepth; // ZigZag Depth - int zigzagDeviation; // ZigZag Deviation - int zigzagBackStep; // ZigZag Back Step - ENUM_X_PRICE zigzagUppersMode; // ZigZag High Detect Mode - ENUM_X_PRICE zigzagLowersMode; // ZigZag Low Detect Mode - - // - // Presentation ... - bool showPV; // Show PV - bool showHK; // Show HK - bool showSAR; // Show Sar - bool showMAFast; // Show MA Fast - bool showMASlow; // Show MA Slow - bool showMABand; // Show MA Band - bool showZigZag; // Show ZigZag - bool showFiboZone; // Show Fibo Zone - int startCalculationForLastBars; // Calculate Last n Bars - int sarArrowCode; // Parabolic Sar Arrow Code - int peakArrowCode; // Peaks Arrow Code - int valeArrowCode; // Vales Arrow Code - - // - // Constructor(s) ... - XFIMAInputs() - { - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - ZeroMemory(this); - } - - // - // Default ... - void Default() - { - // - // Calculations ... - scMethod = X_PERIOD_AUTO; // How to Find Short Period - scPeriod = NULL; // Short Period - mcMethod = X_PERIOD_AUTO; // How to Find Medium Period - mcPeriod = NULL; // Medium Period - lcMethod = X_PERIOD_AUTO; // How to Find Long Period - lcPeriod = NULL; // Long Period - hcMethod = X_PERIOD_AUTO; // How to Find Hind Period - hcPeriod = NULL; // Hind Period - upperMode = MODE_HIGH; // Peak Method - lowerMode = MODE_LOW; // Vale Method - fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level - fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Upper Zone Level - fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level - sarStep = 0.02; // SAR Step - sarMax = 0.2; // SAR Maximum - maMethod = MODE_EMA; // MA Method - maAppliedTo = PRICE_CLOSE; // MA Applied To - maFastLength = 7; // Fast MA Length - maSlowLength = 20; // Slow MA Length - maBandLength = 7; // MA Band Length - zigzagDepth = 12; // ZigZag Depth - zigzagDeviation = 5; // ZigZag Deviation - zigzagBackStep = 3; // ZigZag Back Step - zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode - zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode - - // - // Presentation ... - showPV = true; // Show PV - showHK = true; // Show HK - showSAR = true; // Show Sar - showMAFast = true; // Show MA Fast - showMASlow = true; // Show MA Slow - showMABand = true; // Show MA Band - showZigZag = true; // Show ZigZag - showFiboZone = true; // Show Fibo Zone - startCalculationForLastBars = 1500; // Calculate Last n Bars - sarArrowCode = 159; // Parabolic Sar Arrow Code - peakArrowCode = 159; // Peaks Arrow Code - valeArrowCode = 159; // Vales Arrow Code - } - - // - // Hide all Visible Buffers ... - void Hide() - { - // - showPV = false; - showHK = false; - showSAR = false; - showMAFast = false; - showMASlow = false; - showMABand = false; - showZigZag = false; - showFiboZone = false; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maBandLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsSpecifiedValid(scMethod, scPeriod) && - IsSpecifiedValid(mcMethod, mcPeriod) && - IsSpecifiedValid(lcMethod, lcPeriod) && - IsSpecifiedValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; - } -}; - -// -// Conditions ... -struct XFIMAConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - datetime to; - datetime from; - XOHCL bars[]; - - // - // Buffers ... - double maFastBuffer[]; - double maFastColorBuffer[]; - double maFastStateBuffer[]; - double maSlowBuffer[]; - double maSlowColorBuffer[]; - double maSlowStateBuffer[]; - double maBandUpperBuffer[]; - double maBandLowerBuffer[]; - double sarBuffer[]; - double sarColorBuffer[]; - double sarStateBuffer[]; - double peakBuffer[]; - double valeBuffer[]; - double fiboUpperBuffer[]; - double fiboMiddleBuffer[]; - double fiboLowerBuffer[]; - double zigzagBuffer[]; - double sHHBuffer[]; - double sLLBuffer[]; - double mHHBuffer[]; - double mLLBuffer[]; - double lHHBuffer[]; - double lLLBuffer[]; - double hHHBuffer[]; - double hLLBuffer[]; - double highsBuffer[]; - double highsTimeBuffer[]; - double lowsBuffer[]; - double lowsTimeBuffer[]; - double hkOpenBuffer[]; - double hkHighBuffer[]; - double hkLowBuffer[]; - double hkCloseBuffer[]; - double hkColorBuffer[]; - - // - // Conditions ... - - // - // Constructor ... - XFIMAConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - // Commons ... - to = NULL; - from = NULL; - time = NULL; - symbol = NULL; - period = NULL; - - // - // Buffers ... - - // - SpecifiedClean(bars); - - // - SpecifiedClean(maFastBuffer); - SpecifiedClean(maFastColorBuffer); - SpecifiedClean(maFastStateBuffer); - SpecifiedClean(maSlowBuffer); - SpecifiedClean(maSlowColorBuffer); - SpecifiedClean(maSlowStateBuffer); - SpecifiedClean(maBandUpperBuffer); - SpecifiedClean(maBandLowerBuffer); - SpecifiedClean(sarBuffer); - SpecifiedClean(sarColorBuffer); - SpecifiedClean(sarStateBuffer); - SpecifiedClean(peakBuffer); - SpecifiedClean(valeBuffer); - SpecifiedClean(fiboUpperBuffer); - SpecifiedClean(fiboMiddleBuffer); - SpecifiedClean(fiboLowerBuffer); - SpecifiedClean(zigzagBuffer); - SpecifiedClean(sHHBuffer); - SpecifiedClean(sLLBuffer); - SpecifiedClean(mHHBuffer); - SpecifiedClean(mLLBuffer); - SpecifiedClean(lHHBuffer); - SpecifiedClean(lLLBuffer); - SpecifiedClean(hHHBuffer); - SpecifiedClean(hLLBuffer); - SpecifiedClean(highsBuffer); - SpecifiedClean(highsTimeBuffer); - SpecifiedClean(lowsBuffer); - SpecifiedClean(lowsTimeBuffer); - SpecifiedClean(hkOpenBuffer); - SpecifiedClean(hkHighBuffer); - SpecifiedClean(hkLowBuffer); - SpecifiedClean(hkCloseBuffer); - SpecifiedClean(hkColorBuffer); - - // - // Conditions ... - - // - ArraySetAsSeries(bars, true); - - // - ArraySetAsSeries(maFastBuffer, true); - ArraySetAsSeries(maFastColorBuffer, true); - ArraySetAsSeries(maFastStateBuffer, true); - ArraySetAsSeries(maSlowBuffer, true); - ArraySetAsSeries(maSlowColorBuffer, true); - ArraySetAsSeries(maSlowStateBuffer, true); - ArraySetAsSeries(maBandUpperBuffer, true); - ArraySetAsSeries(maBandLowerBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(sarColorBuffer, true); - ArraySetAsSeries(sarStateBuffer, true); - ArraySetAsSeries(peakBuffer, true); - ArraySetAsSeries(valeBuffer, true); - ArraySetAsSeries(fiboUpperBuffer, true); - ArraySetAsSeries(fiboMiddleBuffer, true); - ArraySetAsSeries(fiboLowerBuffer, true); - ArraySetAsSeries(zigzagBuffer, false); // Fix this ... - ArraySetAsSeries(sHHBuffer, true); - ArraySetAsSeries(sLLBuffer, true); - ArraySetAsSeries(mHHBuffer, true); - ArraySetAsSeries(mLLBuffer, true); - ArraySetAsSeries(lHHBuffer, true); - ArraySetAsSeries(lLLBuffer, true); - ArraySetAsSeries(hHHBuffer, true); - ArraySetAsSeries(hLLBuffer, true); - ArraySetAsSeries(highsBuffer, true); - ArraySetAsSeries(highsTimeBuffer, true); - ArraySetAsSeries(lowsBuffer, true); - ArraySetAsSeries(lowsTimeBuffer, true); - ArraySetAsSeries(hkOpenBuffer, true); - ArraySetAsSeries(hkHighBuffer, true); - ArraySetAsSeries(hkLowBuffer, true); - ArraySetAsSeries(hkCloseBuffer, true); - ArraySetAsSeries(hkColorBuffer, true); - - // - ZeroMemory(this); - } - - /** - * Generate Conditions Scores ... - * - * @param bullishScore: Double, Directional Scores Reference ... - * @param bearishScore: Double, Directional Scores Reference ... - */ - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - } - - /** - * Generate Summary String for Represent Conditions State ... - * - * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... - * @param onlyConditions: Boolean, Just Generate Only Conditions ... - * @param includeScores: Boolean, Attach Scores Representations on Result ... - * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... - * @param separator: String, Separate Lines ... - * - * @return ( string ) - */ - string GenerateSummary( - bool onlyCommons = false, - bool onlyConditions = false, - bool includeScores = true, - bool ignoreFalseConditions = true, - string separator = "\n" // - ) - { - return ""; - } - - /** - * Retrieve Unique Tag Identifier ... - * - * @return ( string ) - */ - string GetTag() - { - return GetToken(this); - } -}; - -// -// Class ... -class XCXFIMAHelper : public XCBaseHelper -{ - // - // Public ... - public: - // - // Props ... - - // - // Buffers ... - double maFastBuffer[]; - double maFastColorBuffer[]; - double maFastStateBuffer[]; - double maSlowBuffer[]; - double maSlowColorBuffer[]; - double maSlowStateBuffer[]; - double maBandUpperBuffer[]; - double maBandLowerBuffer[]; - double sarBuffer[]; - double sarColorBuffer[]; - double sarStateBuffer[]; - double peakBuffer[]; - double valeBuffer[]; - double fiboUpperBuffer[]; - double fiboMiddleBuffer[]; - double fiboLowerBuffer[]; - double zigzagBuffer[]; - double sHHBuffer[]; - double sLLBuffer[]; - double mHHBuffer[]; - double mLLBuffer[]; - double lHHBuffer[]; - double lLLBuffer[]; - double hHHBuffer[]; - double hLLBuffer[]; - double highsBuffer[]; - double highsTimeBuffer[]; - double lowsBuffer[]; - double lowsTimeBuffer[]; - double hkOpenBuffer[]; - double hkHighBuffer[]; - double hkLowBuffer[]; - double hkCloseBuffer[]; - double hkColorBuffer[]; - - // - // Constructors ... - XCXFIMAHelper() - : XCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XCXFIMAHelper() - { - } - - // - // Tools ... - - // - // Initialize Helper Cleass ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XFIMAInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - ArraySetAsSeries(maFastBuffer, true); - ArraySetAsSeries(maFastColorBuffer, true); - ArraySetAsSeries(maFastStateBuffer, true); - ArraySetAsSeries(maSlowBuffer, true); - ArraySetAsSeries(maSlowColorBuffer, true); - ArraySetAsSeries(maSlowStateBuffer, true); - ArraySetAsSeries(maBandUpperBuffer, true); - ArraySetAsSeries(maBandLowerBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(sarColorBuffer, true); - ArraySetAsSeries(sarStateBuffer, true); - ArraySetAsSeries(peakBuffer, true); - ArraySetAsSeries(valeBuffer, true); - ArraySetAsSeries(fiboUpperBuffer, true); - ArraySetAsSeries(fiboMiddleBuffer, true); - ArraySetAsSeries(fiboLowerBuffer, true); - ArraySetAsSeries(zigzagBuffer, false); // TODO: FIX This ... - ArraySetAsSeries(sHHBuffer, true); - ArraySetAsSeries(sLLBuffer, true); - ArraySetAsSeries(mHHBuffer, true); - ArraySetAsSeries(mLLBuffer, true); - ArraySetAsSeries(lHHBuffer, true); - ArraySetAsSeries(lLLBuffer, true); - ArraySetAsSeries(hHHBuffer, true); - ArraySetAsSeries(hLLBuffer, true); - ArraySetAsSeries(highsBuffer, true); - ArraySetAsSeries(highsTimeBuffer, true); - ArraySetAsSeries(lowsBuffer, true); - ArraySetAsSeries(lowsTimeBuffer, true); - ArraySetAsSeries(hkOpenBuffer, true); - ArraySetAsSeries(hkHighBuffer, true); - ArraySetAsSeries(hkLowBuffer, true); - ArraySetAsSeries(hkCloseBuffer, true); - ArraySetAsSeries(hkColorBuffer, true); - - // - mInputs = inputs; - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xfima", - "", // Calculation ... - mInputs.scMethod, - mInputs.scPeriod, - mInputs.mcMethod, - mInputs.mcPeriod, - mInputs.lcMethod, - mInputs.lcPeriod, - mInputs.hcMethod, - mInputs.hcPeriod, - mInputs.upperMode, - mInputs.lowerMode, - mInputs.fiboUpperZoneLevel, - mInputs.fiboMiddleZoneLevel, - mInputs.fiboLowerZoneLevel, - mInputs.sarStep, - mInputs.sarMax, - mInputs.maMethod, - mInputs.maAppliedTo, - mInputs.maFastLength, - mInputs.maSlowLength, - mInputs.maBandLength, - mInputs.zigzagDepth, - mInputs.zigzagDeviation, - mInputs.zigzagBackStep, - mInputs.zigzagUppersMode, - mInputs.zigzagLowersMode, - "", // Presentation ... - mInputs.showPV, - mInputs.showHK, - mInputs.showSAR, - mInputs.showMAFast, - mInputs.showMASlow, - mInputs.showMABand, - mInputs.showZigZag, - mInputs.showFiboZone, - mInputs.startCalculationForLastBars, - mInputs.sarArrowCode, - mInputs.peakArrowCode, - mInputs.valeArrowCode - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XFIMAInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XFIMAInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs // - ); - } - - // - // Tools ... - - // - void Update( - int barIndex // Bar Index - ) - { - Calculate(barIndex); - } - - // - void Free() override - { - Cleanup(10); - } - - // - bool GetConditions( - XFIMAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = true; - - // - if (loopback < 5) - { - loopback = 5; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - // Filling Bars ... - int barsCount = GetBars( - conditions.bars, - mSymbol, - mPeriod, - barIndex, - loopback // - ); - result = barsCount == loopback; - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - conditions.to = conditions.bars[0].time; - conditions.from = conditions.bars[ArraySize(conditions.bars) - 1].time; - - // - int zIndex = barIndex; - - // - // Buffers ... - - // - CopyMAFast( - zIndex, - loopback, - conditions.maFastBuffer // - ); - - // - CopyMAFastState( - zIndex, - loopback, - conditions.maFastStateBuffer // - ); - - // - CopyMASlow( - zIndex, - loopback, - conditions.maSlowBuffer // - ); - - // - CopyMASlowState( - zIndex, - loopback, - conditions.maSlowStateBuffer // - ); - - // - CopyMABandUpper( - zIndex, - loopback, - conditions.maBandUpperBuffer // - ); - - // - CopyMABandLower( - zIndex, - loopback, - conditions.maBandLowerBuffer // - ); - - // - CopySar( - zIndex, - loopback, - conditions.sarBuffer // - ); - - // - CopySarState( - zIndex, - loopback, - conditions.sarStateBuffer // - ); - - // - CopyPeak( - zIndex, - loopback, - conditions.peakBuffer // - ); - - // - CopyVale( - zIndex, - loopback, - conditions.valeBuffer // - ); - - // - CopyFiboUpper( - zIndex, - loopback, - conditions.fiboUpperBuffer // - ); - - // - CopyFiboMiddle( - zIndex, - loopback, - conditions.fiboMiddleBuffer // - ); - - // - CopyFiboLower( - zIndex, - loopback, - conditions.fiboLowerBuffer // - ); - - // - CopyZigZag( - zIndex, - loopback, - conditions.zigzagBuffer // - ); - - // - CopySHH( - zIndex, - loopback, - conditions.sHHBuffer // - ); - - // - CopySLL( - zIndex, - loopback, - conditions.sLLBuffer // - ); - - // - CopyMHH( - zIndex, - loopback, - conditions.mHHBuffer // - ); - - // - CopyMLL( - zIndex, - loopback, - conditions.mLLBuffer // - ); - - // - CopyLHH( - zIndex, - loopback, - conditions.lHHBuffer // - ); - - // - CopyLLL( - zIndex, - loopback, - conditions.lLLBuffer // - ); - - // - CopyHHH( - zIndex, - loopback, - conditions.hHHBuffer // - ); - - // - CopyHLL( - zIndex, - loopback, - conditions.hLLBuffer // - ); - - // - CopyHKOpen( - zIndex, - loopback, - conditions.hkOpenBuffer // - ); - - // - CopyHKHigh( - zIndex, - loopback, - conditions.hkHighBuffer // - ); - - // - CopyHKLow( - zIndex, - loopback, - conditions.hkLowBuffer // - ); - - // - CopyHKClose( - zIndex, - loopback, - conditions.hkCloseBuffer // - ); - - // - CopyHKColor( - zIndex, - loopback, - conditions.hkColorBuffer // - ); - - // - // Conditions ... - - // - return result; - } - - // - // Pivot Actions ... - - /** - * Check Specified Bar has MA Cross or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * - * @return ( bool ) - */ - bool HasMACross( - ENUM_X_DIRECTION &dir, - int barIndex = 0, - double validCrossDiffMultiplier = 1 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - double fast[]; - double slow[]; - double upper[]; - double lower[]; - int count = ReadMAValues( - fast, - slow, - upper, - lower, - barIndex, - 2 // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(fast[0]) && - NotEmptyZero(fast[1]) && - NotEmptyZero(slow[0]) && - NotEmptyZero(slow[1]); - - // - isBullish = - notEmpty && - fast[0] > slow[0] && - fast[1] < slow[1]; - - // - isBearish = - notEmpty && - fast[0] < slow[0] && - fast[1] > slow[1]; - - // - result = - isBullish || - isBearish; - - // - // Validate Direction Change ... - if (result && - validCrossDiffMultiplier > 0) - { - // - double _points = GetPoints(GetSymbol()); - double diff = MathAbs(fast[0] - slow[0]); - - // - result = diff >= (validCrossDiffMultiplier * _points); - } - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(fast); - XClean(slow); - XClean(upper); - XClean(lower); - - // - return result; - } - - /** - * Check Specified Bar has HK Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasHKSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - double low[]; - double open[]; - double high[]; - double close[]; - int count = ReadHKBars( - open, - high, - low, - close, - barIndex, - 2 // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - bool notEmpty = - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - - // - isBullish = - notEmpty && - open[0] < close[0] && - open[1] > close[1]; - - // - isBearish = - notEmpty && - open[0] > close[0] && - open[1] < close[1]; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(low); - XClean(open); - XClean(high); - XClean(close); - - // - return result; - } - - /** - * Check Specified Bar has SAR Switch or not ... - * - * @param dir: reference for holds cross Direction ... - * @param barIndex: int, Specified Bar Index ... - * - * @return ( bool ) - */ - bool HasSARSwitch( - ENUM_X_DIRECTION &dir, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - dir = X_DIRECTION_NONE; - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - double sars[]; - int count = CopyBuffer( - mHandler, - XFIMA_SAR_STATE_LINE, - barIndex, - 2, - sars // - ); - - // - bool isBullish = false; - bool isBearish = false; - - // - // Validate Readed Values ... - result = IsValidSize(count) && count >= 2; - if (result) - { - // - // Detect Direction Change ... - - // - isBullish = - sars[0] >= 1 && - sars[1] <= -1; - - // - isBearish = - sars[0] <= -1 && - sars[1] >= 1; - - // - result = - isBullish || - isBearish; - } - - // - if (result) - { - // - // Setting Direction ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - } - - // - // Cleanup Resources ... - XClean(sars); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( int ) - */ - int ExtractPVPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - bool lookupPeaks = true; - bool lookupVales = true; - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - int samePeaksCount = 0; - int sameValesCount = 0; - double tmpPeaksBuffer[]; - double tmpValesBuffer[]; - string symbol = GetSymbol(); - double iPValue = EMPTY_VALUE; - double iVValue = EMPTY_VALUE; - double pPValue = EMPTY_VALUE; - double pVValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Detecting ... - - // - // Peak ... - if (lookupPeaks) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_PEAK_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpPeaksBuffer // Buffer ... - ); - ArraySetAsSeries(tmpPeaksBuffer, true); - - // - // Reading Values ... - iPValue = tmpPeaksBuffer[0]; - pPValue = tmpPeaksBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iPValue)) - { - // - // Check New Peak ... - has = - !NotEmptyZero(pPValue) - ? true - : iPValue != pPValue; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - iPValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : samePeaksCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iPValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - samePeaksCount = 0; - } - else if (iPValue == pPValue) - { - samePeaksCount++; - } - } - } - - // - // Vale ... - if (lookupVales) - { - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_VALE_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpValesBuffer // Buffer ... - ); - ArraySetAsSeries(tmpValesBuffer, true); - - // - // Reading Values ... - iVValue = tmpValesBuffer[0]; - pVValue = tmpValesBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iVValue)) - { - // - // Check New Vale ... - has = - !NotEmptyZero(pVValue) - ? true - : iVValue != pVValue; - if (has) - { - // - // Calculate and Validate Type ... - // Vales Only Valid when Confirmed by Bar Low ... - iType = - iVValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // Check Validation Length ... - has = - has && - (validationLength <= 0 - ? true - : sameValesCount >= validationLength); - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iVValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - sameValesCount = 0; - } - else if (iVValue == pVValue) - { - sameValesCount++; - } - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpPeaksBuffer); - SpecifiedClean(tmpValesBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param validCrossDiffMultiplier: double, validate diff between MAs on Cross happens ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractMAPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - double validCrossDiffMultiplier = 1, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - validCrossDiffMultiplier = NormalizeDouble(validCrossDiffMultiplier, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double fast[]; - double slow[]; - XPivot iPivot; - int count = 0; - double upper[]; - double lower[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - double iFValue = EMPTY_VALUE; - double pFValue = EMPTY_VALUE; - double iSValue = EMPTY_VALUE; - double pSValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - count = ReadMAValues( - fast, - slow, - upper, - lower, - idx, - 2 // - ); - has = IsValidSize(count); - - // - // Reading Values ... - - // - iFValue = fast[0]; - pFValue = fast[1]; - - // - iSValue = slow[0]; - pSValue = slow[1]; - - // - // Validate Value ... - has = - HasMACross( - iDir, - idx, - validCrossDiffMultiplier // - ) && - NotEmptyZero(iFValue) && - NotEmptyZero(iSValue) && - NotEmptyZero(pFValue) && - NotEmptyZero(pSValue); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(iFValue, iSValue) - : MathMin(iFValue, iSValue); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractHKPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - double low[]; - double open[]; - XPivot iPivot; - int count = 0; - double high[]; - double close[]; - bool has = false; - int idx = barIndex - 1; - datetime iPivotTime = NULL; - string symbol = GetSymbol(); - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - double iSelectedValue = EMPTY_VALUE; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Reading Buffer ... - count = ReadHKBars( - open, - high, - low, - close, - idx, - 2 // - ); - has = IsValidSize(count); - - // - // Validate Value ... - has = - HasHKSwitch( - iDir, - idx // - ) && - NotEmptyZero(open[0]) && - NotEmptyZero(open[1]) && - NotEmptyZero(close[0]) && - NotEmptyZero(close[1]); - if (has) - { - // - // Check Direction Changed ... - isSwitchedToBullish = IsXBullish(iDir); - isSwitchedToBearish = IsXBearish(iDir); - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - if (has) - { - // - iPivotTime = GetBarTime( - symbol, - period, - idx // - ); - - // - // Select Value based on Pivot Type ... - iSelectedValue = IsXPeak(iType) - ? MathMax(open[0], close[0]) - : MathMin(open[0], close[0]); - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iSelectedValue, - iPivotTime, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iPivot.Clean(); - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractSARPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XOHCL pBar; - XPivot iPivot; - bool has = false; - double tmpSarBuffer[]; - int idx = barIndex - 1; - string symbol = GetSymbol(); - double iValue = EMPTY_VALUE; - double pValue = EMPTY_VALUE; - bool isSwitchedToBullish = false; - bool isSwitchedToBearish = false; - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - has = - has && - iBar.GetPreviousBar(pBar); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_SAR_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 2, // Number of Requirements ... - tmpSarBuffer // Buffer ... - ); - ArraySetAsSeries(tmpSarBuffer, true); - - // - // Reading Values ... - iValue = tmpSarBuffer[0]; - pValue = tmpSarBuffer[1]; - - // - // Validate Value ... - if (NotEmptyZero(iValue)) - { - // - // Check Sar Direction Changed ... - isSwitchedToBullish = iValue < iBar.low && - pValue > pBar.high; - isSwitchedToBearish = iValue > iBar.high && - pValue < pBar.low; - has = - isSwitchedToBullish || - isSwitchedToBearish; - if (has) - { - // - // Calculate and Validate Type ... - // Peaks Only Valid when Confirmed by Bar High ... - iType = - isSwitchedToBearish - ? X_PIVOT_TYPE_PEAK - : isSwitchedToBullish - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - - // - // Calculate and Validate Dir ... - iDir = IsXPeak(iType) - ? X_DIRECTION_BEARISH - : IsXVale(iType) - ? X_DIRECTION_BULLISH - : X_DIRECTION_NONE; - has = has && - HasDirection(iDir); - - // - // TODO: we can also Add other Validations Here ... - - // - if (has) - { - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - // Cleanup Resources ... - iPivot.Clean(); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpSarBuffer); - - // - return result; - } - - /** - * Extract Specified Kind of Pivots ... - * - * @param pivots: XPivot, refrence Collection to hold Extracted pivots ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( int ) - */ - int ExtractZigZagPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(pivots); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - requiredNumberOFPivots = NormalizeInt(requiredNumberOFPivots, 2); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - XOHCL iBar; - XPivot iPivot; - bool has = false; - int idx = barIndex - 1; - double tmpZigZagBuffer[]; - double iValue = EMPTY_VALUE; - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int maxAllowed = barIndex + maxAllowedLoopbackLength - 1; - while (idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots) - { - // - idx++; - - // - // Prepare ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Ignore First Item ... - if (idx == barIndex) - { - continue; - } - - // - // Initialize Bar ... - has = iBar.Init( - symbol, - period, - idx // - ); - if (!has) - { - continue; - } - - // - // Reading Buffer ... - CopyBuffer( - mHandler, // Handler ... - XFIMA_ZIGZAG_LINE, // Handler Buffer Number ... - idx, // Bar Index ... - 1, // Number of Requirements ... - tmpZigZagBuffer // Buffer ... - ); - ArraySetAsSeries(tmpZigZagBuffer, true); - - // - // Read and Validate Value ... - iValue = tmpZigZagBuffer[0]; - has = NotEmptyZero(iValue); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Type ... - iType = - iValue == iBar.high - ? X_PIVOT_TYPE_PEAK - : iValue == iBar.low - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_NONE; - has = IsXValid(iType); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Calculate and Validate Dir ... - iDir = - IsXVale(iType) - ? X_DIRECTION_BULLISH - : IsXPeak(iType) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(iDir); - if (!has) - { - // - iBar.Clean(); - SpecifiedClean(tmpZigZagBuffer); - continue; - } - - // - // Initialize and Validate Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - symbol, - iDir, - period, - iType // - ); - if (has) - { - // - // Add Pivot to Collection only if not Exists ... - AddIfNotExists( - iPivot, - pivots // - ); - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - // Check Moving Forward Condition ... - has = - idx < maxAllowed && - ArraySize(pivots) < requiredNumberOFPivots; - if (!has) - { - break; - } - } - - // - result = ArraySize(pivots); - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - SpecifiedClean(tmpZigZagBuffer); - - // - return result; - } - - /** - * Extract Validated Zones ... - * - * @param zones: XBoxZone, collection reference to holds results ... - * @param barIndex: int, Specified Bar Index ... - * @param requiredNumberOFZones: int, required Number of Zones ... - * @param breakValidLength: int, Breake Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * @param shadowMultiplier: double a Shadow Multiplier for Validation ... - * @param validationStrength: double, Minimum Strngth Multiplier in Point to Validate ... - * @param validationLength: int, Validation Length of Zones ... - * @param maxAllowedLoopbackLength: int, max Allowed Loopback Length ... - * - * @return ( int ) - */ - int ExtractHKZones( - XBoxZone &zones[], - int barIndex = 0, - int requiredNumberOFZones = 50, - int breakValidLength = 3, - bool validateFakeBreakes = true, - double shadowMultiplier = 3, - double validationStrength = 1, - int validationLength = 21, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(zones); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - validationLength = NormalizeInt(validationLength, 7); - shadowMultiplier = NormalizeDouble(shadowMultiplier, 1); - validationStrength = NormalizeDouble(validationStrength, 1); - requiredNumberOFZones = NormalizeInt(requiredNumberOFZones, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 100); - - // - // Reading Values ... - - // - string symbol = GetSymbol(); - ENUM_TIMEFRAMES period = GetPeriod(); - double minAllowedStrength = (validationStrength * GetPoints(symbol)); - - // - int count = 0; - XBoxZone zone; - double hkLows[]; - bool has = false; - double hkOpens[]; - double hkHighs[]; - double hkCloses[]; - int start = barIndex; - bool isBullish = false; - bool isBearish = false; - double up = EMPTY_VALUE; - double down = EMPTY_VALUE; - double body = EMPTY_VALUE; - double range = EMPTY_VALUE; - bool lowShadowPassed = false; - bool highShadowPassed = false; - double lowShadow = EMPTY_VALUE; - double highShadow = EMPTY_VALUE; - double startHKLow = EMPTY_VALUE; - double startHKOpen = EMPTY_VALUE; - double startHKHigh = EMPTY_VALUE; - double startHKClose = EMPTY_VALUE; - ENUM_X_DIRECTION dir = X_DIRECTION_NONE; - int end = start + maxAllowedLoopbackLength; - for (int i = start; i < end; i++) - { - // - // Cleanup ... - zone.Clean(); - dir = X_DIRECTION_NONE; - - // - // Reading HK Buffesr ... - count = ReadHKBars( - hkOpens, - hkHighs, - hkLows, - hkCloses, - i, - 1 // - ); - has = IsValidSize(count); - if (!has) - { - continue; - } - - // - // Initialized Start Bar ... - if (i == start) - { - // - startHKLow = hkLows[0]; - startHKOpen = hkOpens[0]; - startHKHigh = hkHighs[0]; - startHKClose = hkCloses[0]; - } - - // - // Check Direction ... - isBullish = hkOpens[0] < hkCloses[0]; - isBearish = hkOpens[0] > hkCloses[0]; - dir = - (isBullish && !isBearish) - ? X_DIRECTION_BULLISH - : (isBearish && !isBullish) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(dir); - if (!has) - { - continue; - } - - // - // Calculate Requirements for Processing ... - up = isBullish - ? hkCloses[0] - : hkOpens[0]; - down = isBullish - ? hkOpens[0] - : hkCloses[0]; - body = MathAbs(up - down); - range = hkHighs[0] - hkLows[0]; - highShadow = hkHighs[0] - up; - lowShadow = down - hkLows[0]; - - // - // Detecting Shadows ... - - // - // Low Shadow ... - lowShadowPassed = lowShadow >= (shadowMultiplier * highShadow); - - // - // High Shadow ... - highShadowPassed = highShadow >= (shadowMultiplier * lowShadow); - - // - has = (lowShadowPassed && !highShadowPassed) || - (highShadowPassed && !lowShadowPassed); - if (!has) - { - continue; - } - - // - // Filling Zone ... - - // - zone.symbol = symbol; - zone.period = period; - zone.from = GetBarTime( - zone.symbol, - zone.period, - i // - ); - zone.dir = lowShadowPassed - ? X_DIRECTION_BULLISH - : highShadowPassed - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - zone.upper = - IsXBullish(zone.dir) - ? down - : IsXBearish(zone.dir) - ? hkHighs[0] - : EMPTY_VALUE; - - // - zone.lower = - IsXBullish(zone.dir) - ? hkLows[0] - : IsXBearish(zone.dir) - ? up - : EMPTY_VALUE; - - // - zone.to = TimeCurrent(); - zone.type = "XHK_" + (IsXBullish(zone.dir) ? "Support" : IsXBearish(zone.dir) ? "Resistance" - : "") + - "_" + ToXString(TimeToSeconds(zone.from)); - - // - // Validate ... - has = - zone.IsValid() && - HasDirection(zone.dir) && - NotEmptyZero(zone.upper) && - NotEmptyZero(zone.lower) && - (zone.IsBullish() - ? startHKLow > zone.upper - : startHKHigh < zone.lower) && - (zone.upper - zone.lower) >= minAllowedStrength && - ValidateHKZone(zone, validationLength, breakValidLength, validateFakeBreakes); - if (has) - { - // - AddIfNotExists( - zone, - zones // - ); - } - - // - // Cleanup Resources ... - zone.Clean(); - - // - // Validating ... - result = ArraySize(zones); - has = IsValidSize(result) && - result >= requiredNumberOFZones; - if (has) - { - break; - } - } - - // - // Cleanup Resources ... - zone.Clean(); - SpecifiedClean(hkLows); - SpecifiedClean(hkOpens); - SpecifiedClean(hkHighs); - SpecifiedClean(hkCloses); - - // - return result; - } - - // - // Values Retrievers ... - - // - // Fast MA ... - - // - double GetMAFast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maFastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maFastBuffer[barIndex]; - } - - // - int CopyMAFast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maFastBuffer, - buffer, - forceClean - // - ); - } - - // - // Fast MA State ... - - // - double GetMAFastState( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maFastStateBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maFastStateBuffer[barIndex]; - } - - // - int CopyMAFastState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maFastStateBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow MA ... - - // - double GetMASlow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maSlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maSlowBuffer[barIndex]; - } - - // - int CopyMASlow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maSlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow MA State ... - - // - double GetMASlowState( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maSlowStateBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maSlowStateBuffer[barIndex]; - } - - // - int CopyMASlowState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maSlowStateBuffer, - buffer, - forceClean - // - ); - } - - // - // Upper MA ... - - // - double GetMABandUpper( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maBandUpperBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maBandUpperBuffer[barIndex]; - } - - // - int CopyMABandUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maBandUpperBuffer, - buffer, - forceClean - // - ); - } - - // - // Lower MA ... - - // - double GetMABandLower( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(maBandLowerBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return maBandLowerBuffer[barIndex]; - } - - // - int CopyMABandLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - maBandLowerBuffer, - buffer, - forceClean - // - ); - } - - // - // SAR ... - - // - double GetSar( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(sarBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return sarBuffer[barIndex]; - } - - // - int CopySar( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - sarBuffer, - buffer, - forceClean - // - ); - } - - // - // SAR State ... - - // - double GetSarState( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(sarStateBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return sarStateBuffer[barIndex]; - } - - // - int CopySarState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - sarStateBuffer, - buffer, - forceClean - // - ); - } - - // - // PEAK ... - - // - double GetPeak( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(peakBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return peakBuffer[barIndex]; - } - - // - int CopyPeak( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - peakBuffer, - buffer, - forceClean - // - ); - } - - // - // VALE ... - - // - double GetVale( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(valeBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return valeBuffer[barIndex]; - } - - // - int CopyVale( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - valeBuffer, - buffer, - forceClean - // - ); - } - - // - // FIBO Zone ... - - // - // FIBO Upper ... - - // - double GetFiboUpper( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(fiboUpperBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fiboUpperBuffer[barIndex]; - } - - // - int CopyFiboUpper( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - fiboUpperBuffer, - buffer, - forceClean - // - ); - } - - // - // FIBO Middle ... - - // - double GetFiboMiddle( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(fiboMiddleBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fiboMiddleBuffer[barIndex]; - } - - // - int CopyFiboMiddle( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - fiboMiddleBuffer, - buffer, - forceClean - // - ); - } - - // - // FIBO Lower ... - - // - double GetFiboLower( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(fiboLowerBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fiboLowerBuffer[barIndex]; - } - - // - int CopyFiboLower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - fiboLowerBuffer, - buffer, - forceClean - // - ); - } - - // - // ZigZag ... - - // - double GetZigZag( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - // Calculate(barIndex); - SpecifiedClean(zigzagBuffer); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_LINE, - barIndex, - 1, - zigzagBuffer // - ); - - // - int count = ArraySize(zigzagBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return zigzagBuffer[barIndex]; - } - - // - int CopyZigZag( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - // Calculate(start); - SpecifiedClean(zigzagBuffer); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_LINE, - start, - 0, - zigzagBuffer // - ); - - // - // Copy Items ... - return Copy( - 0, - count, - zigzagBuffer, - buffer, - forceClean - // - ); - } - - // - // CYCLES Range ... - - // - // SHORT ... - - // - // HH ... - - // - double GetSHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(sHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return sHHBuffer[barIndex]; - } - - // - int CopySHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - sHHBuffer, - buffer, - forceClean - // - ); - } - - // - // LL ... - - // - double GetSLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(sLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return sLLBuffer[barIndex]; - } - - // - int CopySLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - sLLBuffer, - buffer, - forceClean - // - ); - } - - // - // MEDIUM ... - - // - // HH ... - - // - double GetMHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(mHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mHHBuffer[barIndex]; - } - - // - int CopyMHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - mHHBuffer, - buffer, - forceClean - // - ); - } - - // - // LL ... - - // - double GetMLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(mLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mLLBuffer[barIndex]; - } - - // - int CopyMLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - mLLBuffer, - buffer, - forceClean - // - ); - } - - // - // LONG ... - - // - // HH ... - - // - double GetLHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(lHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lHHBuffer[barIndex]; - } - - // - int CopyLHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - lHHBuffer, - buffer, - forceClean - // - ); - } - - // - // LL ... - - // - double GetLLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(lLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lLLBuffer[barIndex]; - } - - // - int CopyLLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - lLLBuffer, - buffer, - forceClean - // - ); - } - - // - // HIND ... - - // - // HH ... - - // - double GetHHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hHHBuffer[barIndex]; - } - - // - int CopyHHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hHHBuffer, - buffer, - forceClean - // - ); - } - - // - // LL ... - - // - double GetHLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hLLBuffer[barIndex]; - } - - // - int CopyHLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hLLBuffer, - buffer, - forceClean - // - ); - } - - // - // XHK ... - - // - // XHK Open ... - - // - double GetHKOpen( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hkOpenBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hkOpenBuffer[barIndex]; - } - - // - int CopyHKOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hkOpenBuffer, - buffer, - forceClean - // - ); - } - - // - // XHK High ... - - // - double GetHKHigh( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hkHighBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hkHighBuffer[barIndex]; - } - - // - int CopyHKHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hkHighBuffer, - buffer, - forceClean - // - ); - } - - // - // XHK Low ... - - // - double GetHKLow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hkLowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hkLowBuffer[barIndex]; - } - - // - int CopyHKLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hkLowBuffer, - buffer, - forceClean - // - ); - } - - // - // XHK Close ... - - // - double GetHKClose( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hkCloseBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hkCloseBuffer[barIndex]; - } - - // - int CopyHKClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hkCloseBuffer, - buffer, - forceClean - // - ); - } - - // - // XHK Color ... - - // - double GetHKColor( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(barIndex); - - // - int count = ArraySize(hkColorBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hkColorBuffer[barIndex]; - } - - // - int CopyHKColor( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(start); - - // - // Copy Items ... - return Copy( - 0, - count, - hkColorBuffer, - buffer, - forceClean - // - ); - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - XFIMAInputs mInputs; // Inputs ... - - // - // Buffers ... - // Define in Public ... - - // - void Calculate( - int barIndex = 0, - int maxRequiredBars = 100 // - ) - { - // - // Buffers ... - if (barIndex < 0) - { - barIndex = 0; - } - - // - CopyBuffer( - mHandler, - XFIMA_MA_FAST_LINE, - barIndex, - maxRequiredBars, - maFastBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_FAST_COLOR_LINE, - barIndex, - maxRequiredBars, - maFastColorBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_FAST_STATE_LINE, - barIndex, - maxRequiredBars, - maFastStateBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_SLOW_LINE, - barIndex, - maxRequiredBars, - maSlowBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_SLOW_COLOR_LINE, - barIndex, - maxRequiredBars, - maSlowColorBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_SLOW_STATE_LINE, - barIndex, - maxRequiredBars, - maSlowStateBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_UPPER_LINE, - barIndex, - maxRequiredBars, - maBandUpperBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_LOWER_LINE, - barIndex, - maxRequiredBars, - maBandLowerBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_SAR_LINE, - barIndex, - maxRequiredBars, - sarBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_SAR_COLOR_LINE, - barIndex, - maxRequiredBars, - sarColorBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_SAR_STATE_LINE, - barIndex, - maxRequiredBars, - sarStateBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_PEAK_LINE, - barIndex, - maxRequiredBars, - peakBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_VALE_LINE, - barIndex, - maxRequiredBars, - valeBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_FIBO_UPPER_LINE, - barIndex, - maxRequiredBars, - fiboUpperBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_FIBO_MIDDLE_LINE, - barIndex, - maxRequiredBars, - fiboMiddleBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_FIBO_LOWER_LINE, - barIndex, - maxRequiredBars, - fiboLowerBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_LINE, - barIndex, - maxRequiredBars, - zigzagBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_SC_HH_LINE, - barIndex, - maxRequiredBars, - sHHBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_SC_LL_LINE, - barIndex, - maxRequiredBars, - sLLBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MC_HH_LINE, - barIndex, - maxRequiredBars, - mHHBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MC_LL_LINE, - barIndex, - maxRequiredBars, - mLLBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_LC_HH_LINE, - barIndex, - maxRequiredBars, - lHHBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_LC_LL_LINE, - barIndex, - maxRequiredBars, - lLLBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HC_HH_LINE, - barIndex, - maxRequiredBars, - hHHBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HC_LL_LINE, - barIndex, - maxRequiredBars, - hLLBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_HIGHS_LINE, - barIndex, - maxRequiredBars, - highsBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_HIGHS_TIME_LINE, - barIndex, - maxRequiredBars, - highsTimeBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_LOWS_LINE, - barIndex, - maxRequiredBars, - lowsBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_ZIGZAG_LOWS_TIME_LINE, - barIndex, - maxRequiredBars, - lowsTimeBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HK_OPEN_LINE, - barIndex, - maxRequiredBars, - hkOpenBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HK_HIGH_LINE, - barIndex, - maxRequiredBars, - hkHighBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HK_LOW_LINE, - barIndex, - maxRequiredBars, - hkLowBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HK_CLOSE_LINE, - barIndex, - maxRequiredBars, - hkCloseBuffer // - ); - - // - CopyBuffer( - mHandler, - XFIMA_HK_COLOR_LINE, - barIndex, - maxRequiredBars, - hkColorBuffer // - ); - } - - // - void Cleanup( - int maxAllowed = 100 // - ) - { - // - CleanupArray( - maFastBuffer, - maxAllowed // - ); - - // - CleanupArray( - maFastColorBuffer, - maxAllowed // - ); - - // - CleanupArray( - maFastStateBuffer, - maxAllowed // - ); - - // - CleanupArray( - maSlowBuffer, - maxAllowed // - ); - - // - CleanupArray( - maSlowColorBuffer, - maxAllowed // - ); - - // - CleanupArray( - maSlowStateBuffer, - maxAllowed // - ); - - // - CleanupArray( - maBandUpperBuffer, - maxAllowed // - ); - - // - CleanupArray( - maBandLowerBuffer, - maxAllowed // - ); - - // - CleanupArray( - sarBuffer, - maxAllowed // - ); - - // - CleanupArray( - sarColorBuffer, - maxAllowed // - ); - - // - CleanupArray( - sarStateBuffer, - maxAllowed // - ); - - // - CleanupArray( - peakBuffer, - maxAllowed // - ); - - // - CleanupArray( - valeBuffer, - maxAllowed // - ); - - // - CleanupArray( - fiboUpperBuffer, - maxAllowed // - ); - - // - CleanupArray( - fiboMiddleBuffer, - maxAllowed // - ); - - // - CleanupArray( - fiboLowerBuffer, - maxAllowed // - ); - - // - CleanupArray( - zigzagBuffer, - maxAllowed // - ); - - // - CleanupArray( - sHHBuffer, - maxAllowed // - ); - - // - CleanupArray( - sLLBuffer, - maxAllowed // - ); - - // - CleanupArray( - mHHBuffer, - maxAllowed // - ); - - // - CleanupArray( - mLLBuffer, - maxAllowed // - ); - - // - CleanupArray( - lHHBuffer, - maxAllowed // - ); - - // - CleanupArray( - lLLBuffer, - maxAllowed // - ); - - // - CleanupArray( - hHHBuffer, - maxAllowed // - ); - - // - CleanupArray( - hLLBuffer, - maxAllowed // - ); - - // - CleanupArray( - highsBuffer, - maxAllowed // - ); - - // - CleanupArray( - highsTimeBuffer, - maxAllowed // - ); - - // - CleanupArray( - lowsBuffer, - maxAllowed // - ); - - // - CleanupArray( - lowsTimeBuffer, - maxAllowed // - ); - - // - CleanupArray( - hkOpenBuffer, - maxAllowed // - ); - - // - CleanupArray( - hkHighBuffer, - maxAllowed // - ); - - // - CleanupArray( - hkLowBuffer, - maxAllowed // - ); - - // - CleanupArray( - hkCloseBuffer, - maxAllowed // - ); - - // - CleanupArray( - hkColorBuffer, - maxAllowed // - ); - } - - // - // XHK Helper ... - - // - int ReadHKBars( - double &open[], - double &high[], - double &low[], - double &close[], - int barIndex = 0, - int count = 1 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - // Normalize ... - count = NormalizeInt(count, 1); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - // Open ... - CopyBuffer( - mHandler, - XFIMA_HK_OPEN_LINE, - barIndex, - count, - open // - ); - - // - // High ... - CopyBuffer( - mHandler, - XFIMA_HK_HIGH_LINE, - barIndex, - count, - high // - ); - - // - // Low ... - CopyBuffer( - mHandler, - XFIMA_HK_LOW_LINE, - barIndex, - count, - low // - ); - - // - // Close ... - CopyBuffer( - mHandler, - XFIMA_HK_CLOSE_LINE, - barIndex, - count, - close // - ); - - // - ArraySetAsSeries(low, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(close, true); - - // - // Min Number of Array Sizes ... - result = MathMin(ArraySize(open), ArraySize(high)); - result = MathMin(result, ArraySize(close)); - result = MathMin(result, ArraySize(low)); - - // - return result; - } - - /** - * Validate HK Zone ... - * - * @param zone: XBoxZone, reference to Specified Zone ... - * @param validationLength: int, Validation Length of Zones ... - * @param breakValidLength: int, Break Validation Length of Zones ... - * @param validateFakeBreakes: bool, Validation Fake Breaked Zones ... - * - * @return ( bool ) - */ - bool ValidateHKZone( - XBoxZone &zone, - int validationLength = 1, - int breakValidLength = 3, - bool validateFakeBreakes = true // - ) - { - // - bool result = false; - - // - // Normalize ... - validationLength = NormalizeInt(validationLength, 1); - breakValidLength = NormalizeInt(breakValidLength, 2); - - // - // Validate ... - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - // Requirements ... - double low[]; - double open[]; - double high[]; - int count = 0; - double close[]; - - // - int start = zone.FromIndex() + 1; - int end = start + validationLength; - - // - // Validate Before ... - for (int i = start; i < end; i++) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - i, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low[0] > zone.lower - : high[0] < zone.upper; - if (!result) - { - break; - } - } - - // - // Validating After ... - if (result) - { - // - start = zone.ToIndex() + 1; - count = zone.FromIndex() - start; - end = start + count; - for (int i = start; i < end; i++) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - i, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? low[0] > zone.lower - : high[0] < zone.upper; - if (!result) - { - // - // Check For Fake Breake ... - if (validateFakeBreakes && breakValidLength > 0) - { - // - result = i - 1 >= 0; - if (result) - { - // - for (int j = i - 1; j >= zone.ToIndex(); j--) - { - // - // Reading HK ... - count = ReadHKBars( - open, - high, - low, - close, - j, - 1 // - ); - result = IsValidSize(count); - if (!result) - { - break; - } - - // - result = zone.IsBullish() - ? close[0] > zone.upper - : close[0] < zone.lower; - if (result) - { - // - result = MathAbs(j - i) <= breakValidLength; - if (result) - { - break; - } - } - } - } - } - - // - if (!result) - { - break; - } - } - } - } - - // - // Cleanup Resource ... - SpecifiedClean(low); - SpecifiedClean(open); - SpecifiedClean(high); - SpecifiedClean(close); - - // - return result; - } - - // - int ReadMAValues( - double &fast[], - double &slow[], - double &upper[], - double &lower[], - int barIndex = 0, - int count = 0 // - ) - { - // - int result = 0; - - // - // Prepare ... - SpecifiedClean(fast); - SpecifiedClean(slow); - SpecifiedClean(upper); - SpecifiedClean(lower); - - // - // Normalize ... - count = NormalizeInt(count, 1); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate ... - if (mHandler == INVALID_HANDLE) - { - return result; - } - - // - CopyBuffer( - mHandler, - XFIMA_MA_FAST_LINE, - barIndex, - count, - fast // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_SLOW_LINE, - barIndex, - count, - slow // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_UPPER_LINE, - barIndex, - count, - upper // - ); - - // - CopyBuffer( - mHandler, - XFIMA_MA_BAND_LOWER_LINE, - barIndex, - count, - lower // - ); - - // - ArraySetAsSeries(fast, true); - ArraySetAsSeries(slow, true); - ArraySetAsSeries(upper, true); - ArraySetAsSeries(lower, true); - - // - result = MathMin(ArraySize(fast), ArraySize(slow)); - result = MathMin(result, ArraySize(upper)); - result = MathMin(result, ArraySize(lower)); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.lib copy 2.mq5 b/Documents/BKP/x-saherelm.xfima.lib copy 2.mq5 deleted file mode 100644 index 279edaeb..00000000 --- a/Documents/BKP/x-saherelm.xfima.lib copy 2.mq5 +++ /dev/null @@ -1,567 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Library -// ------------------------------------------------- -// Name: XCXFIMAEALib ... -// Description: XFIMAEA Library ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMAEA Library" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-cobject.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.parser.class.mq5" -#include "../../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" - -// -// Definitions ... - -/** - * XFIMA Base Market Structure ... - * AnalyseMarket result ... - **/ -struct XFIMAMarketStructure -{ - // - XOHCL bar; // Spacified Start Bar for Analysing ... - XPatternAnalysis barAnalysis; // Structure Bar Pattern Analysis ... - - // - XPivotAnalysis pvAnalysis; // PV Pivot Analysis Result ... - XPivotAnalysis zgAnalysis; // ZG Pivot Analysis Result ... - - // - XPatternAnalysis barsAnalysis[]; // Anaysed Bars ... - - // - // Constructor ... - XFIMAMarketStructure() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - bar.Clean(); - barAnalysis.Clean(); - - // - pvAnalysis.Clean(); - zgAnalysis.Clean(); - XClean(barsAnalysis); - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = bar.IsValid() && - barAnalysis.IsValid(); - - // - return result; - } - - // - // Collectors ... - - /** - * Collect Required Zones from Structure ... - * - * @param dest: XBoxZone, reference collection to holds result ... - * @param forDir: ENUM_X_DIRECTION, Specified Collectiong ones Direction ... - * @param containsOB: bool, Contains OB Zones ... - * @param containsFVG: bool, Contains FVG Zones ... - * - * @return ( int ) - */ - int CollectZones( - XBoxZone &dest[], - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, - bool containsOB = false, - bool containsFVG = false // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(dest); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - bool canCollectBullish = - IsXBullish(forDir) || - !HasDirection(forDir); - - // - bool canCollectBearish = - IsXBearish(forDir) || - !HasDirection(forDir); - - // - int count = 0; - XBoxZone tmpBox; - - // - // Check Analysis ... - - // - // XPV ... - has = pvAnalysis.IsValid(); - if (has) - { - // - // Support ... - tmpBox.Clean(); - has = pvAnalysis.HasSupportBox(tmpBox); - if (has && canCollectBullish) - { - // - AddIfNotExists( - tmpBox, - dest // - ); - } - - // - // Resistance ... - tmpBox.Clean(); - has = pvAnalysis.HasResistanceBox(tmpBox); - if (has && canCollectBearish) - { - // - AddIfNotExists( - tmpBox, - dest // - ); - } - } - - // - // XZG ... - has = zgAnalysis.IsValid(); - if (has) - { - // - // Support ... - tmpBox.Clean(); - has = zgAnalysis.HasSupportBox(tmpBox); - if (has && canCollectBullish) - { - // - AddIfNotExists( - tmpBox, - dest // - ); - } - - // - // Resistance ... - tmpBox.Clean(); - has = zgAnalysis.HasResistanceBox(tmpBox); - if (has && canCollectBearish) - { - // - AddIfNotExists( - tmpBox, - dest // - ); - } - } - - // - // Bar Patterns ... - has = HasChild(barsAnalysis); - if (has) - { - // - count = ArraySize(barsAnalysis); - for (int i = 0; i < count; i++) - { - // - // Support ... - has = barsAnalysis[i].IsSupport(); - if (has && canCollectBullish) - { - // - AddIfNotExists( - barsAnalysis[i].support, - dest // - ); - } - - // - // Resistance ... - has = barsAnalysis[i].IsResistance(); - if (has && canCollectBearish) - { - // - AddIfNotExists( - barsAnalysis[i].resistance, - dest // - ); - } - - // - // OB ... - if (containsOB) - { - // - has = barsAnalysis[i].IsOB(); - if (has) - { - // - has = (canCollectBullish && barsAnalysis[i].ob.IsBullish()) || - (canCollectBearish && barsAnalysis[i].ob.IsBearish()); - if (has) - { - // - AddIfNotExists( - barsAnalysis[i].ob, - dest // - ); - } - } - } - - // - // FVG ... - if (containsFVG) - { - has = barsAnalysis[i].IsFVG(); - if (has) - { - // - has = (canCollectBullish && barsAnalysis[i].fvg.IsBullish()) || - (canCollectBearish && barsAnalysis[i].fvg.IsBearish()); - if (has) - { - // - AddIfNotExists( - barsAnalysis[i].fvg, - dest // - ); - } - } - } - } - } - - // - result = ArraySize(dest); - has = IsValidSize(result); - if (has) - { - // - // Update To Time ... - // and also we Can Validate Zones Here ... - datetime cTime = TimeCurrent(); - for (int i = 0; i < result; i++) - { - dest[i].to = cTime; - } - } - - // - // Cleanup ... - tmpBox.Clean(); - - // - return result; - } - - // -}; - -struct XFIMAMarketStructureConfig -{ - // - // Props ... - - // - // Detector Flags ... - - // - bool analysePVPivots; // Analyse PV Pivots ... - bool analyseZGPivots; // Analyse ZG Pivots ... - - // - bool analyseBarPatterns; // Analyse Bar Patterns ... - - // - // Detector Configs ... - - // - int loopback; // Max Allowed Looping Back Length ... - int requiredPivots; // Required Extracted Pivots for Analysis ... - - // - int pvPivotsValidationLength; // PV Pivots Validation Length ... - double maCrossValidationDiffMultiplier; // a Point Distance to Validate MA Crosses ... - - // - XPatternAnalysisConfig barsAnalysisConfig; // Bars Analyser Config ... - - // - // Constructor ... - XFIMAMarketStructureConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * This function fulfills the will of the developer - */ - void Clean() - { - // - // Detector Flags ... - analysePVPivots = false; - analyseZGPivots = false; - analyseBarPatterns = false; - - // - // Configure Detectors ... - loopback = 0; - requiredPivots = 0; - pvPivotsValidationLength = 0; - maCrossValidationDiffMultiplier = 0; - - // - barsAnalysisConfig.Clean(); - - // - ZeroMemory(this); - } - - /** - * Default Configurations ... - */ - void Default() - { - // - // Detector Flags ... - analysePVPivots = true; - analyseZGPivots = true; - analyseBarPatterns = true; - - // - // Configure Detectors ... - loopback = 200; - requiredPivots = 10; - pvPivotsValidationLength = 5; - maCrossValidationDiffMultiplier = 4; - - // - barsAnalysisConfig.Default(); - barsAnalysisConfig.FullPattern(); - } - - /** - * No Draw Abilioty ... - */ - void Off() - { - // - // Detector Flags ... - analysePVPivots = false; - analyseZGPivots = false; - analyseBarPatterns = false; - } - - /** - * Full Draw Abilioty ... - */ - void Full() - { - // - // Detector Flags ... - analysePVPivots = true; - analyseZGPivots = true; - analyseBarPatterns = true; - } - - // -}; - -/** - * Configure Market Structure Drawer ... - **/ -struct XFIMAMarketStructureDrawerConfig -{ - // - // Props ... - - // - bool drawPVAnalysis; - bool drawZGAnalysis; - bool drawBarsAnalysis; - - // - XPOIDrawConfig drawConfig; - XPivotAnalysisDrawConfig pivotAnalysisDrawConfig; - XPatternAnalysisDrawConfig barAnalysisDrawConfig; - - // - // Constructor ... - XFIMAMarketStructureDrawerConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * This function fulfills the will of the developer - */ - void Clean() - { - // - // Drawing Flags ... - - // - drawPVAnalysis = false; - drawZGAnalysis = false; - drawBarsAnalysis = false; - - // - // Drawing Configs ... - drawConfig.Clean(); - barAnalysisDrawConfig.Clean(); - pivotAnalysisDrawConfig.Clean(); - - // - ZeroMemory(this); - } - - /** - * Default Configurations ... - */ - void Default() - { - // - // Drawing Flags ... - - // - drawPVAnalysis = true; - drawZGAnalysis = true; - drawBarsAnalysis = true; - - // - // Drawing Configs ... - drawConfig.Default(); - pivotAnalysisDrawConfig.Default(); - - // - barAnalysisDrawConfig.Default(); - barAnalysisDrawConfig.Full(); - XClean(barAnalysisDrawConfig.allowedDrawZones); - Add( - X_BAR_PATTERN_SUPPORT, - barAnalysisDrawConfig.allowedDrawZones); - Add( - X_BAR_PATTERN_RESISTANCE, - barAnalysisDrawConfig.allowedDrawZones); - } - - /** - * No Draw Abilioty ... - */ - void Off() - { - // - // Drawing Flags ... - - // - drawPVAnalysis = false; - drawZGAnalysis = false; - drawBarsAnalysis = false; - - // - // Drawing Configs ... - barAnalysisDrawConfig.Off(); - pivotAnalysisDrawConfig.Off(); - } - - /** - * Full Draw Abilioty ... - */ - void Full() - { - // - // Drawing Flags ... - - // - drawPVAnalysis = false; - drawZGAnalysis = false; - drawBarsAnalysis = false; - - // - // Drawing Configs ... - barAnalysisDrawConfig.Full(); - pivotAnalysisDrawConfig.Full(); - } - - void ApplyDrawConfig() - { - // - barAnalysisDrawConfig.drawConfig = drawConfig; - barAnalysisDrawConfig.ConfigureQuarterDraws(); - pivotAnalysisDrawConfig.drawConfig = drawConfig; - } - - void ApplyDrawConfig(XPOIDrawConfig &_drawConfig) - { - // - drawConfig = _drawConfig; - ApplyDrawConfig(); - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.lib copy.mq5 b/Documents/BKP/x-saherelm.xfima.lib copy.mq5 deleted file mode 100644 index 78665e18..00000000 --- a/Documents/BKP/x-saherelm.xfima.lib copy.mq5 +++ /dev/null @@ -1,694 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Library -// ------------------------------------------------- -// Name: XCXFIMAEALib ... -// Description: XFIMAEA Library ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMAEA Library" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-cobject.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" - -// -// Definitions ... - -/** - * Configure Market Structure Detection ... - **/ -struct XFIMAPatternDetectorConfig -{ - // - // Props ... - - // - bool detectSwingTrend; - - // - bool detectStarPattern; - bool detectFlagPattern; - bool detectRisingPattern; - bool detectPiercingPattern; - bool detectSignalKeyBarPattern; - - // - bool detectPinned; - bool detectMomentum; - bool detectEngulfed; - bool detectTrueGaped; - - // - bool analyseFIMAPVPivots; - bool analyseFIMAZigZagPivots; - - // - bool detectMACrosses; - double validMACrossDiffMultiplier; - - // - bool detectHKSwitches; - bool detectSARSwitches; - - // - // Configs ... - - // - // Trending ... - int trendingNumberOfSwings; - int trendingSwingShoulders; - - // - // Support and Resistance ... - int zonesRequiredNumber; - int zonesValidationLength; - double zonesMinAlloweStrength; - int zonesBreakValidationLength; - double zonesBarShadowMultiplier; - int zonesMaxAllowedLoopbackLength; - - // - // TrueGap ... - double truwGapApprovedPointMultiplier; - - // - // Flag Pattern ... - int flagPatternMinimumPullbackBars; - - // - // Momentum Bar ... - int momentumBarRangeLength; - double momentumBarApprovedMultiplier; - - // - // Pinned Bar ... - double pinnedBaarShadowApprovedMultiplier; - double pinnedBarMinimumPinBarRangeMultiplier; - bool pinnedBarForceDirection; - - // - // SignalKey Bar ... - double signalKeyBarShadowApprovedMultiplier; - double signalKeyBarMinimumPinBarRangeMultiplier; - bool signalKeyBarForceDirection; - - // - // Analyser ... - int pvPivotsValidationLength; - int numberOfRequiredPivotsForAnalysis; - int maxAllowedLoopbackLengthForAnalysis; - - // - // Constructor ... - XFIMAPatternDetectorConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - detectSwingTrend = false; - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - analyseFIMAPVPivots = false; - detectPiercingPattern = false; - analyseFIMAZigZagPivots = false; - detectSignalKeyBarPattern = false; - - // - detectMACrosses = false; - validMACrossDiffMultiplier = 0; - - // - detectHKSwitches = false; - detectSARSwitches = false; - - // - zonesRequiredNumber = 0; - zonesValidationLength = 0; - zonesMinAlloweStrength = 0; - zonesBarShadowMultiplier = 0; - zonesBreakValidationLength = 0; - zonesMaxAllowedLoopbackLength = 0; - - // - trendingNumberOfSwings = 0; - trendingSwingShoulders = 0; - momentumBarRangeLength = 0; - pvPivotsValidationLength = 0; - pinnedBarForceDirection = false; - momentumBarApprovedMultiplier = 0; - signalKeyBarForceDirection = false; - truwGapApprovedPointMultiplier = 0; - flagPatternMinimumPullbackBars = 0; - numberOfRequiredPivotsForAnalysis = 0; - pinnedBaarShadowApprovedMultiplier = 0; - maxAllowedLoopbackLengthForAnalysis = 0; - signalKeyBarShadowApprovedMultiplier = 0; - pinnedBarMinimumPinBarRangeMultiplier = 0; - signalKeyBarMinimumPinBarRangeMultiplier = 0; - - // - ZeroMemory(this); - } - - /** - * Default Model ... - */ - void Default() - { - // - // Patterns ... - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - detectPiercingPattern = false; - detectSignalKeyBarPattern = false; - - // - // Bars ... - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - - // - // Analysers ... - analyseFIMAPVPivots = false; - analyseFIMAZigZagPivots = false; - - // - detectMACrosses = true; - validMACrossDiffMultiplier = 1; - - // - detectHKSwitches = true; - detectSARSwitches = true; - - // - // Trending ... - trendingNumberOfSwings = 3; - trendingSwingShoulders = 11; - - // - // Support and Resistance ... - zonesRequiredNumber = 25; - zonesValidationLength = 21; - zonesMinAlloweStrength = 2; - zonesBarShadowMultiplier = 4; - zonesBreakValidationLength = 3; - zonesMaxAllowedLoopbackLength = 200; - - // - // TrueGap ... - truwGapApprovedPointMultiplier = 1; - - // - // Flag Pattern ... - flagPatternMinimumPullbackBars = 3; - - // - // Momentum Bar ... - momentumBarRangeLength = 3; - momentumBarApprovedMultiplier = 2; - - // - // Pinned Bar ... - pinnedBaarShadowApprovedMultiplier = 3; - pinnedBarMinimumPinBarRangeMultiplier = 4; - pinnedBarForceDirection = false; - - // - // SignalKey Bar ... - signalKeyBarShadowApprovedMultiplier = 3; - signalKeyBarMinimumPinBarRangeMultiplier = 4; - signalKeyBarForceDirection = false; - - // - // Length ... - pvPivotsValidationLength = 10; - numberOfRequiredPivotsForAnalysis = 50; - maxAllowedLoopbackLengthForAnalysis = 1500; - } - - /** - * Full Detection Model ... - */ - void FullDetect() - { - // - // Patterns ... - detectStarPattern = true; - detectFlagPattern = true; - detectRisingPattern = true; - detectPiercingPattern = true; - detectSignalKeyBarPattern = true; - - // - // Bars ... - detectPinned = true; - detectMomentum = true; - detectEngulfed = true; - detectTrueGaped = true; - - // - // Analysers ... - analyseFIMAPVPivots = true; - analyseFIMAZigZagPivots = true; - - // - detectMACrosses = true; - detectHKSwitches = true; - detectSARSwitches = true; - } - - /** - * Default Config, by turn off all detecting flags ... - */ - void OffDetectors() - { - // - // Patterns ... - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - detectPiercingPattern = false; - detectSignalKeyBarPattern = false; - - // - // Bars ... - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - - // - // Analysers ... - analyseFIMAPVPivots = false; - analyseFIMAZigZagPivots = false; - - // - detectMACrosses = false; - detectHKSwitches = false; - detectSARSwitches = false; - } - - // -}; - -/** - * XFIMA Base Market Structure ... - * AnalyseMarket result ... - **/ -struct XFIMAMarketStructure -{ - // - XOHCL bar; - - // - XBoxZone obs[]; - XBoxZone fvgs[]; - XBoxZone supports[]; - XBoxZone resistances[]; - - // - XPivot pinBars[]; - XPivot engulfBars[]; - XPivot trueGapBars[]; - XPivot momentumBars[]; - - // - XBoxZone flagPatterns[]; - XBoxZone starPatterns[]; - XBoxZone risingPatterns[]; - XBoxZone piercingPatterns[]; - XBoxZone signalKeyBarPatterns[]; - - // - // Analysis ... - XPivotAnalysis pvAnalysis; - XPivotAnalysis zigzagAnalysis; - - // - ENUM_X_DIRECTION pinnedDir; - ENUM_X_DIRECTION momentumDir; - ENUM_X_DIRECTION engulfedDir; - ENUM_X_DIRECTION trueGapedDir; - - // - XOHCL flagSwing; - ENUM_X_DIRECTION flagPatternDir; - - // - XOHCL trendSwings[]; - ENUM_X_DIRECTION trendDir; - - // - ENUM_X_DIRECTION starPatternDir; - ENUM_X_DIRECTION risingPatternDir; - ENUM_X_DIRECTION piercingPatternDir; - ENUM_X_DIRECTION signalKeyBarPatternDir; - - // - ENUM_X_DIRECTION maCrossDir; - XPivot maCrosses[]; - - // - ENUM_X_DIRECTION hkSwitchDir; - XPivot hkSwitches[]; - - // - ENUM_X_DIRECTION sarSwitchDir; - XPivot sarSwitches[]; - - // - // Constructor ... - XFIMAMarketStructure() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - bar.Clean(); - flagSwing.Clean(); - - // - pvAnalysis.Clean(); - zigzagAnalysis.Clean(); - - // - trendDir = X_DIRECTION_NONE; - pinnedDir = X_DIRECTION_NONE; - momentumDir = X_DIRECTION_NONE; - engulfedDir = X_DIRECTION_NONE; - trueGapedDir = X_DIRECTION_NONE; - flagPatternDir = X_DIRECTION_NONE; - starPatternDir = X_DIRECTION_NONE; - risingPatternDir = X_DIRECTION_NONE; - piercingPatternDir = X_DIRECTION_NONE; - signalKeyBarPatternDir = X_DIRECTION_NONE; - - // - maCrossDir = X_DIRECTION_NONE; - SpecifiedClean(maCrosses); - - // - hkSwitchDir = X_DIRECTION_NONE; - SpecifiedClean(hkSwitches); - - // - sarSwitchDir = X_DIRECTION_NONE; - SpecifiedClean(sarSwitches); - - // - SpecifiedClean(obs); - SpecifiedClean(fvgs); - SpecifiedClean(pinBars); - SpecifiedClean(supports); - SpecifiedClean(engulfBars); - SpecifiedClean(resistances); - SpecifiedClean(trueGapBars); - SpecifiedClean(momentumBars); - SpecifiedClean(flagPatterns); - SpecifiedClean(starPatterns); - SpecifiedClean(risingPatterns); - SpecifiedClean(piercingPatterns); - SpecifiedClean(signalKeyBarPatterns); - - // - SpecifiedClean(trendSwings); - - // - ZeroMemory(this); - } - - // - // Checker Functions ... - - // -}; - -/** - * Configure Market Structure Drawer ... - **/ -struct XFIMAMarketStructureDrawerConfig -{ - // - // Props ... - - // - bool drawOB; // Current Order Block ... - bool drawFVG; // Current Fair Value Gap ... - - // - bool drawSupport; // Detected Supports ... - bool drawResistance; // Detected Resistances ... - - // - bool drawSwingTrend; // Swing Trend ... - bool swingTrendRayLeft; // Ray Left Swing Trend ... - bool swingTrendRayRight; // Ray Right Swing Trend ... - - // - // Draw Current Detected Patterns ... - - // - bool drawPinned; - bool drawMomentum; - bool drawEngulfed; - bool drawTrueGaped; - - // - bool drawStarPattern; - bool drawFlagPattern; - bool drawRisingPattern; - bool drawPiercingPattern; - bool drawSignalKeyBarPattern; - - // - // Draw Recently Zones ... - bool drawRecentPatterns; - bool drawFakeBreakedZone; - bool drawRecentlyTestedZones; - bool drawRecentlyBreakedZones; - - // - // Draw Analysis Pivots ... - - // - // XPV ... - bool drawFIMAPVPivotsAnalysis; - bool drawFIMAPVPivotsAnalysisZones; - bool drawFIMAPVPivotsAnalysisTrends; - bool drawFIMAPVPivotsAnalysisPivots; - - // - // XSAR ... - bool drawFIMASARPivotsAnalysis; - bool drawFIMASARPivotsAnalysisZones; - bool drawFIMASARPivotsAnalysisTrends; - bool drawFIMASARPivotsAnalysisPivots; - - // - // XZIGZAG ... - bool drawFIMAZigZagPivotsAnalysis; - bool drawFIMAZigZagPivotsAnalysisZones; - bool drawFIMAZigZagPivotsAnalysisTrends; - bool drawFIMAZigZagPivotsAnalysisPivots; - - // - // Constructor ... - XFIMAMarketStructureDrawerConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - drawOB = false; - drawFVG = false; - drawPinned = false; - drawMomentum = false; - drawSupport = false; - drawEngulfed = false; - drawTrueGaped = false; - drawResistance = false; - drawSwingTrend = false; - drawStarPattern = false; - drawFlagPattern = false; - swingTrendRayLeft = false; - drawRisingPattern = false; - swingTrendRayRight = false; - drawPiercingPattern = false; - drawSignalKeyBarPattern = false; - - // - drawRecentPatterns = false; - drawFakeBreakedZone = false; - drawRecentlyTestedZones = false; - drawRecentlyBreakedZones = false; - - // - drawFIMAPVPivotsAnalysis = false; - drawFIMAPVPivotsAnalysisZones = false; - drawFIMAPVPivotsAnalysisTrends = false; - drawFIMAPVPivotsAnalysisPivots = false; - - // - drawFIMASARPivotsAnalysis = false; - drawFIMASARPivotsAnalysisZones = false; - drawFIMASARPivotsAnalysisTrends = false; - drawFIMASARPivotsAnalysisPivots = false; - - // - drawFIMAZigZagPivotsAnalysis = false; - drawFIMAZigZagPivotsAnalysisZones = false; - drawFIMAZigZagPivotsAnalysisTrends = false; - drawFIMAZigZagPivotsAnalysisPivots = false; - - // - ZeroMemory(this); - } - - /** - * Default Model ... - */ - void Default() - { - drawOB = true; - drawFVG = true; - drawPinned = true; - drawMomentum = true; - drawSupport = true; - drawEngulfed = true; - drawTrueGaped = true; - drawResistance = true; - drawSwingTrend = true; - drawStarPattern = true; - drawFlagPattern = true; - drawRisingPattern = true; - drawPiercingPattern = true; - swingTrendRayLeft = false; - swingTrendRayRight = true; - drawSignalKeyBarPattern = true; - - // - drawRecentPatterns = true; - drawFakeBreakedZone = true; - drawRecentlyTestedZones = true; - drawRecentlyBreakedZones = true; - - // - drawFIMAPVPivotsAnalysis = true; - drawFIMAPVPivotsAnalysisZones = true; - drawFIMAPVPivotsAnalysisTrends = true; - drawFIMAPVPivotsAnalysisPivots = true; - - // - drawFIMASARPivotsAnalysis = true; - drawFIMASARPivotsAnalysisZones = true; - drawFIMASARPivotsAnalysisTrends = true; - drawFIMASARPivotsAnalysisPivots = true; - - // - drawFIMAZigZagPivotsAnalysis = true; - drawFIMAZigZagPivotsAnalysisZones = true; - drawFIMAZigZagPivotsAnalysisTrends = true; - drawFIMAZigZagPivotsAnalysisPivots = true; - } - - /** - * Configure for Full Drawing ... - */ - void FullDraw() - { - // - Default(); - - // - drawOB = true; - drawFVG = true; - drawPinned = true; - drawMomentum = true; - drawSupport = true; - drawEngulfed = true; - drawTrueGaped = true; - drawResistance = true; - drawSwingTrend = true; - drawStarPattern = true; - drawFlagPattern = true; - drawRisingPattern = true; - swingTrendRayLeft = true; - swingTrendRayRight = true; - drawPiercingPattern = true; - drawSignalKeyBarPattern = true; - - // - drawRecentPatterns = true; - drawFakeBreakedZone = true; - drawRecentlyTestedZones = true; - drawRecentlyBreakedZones = true; - - // - drawFIMAPVPivotsAnalysis = true; - drawFIMAPVPivotsAnalysisZones = true; - drawFIMAPVPivotsAnalysisTrends = true; - drawFIMAPVPivotsAnalysisPivots = true; - - // - drawFIMASARPivotsAnalysis = true; - drawFIMASARPivotsAnalysisZones = true; - drawFIMASARPivotsAnalysisTrends = true; - drawFIMASARPivotsAnalysisPivots = true; - - // - drawFIMAZigZagPivotsAnalysis = true; - drawFIMAZigZagPivotsAnalysisZones = true; - drawFIMAZigZagPivotsAnalysisTrends = true; - drawFIMAZigZagPivotsAnalysisPivots = true; - } - - // -}; diff --git a/Documents/BKP/x-saherelm.xfima.lib.mq5 b/Documents/BKP/x-saherelm.xfima.lib.mq5 deleted file mode 100644 index 3a376c25..00000000 --- a/Documents/BKP/x-saherelm.xfima.lib.mq5 +++ /dev/null @@ -1,792 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Library -// ------------------------------------------------- -// Name: XCXFIMAEALib ... -// Description: XFIMAEA Library ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMAEA Library" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-cobject.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../../Libraries/x-saherelm.x-pivot.analysis.lib.mq5" - -// -// Definitions ... - -/** - * Configure Market Structure Detection ... - **/ -struct XFIMAPatternDetectorConfig -{ - // - // Props ... - - // - // Flags ... - - // - bool detectSupport; - bool detectResistance; - - // - bool detectSwingTrend; - - // - bool detectOB; - bool detectFVG; - - // - bool detectStarPattern; - bool detectFlagPattern; - bool detectRisingPattern; - bool detectPiercingPattern; - bool detectSignalKeyBarPattern; - - // - bool detectPinned; - bool detectMomentum; - bool detectEngulfed; - bool detectTrueGaped; - - // - bool analyseFIMAPVPivots; - bool analyseFIMASARPivots; - bool analyseFIMAZigZagPivots; - - // - bool detectMACrosses; - double validMACrossDiffMultiplier; - - // - bool detectHKSwitches; - bool detectSARSwitches; - - // - // Configs ... - - // - // OB / FVG ... - int obLoopback; - int fvgLoopback; - - // - // Trending ... - int trendingNumberOfSwings; - int trendingSwingShoulders; - - // - int recentlyPatternsMaxLookupLength; - int recentlyPatternsMaxAllowedCollecting; - - // - // Support and Resistance ... - int recentlyZonesMaxLookupLength; - int supportAndResistanceValidationLength; - int minAllowdSupportAndResistanceStrength; - int supportAndResistanceMaxAllowedLoopback; - int supportAndResistanceBreakeValidationLength; - - // - // TrueGap ... - double truwGapApprovedPointMultiplier; - - // - // Flag Pattern ... - int flagPatternMinimumPullbackBars; - - // - // Momentum Bar ... - int momentumBarRangeLength; - double momentumBarApprovedMultiplier; - - // - // Pinned Bar ... - double pinnedBaarShadowApprovedMultiplier; - double pinnedBarMinimumPinBarRangeMultiplier; - bool pinnedBarForceDirection; - - // - // SignalKey Bar ... - double signalKeyBarShadowApprovedMultiplier; - double signalKeyBarMinimumPinBarRangeMultiplier; - bool signalKeyBarForceDirection; - - // - // Analyser ... - int pvPivotsValidationLength; - int numberOfRequiredPivotsForAnalysis; - int maxAllowedLoopbackLengthForAnalysis; - - // - // Constructor ... - XFIMAPatternDetectorConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - detectOB = false; - detectFVG = false; - detectSupport = false; - detectResistance = false; - detectSwingTrend = false; - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - detectPiercingPattern = false; - detectSignalKeyBarPattern = false; - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - analyseFIMAPVPivots = false; - analyseFIMASARPivots = false; - analyseFIMAZigZagPivots = false; - - // - detectMACrosses = false; - validMACrossDiffMultiplier = 0; - - // - detectHKSwitches = false; - detectSARSwitches = false; - - // - obLoopback = 0; - fvgLoopback = 0; - trendingNumberOfSwings = 0; - trendingSwingShoulders = 0; - recentlyZonesMaxLookupLength = 0; - recentlyPatternsMaxLookupLength = 0; - recentlyPatternsMaxAllowedCollecting = 0; - supportAndResistanceValidationLength = 0; - minAllowdSupportAndResistanceStrength = 0; - supportAndResistanceMaxAllowedLoopback = 0; - supportAndResistanceBreakeValidationLength = 0; - truwGapApprovedPointMultiplier = 0; - flagPatternMinimumPullbackBars = 0; - momentumBarRangeLength = 0; - momentumBarApprovedMultiplier = 0; - pinnedBaarShadowApprovedMultiplier = 0; - pinnedBarMinimumPinBarRangeMultiplier = 0; - pinnedBarForceDirection = false; - signalKeyBarShadowApprovedMultiplier = 0; - signalKeyBarMinimumPinBarRangeMultiplier = 0; - signalKeyBarForceDirection = false; - pvPivotsValidationLength = 0; - numberOfRequiredPivotsForAnalysis = 0; - maxAllowedLoopbackLengthForAnalysis = 0; - - // - ZeroMemory(this); - } - - /** - * Default Model ... - */ - void Default() - { - // - // OB / FVG ... - detectOB = false; - detectFVG = false; - - // - // Support and Resistances ... - detectSupport = false; - detectResistance = false; - detectSwingTrend = false; - - // - // Patterns ... - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - detectPiercingPattern = false; - detectSignalKeyBarPattern = false; - - // - // Bars ... - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - - // - // Analysers ... - analyseFIMAPVPivots = false; - analyseFIMASARPivots = false; - analyseFIMAZigZagPivots = false; - - // - detectMACrosses = true; - validMACrossDiffMultiplier = 1; - - // - detectHKSwitches = true; - detectSARSwitches = true; - - // - // OB / FVg ... - obLoopback = 5; - fvgLoopback = 5; - - // - // Trending ... - trendingNumberOfSwings = 3; - trendingSwingShoulders = 11; - - // - // Support and Resistance ... - recentlyZonesMaxLookupLength = 100; - recentlyPatternsMaxLookupLength = 50; - recentlyPatternsMaxAllowedCollecting = 20; - supportAndResistanceValidationLength = 100; - minAllowdSupportAndResistanceStrength = 1; - supportAndResistanceMaxAllowedLoopback = 1500; - supportAndResistanceBreakeValidationLength = 4; - - // - // TrueGap ... - truwGapApprovedPointMultiplier = 1; - - // - // Flag Pattern ... - flagPatternMinimumPullbackBars = 3; - - // - // Momentum Bar ... - momentumBarRangeLength = 3; - momentumBarApprovedMultiplier = 2; - - // - // Pinned Bar ... - pinnedBaarShadowApprovedMultiplier = 3; - pinnedBarMinimumPinBarRangeMultiplier = 4; - pinnedBarForceDirection = false; - - // - // SignalKey Bar ... - signalKeyBarShadowApprovedMultiplier = 3; - signalKeyBarMinimumPinBarRangeMultiplier = 4; - signalKeyBarForceDirection = false; - - // - // Length ... - pvPivotsValidationLength = 10; - numberOfRequiredPivotsForAnalysis = 50; - maxAllowedLoopbackLengthForAnalysis = 1500; - } - - /** - * Full Detection Model ... - */ - void FullDetect() - { - // - // OB / FVG ... - detectOB = true; - detectFVG = true; - - // - // Support and Resistances ... - detectSupport = true; - detectResistance = true; - detectSwingTrend = true; - - // - // Patterns ... - detectStarPattern = true; - detectFlagPattern = true; - detectRisingPattern = true; - detectPiercingPattern = true; - detectSignalKeyBarPattern = true; - - // - // Bars ... - detectPinned = true; - detectMomentum = true; - detectEngulfed = true; - detectTrueGaped = true; - - // - // Analysers ... - analyseFIMAPVPivots = true; - analyseFIMASARPivots = true; - analyseFIMAZigZagPivots = true; - - // - detectMACrosses = true; - detectHKSwitches = true; - detectSARSwitches = true; - } - - /** - * Default Config, by turn off all detecting flags ... - */ - void OffDetectors() - { - // - // OB / FVG ... - detectOB = false; - detectFVG = false; - - // - // Support and Resistances ... - detectSupport = false; - detectResistance = false; - detectSwingTrend = false; - - // - // Patterns ... - detectStarPattern = false; - detectFlagPattern = false; - detectRisingPattern = false; - detectPiercingPattern = false; - detectSignalKeyBarPattern = false; - - // - // Bars ... - detectPinned = false; - detectMomentum = false; - detectEngulfed = false; - detectTrueGaped = false; - - // - // Analysers ... - analyseFIMAPVPivots = false; - analyseFIMASARPivots = false; - analyseFIMAZigZagPivots = false; - - // - detectMACrosses = false; - detectHKSwitches = false; - detectSARSwitches = false; - } - - // -}; - -/** - * XFIMA Base Market Structure ... - * AnalyseMarket result ... - **/ -struct XFIMAMarketStructure -{ - // - XOHCL bar; - - // - XBoxZone ob; - XBoxZone fvg; - XBoxZone support; - XBoxZone resistance; - - // - XBoxZone obs[]; - XBoxZone fvgs[]; - XBoxZone supports[]; - XBoxZone resistances[]; - - // - XPivot pinBars[]; - XPivot engulfBars[]; - XPivot trueGapBars[]; - XPivot momentumBars[]; - - // - XBoxZone flagPatterns[]; - XBoxZone starPatterns[]; - XBoxZone risingPatterns[]; - XBoxZone piercingPatterns[]; - XBoxZone signalKeyBarPatterns[]; - - // - // Previous Support or Resistance based on current ... - // - // Current Support is Touched => Prev Support; - // Current Resistance is Touched => Prev Resistance; - XBoxZone fakeBreakedZone; - - // - XBoxZone recentlyTestedZones[]; - XBoxZone recentlyBreakedZones[]; - - // - // Analysis ... - XPivotAnalysis pvAnalysis; - XPivotAnalysis sarAnalysis; - XPivotAnalysis zigzagAnalysis; - - // - ENUM_X_DIRECTION pinnedDir; - ENUM_X_DIRECTION momentumDir; - ENUM_X_DIRECTION engulfedDir; - ENUM_X_DIRECTION trueGapedDir; - - // - XOHCL flagSwing; - ENUM_X_DIRECTION flagPatternDir; - - // - XOHCL trendSwings[]; - ENUM_X_DIRECTION trendDir; - - // - ENUM_X_DIRECTION starPatternDir; - ENUM_X_DIRECTION risingPatternDir; - ENUM_X_DIRECTION piercingPatternDir; - ENUM_X_DIRECTION signalKeyBarPatternDir; - - // - ENUM_X_DIRECTION maCrossDir; - XPivot maCrosses[]; - - // - ENUM_X_DIRECTION hkSwitchDir; - XPivot hkSwitches[]; - - // - ENUM_X_DIRECTION sarSwitchDir; - XPivot sarSwitches[]; - - // - // Constructor ... - XFIMAMarketStructure() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - ob.Clean(); - fvg.Clean(); - support.Clean(); - resistance.Clean(); - - // - fakeBreakedZone.Clean(); - - // - bar.Clean(); - flagSwing.Clean(); - - // - pvAnalysis.Clean(); - sarAnalysis.Clean(); - zigzagAnalysis.Clean(); - - // - trendDir = X_DIRECTION_NONE; - pinnedDir = X_DIRECTION_NONE; - momentumDir = X_DIRECTION_NONE; - engulfedDir = X_DIRECTION_NONE; - trueGapedDir = X_DIRECTION_NONE; - flagPatternDir = X_DIRECTION_NONE; - starPatternDir = X_DIRECTION_NONE; - risingPatternDir = X_DIRECTION_NONE; - piercingPatternDir = X_DIRECTION_NONE; - signalKeyBarPatternDir = X_DIRECTION_NONE; - - // - maCrossDir = X_DIRECTION_NONE; - SpecifiedClean(maCrosses); - - // - hkSwitchDir = X_DIRECTION_NONE; - SpecifiedClean(hkSwitches); - - // - sarSwitchDir = X_DIRECTION_NONE; - SpecifiedClean(sarSwitches); - - // - SpecifiedClean(obs); - SpecifiedClean(fvgs); - SpecifiedClean(pinBars); - SpecifiedClean(supports); - SpecifiedClean(engulfBars); - SpecifiedClean(resistances); - SpecifiedClean(trueGapBars); - SpecifiedClean(momentumBars); - SpecifiedClean(flagPatterns); - SpecifiedClean(starPatterns); - SpecifiedClean(risingPatterns); - SpecifiedClean(piercingPatterns); - SpecifiedClean(signalKeyBarPatterns); - - // - SpecifiedClean(trendSwings); - SpecifiedClean(recentlyTestedZones); - SpecifiedClean(recentlyBreakedZones); - - // - ZeroMemory(this); - } - - // - // Checker Functions ... - - // -}; - -/** - * Configure Market Structure Drawer ... - **/ -struct XFIMAMarketStructureDrawerConfig -{ - // - // Props ... - - // - bool drawOB; // Current Order Block ... - bool drawFVG; // Current Fair Value Gap ... - - // - bool drawSupport; // Detected Supports ... - bool drawResistance; // Detected Resistances ... - - // - bool drawSwingTrend; // Swing Trend ... - bool swingTrendRayLeft; // Ray Left Swing Trend ... - bool swingTrendRayRight; // Ray Right Swing Trend ... - - // - // Draw Current Detected Patterns ... - - // - bool drawPinned; - bool drawMomentum; - bool drawEngulfed; - bool drawTrueGaped; - - // - bool drawStarPattern; - bool drawFlagPattern; - bool drawRisingPattern; - bool drawPiercingPattern; - bool drawSignalKeyBarPattern; - - // - // Draw Recently Zones ... - bool drawRecentPatterns; - bool drawFakeBreakedZone; - bool drawRecentlyTestedZones; - bool drawRecentlyBreakedZones; - - // - // Draw Analysis Pivots ... - - // - // XPV ... - bool drawFIMAPVPivotsAnalysis; - bool drawFIMAPVPivotsAnalysisZones; - bool drawFIMAPVPivotsAnalysisTrends; - bool drawFIMAPVPivotsAnalysisPivots; - - // - // XSAR ... - bool drawFIMASARPivotsAnalysis; - bool drawFIMASARPivotsAnalysisZones; - bool drawFIMASARPivotsAnalysisTrends; - bool drawFIMASARPivotsAnalysisPivots; - - // - // XZIGZAG ... - bool drawFIMAZigZagPivotsAnalysis; - bool drawFIMAZigZagPivotsAnalysisZones; - bool drawFIMAZigZagPivotsAnalysisTrends; - bool drawFIMAZigZagPivotsAnalysisPivots; - - // - // Constructor ... - XFIMAMarketStructureDrawerConfig() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - drawOB = false; - drawFVG = false; - drawPinned = false; - drawMomentum = false; - drawSupport = false; - drawEngulfed = false; - drawTrueGaped = false; - drawResistance = false; - drawSwingTrend = false; - drawStarPattern = false; - drawFlagPattern = false; - swingTrendRayLeft = false; - drawRisingPattern = false; - swingTrendRayRight = false; - drawPiercingPattern = false; - drawSignalKeyBarPattern = false; - - // - drawRecentPatterns = false; - drawFakeBreakedZone = false; - drawRecentlyTestedZones = false; - drawRecentlyBreakedZones = false; - - // - drawFIMAPVPivotsAnalysis = false; - drawFIMAPVPivotsAnalysisZones = false; - drawFIMAPVPivotsAnalysisTrends = false; - drawFIMAPVPivotsAnalysisPivots = false; - - // - drawFIMASARPivotsAnalysis = false; - drawFIMASARPivotsAnalysisZones = false; - drawFIMASARPivotsAnalysisTrends = false; - drawFIMASARPivotsAnalysisPivots = false; - - // - drawFIMAZigZagPivotsAnalysis = false; - drawFIMAZigZagPivotsAnalysisZones = false; - drawFIMAZigZagPivotsAnalysisTrends = false; - drawFIMAZigZagPivotsAnalysisPivots = false; - - // - ZeroMemory(this); - } - - /** - * Default Model ... - */ - void Default() - { - drawOB = true; - drawFVG = true; - drawPinned = true; - drawMomentum = true; - drawSupport = true; - drawEngulfed = true; - drawTrueGaped = true; - drawResistance = true; - drawSwingTrend = true; - drawStarPattern = true; - drawFlagPattern = true; - drawRisingPattern = true; - drawPiercingPattern = true; - swingTrendRayLeft = false; - swingTrendRayRight = true; - drawSignalKeyBarPattern = true; - - // - drawRecentPatterns = true; - drawFakeBreakedZone = true; - drawRecentlyTestedZones = true; - drawRecentlyBreakedZones = true; - - // - drawFIMAPVPivotsAnalysis = true; - drawFIMAPVPivotsAnalysisZones = true; - drawFIMAPVPivotsAnalysisTrends = true; - drawFIMAPVPivotsAnalysisPivots = true; - - // - drawFIMASARPivotsAnalysis = true; - drawFIMASARPivotsAnalysisZones = true; - drawFIMASARPivotsAnalysisTrends = true; - drawFIMASARPivotsAnalysisPivots = true; - - // - drawFIMAZigZagPivotsAnalysis = true; - drawFIMAZigZagPivotsAnalysisZones = true; - drawFIMAZigZagPivotsAnalysisTrends = true; - drawFIMAZigZagPivotsAnalysisPivots = true; - } - - /** - * Configure for Full Drawing ... - */ - void FullDraw() - { - // - Default(); - - // - drawOB = true; - drawFVG = true; - drawPinned = true; - drawMomentum = true; - drawSupport = true; - drawEngulfed = true; - drawTrueGaped = true; - drawResistance = true; - drawSwingTrend = true; - drawStarPattern = true; - drawFlagPattern = true; - drawRisingPattern = true; - swingTrendRayLeft = true; - swingTrendRayRight = true; - drawPiercingPattern = true; - drawSignalKeyBarPattern = true; - - // - drawRecentPatterns = true; - drawFakeBreakedZone = true; - drawRecentlyTestedZones = true; - drawRecentlyBreakedZones = true; - - // - drawFIMAPVPivotsAnalysis = true; - drawFIMAPVPivotsAnalysisZones = true; - drawFIMAPVPivotsAnalysisTrends = true; - drawFIMAPVPivotsAnalysisPivots = true; - - // - drawFIMASARPivotsAnalysis = true; - drawFIMASARPivotsAnalysisZones = true; - drawFIMASARPivotsAnalysisTrends = true; - drawFIMASARPivotsAnalysisPivots = true; - - // - drawFIMAZigZagPivotsAnalysis = true; - drawFIMAZigZagPivotsAnalysisZones = true; - drawFIMAZigZagPivotsAnalysisTrends = true; - drawFIMAZigZagPivotsAnalysisPivots = true; - } - - // -}; diff --git a/Documents/BKP/x-saherelm.xfima.signaller.class copy 2.mq5 b/Documents/BKP/x-saherelm.xfima.signaller.class copy 2.mq5 deleted file mode 100644 index b2d9299d..00000000 --- a/Documents/BKP/x-saherelm.xfima.signaller.class copy 2.mq5 +++ /dev/null @@ -1,2249 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - bool ignoreTargets; // Ignore Signal Targets ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - /** - * Check Specified Bar has Pattern or not ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param name: string, reference to holds Detected Patterns Name ... - * @param dir: ENUM_X_DIRECTION, reference to holds Detected Patterns Direction ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool HasPattern( - XOHCL &bar, - string &patternName, - ENUM_X_DIRECTION &patternDir, - XFIMAMarketStructure &structure // - ) - { - // - bool result = false; - - // - // Prepare ... - patternName = NULL; - patternDir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(structure.pinnedDir); - bool hasEngulfedBar = HasDirection(structure.engulfedDir); - bool hasFlagPattern = HasDirection(structure.flagPatternDir); - bool hasStarPattern = HasDirection(structure.starPatternDir); - bool hasRisingPattern = HasDirection(structure.risingPatternDir); - bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - - // - // Check Bar Pattern Exists ... - // and Select Pattern Direction and Price and Price Type ... - result = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - - // - if (result) - { - // - if (hasPinnedBar) - { - // - patternDir = structure.pinnedDir; - patternName = "XPinned_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - patternDir = structure.engulfedDir; - patternName = "XEngulfed_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - patternDir = structure.flagPatternDir; - patternName = "XFlag_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - patternDir = structure.starPatternDir; - patternName = "XStar_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - patternDir = structure.risingPatternDir; - patternName = "XRising_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - patternDir = structure.piercingPatternDir; - patternName = "XPiercing_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - patternDir = structure.signalKeyBarPatternDir; - patternName = "XSignalKey_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - } - - // - result = - result && - IsXValid(patternName) && - HasDirection(patternDir); - - // - return result; - } - - /** - * Validate a Pattern based on MA Band ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param patternName: string, detected pattern's name ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ - bool ValidatePatternBasedOnMABand( - XOHCL &bar, - string patternName, - ENUM_X_DIRECTION patternDir, - XFIMAConditions &fimaConditions // - ) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - IsXValid(patternName) && - HasDirection(patternDir); - if (!result) - { - return result; - } - - // - // Define Requirements ... - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - double iPriceEdge = EMPTY_VALUE; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_PRICE iPriceEdgeType = X_PRICE_NONE; - - // - // Calculating Price and Price Types ... - - // - isBullish = IsXBullish(patternDir); - isBearish = IsXBearish(patternDir); - - // - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - - // - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate ... - result = - NotEmptyZero(iPrice) && - IsXValid(iPriceType) && - NotEmptyZero(iPriceEdge) && - IsXValid(iPriceEdgeType) && - ((isBullish && !isBearish) || - (isBearish && !isBullish)); - if (!result) - { - return result; - } - - // - // Validate Pattern based on MA Band ... - - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fimaConditions.maBondUpperBuffer[0]; - double iMABandLower = fimaConditions.maBondLowerBuffer[0]; - - // - // Validate by Edge Price ... - result = - NotEmptyZero(iMABandUpper) && - NotEmptyZero(iMABandLower) && - (isBullish - ? iPriceEdge < iMABandLower - : iPriceEdge > iMABandUpper); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - CArrayObj drawnObjects; - // XFIMAPatternDetectorConfig analyserConfig; - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure Detector ... - - // - analyserConfig.Default(); - analyserConfig.validMACrossDiffMultiplier = 4; - - // - analyserConfig.FullDetect(); - - // - // Ignore Signal Targets ... - ignoreTargets = true; - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - - // - analyserConfig.Clean(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - int count = 0; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - string iName = NULL; - bool isBullish = false; - bool isBearish = false; - XPatternAnalysis iBarAnalysis; - XFIMAConditions iFIMAConditions; - XFIMAMarketStructure iStructure; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - iFIMAConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - iBar.Clean(); - iFIMAConditions.Clean(); - - // - return; - } - - // - // Analyse Market ... - poiDetector.AnalyseMarket( - iBar, - iStructure, - analyserConfig // - ); - - // - // Bar Pattern Analysis Detection Test ... - has = poiDetector.AnalyseBarPatterns( - iBar, - iBarAnalysis - // - // Use Default Config ... - ); - DrawBarPatternAnalysis(iBarAnalysis); - - // - // Disable Signallers ... - has = false; - iDir = X_DIRECTION_NONE; - - // - // Strategy 1 ... - // Works on Support or Resistances Areas ... - // has = Strategy1HasSignal( - // iBar, - // iZone, - // iTargets, - // iDir, - // iFIMAConditions, - // iStructure // - // ); - - // - // Strategy 2 ... - // Works on MA Crosses ... - if (!has) - { - // - // has = Strategy2HasSignal( - // iBar, - // iZone, - // iTargets, - // iDir, - // iFIMAConditions, - // iStructure // - // ); - } - - // - has = HasDirection(iDir); - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // TODO: Provided SL ... - double _point = GetPoints(iBar.symbol); - double slAddition = 5 * _point; - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - - // - // Handle Signal Targets ... - if (ignoreTargets) - { - XClean(iTargets); - } - - // - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(iSignal); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - iStructure.Clean(); - iBarAnalysis.Clean(); - iFIMAConditions.Clean(); - SpecifiedClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &structure // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Pattern Exists ... - string patternName = NULL; - ENUM_X_DIRECTION patternDir = X_DIRECTION_NONE; - result = HasPattern( - bar, - patternName, - patternDir, - structure // - ); - if (!result) - { - return result; - } - - // - // Validate Pattern Based on MA Band ... - result = ValidatePatternBasedOnMABand( - bar, - patternName, - patternDir, - conditions // - ); - if (!result) - { - return result; - } - - // - // Here i Use Specified Supports and Resistances ... - XBoxZone tmpBox; - bool has = false; - XBoxZone supports[]; - XBoxZone resistances[]; - - // - has = structure.pvAnalysis.IsValid() && - structure.pvAnalysis.HasSupportBox(tmpBox); - if (has) - { - // - tmpBox.to = bar.time; - AddIfNotExists( - tmpBox, - supports // - ); - } - - // - has = structure.zigzagAnalysis.IsValid() && - structure.zigzagAnalysis.HasSupportBox(tmpBox); - if (has) - { - // - tmpBox.to = bar.time; - AddIfNotExists( - tmpBox, - supports // - ); - } - - // - has = structure.pvAnalysis.IsValid() && - structure.pvAnalysis.HasResistanceBox(tmpBox); - if (has) - { - // - tmpBox.to = bar.time; - AddIfNotExists( - tmpBox, - resistances // - ); - } - - // - has = structure.zigzagAnalysis.IsValid() && - structure.zigzagAnalysis.HasResistanceBox(tmpBox); - if (has) - { - // - tmpBox.to = bar.time; - AddIfNotExists( - tmpBox, - resistances // - ); - } - - // - // Check Affected Zone ... - // Select a Support or Resistance ... - int insideZoneIDX = -1; - result = - (IsXBullish(patternDir) - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : IsXBearish(patternDir) - ? HasInside( - insideZoneIDX, - bar, - resistances // - ) - : false // - ); - if (!result) - { - return result; - } - - // - // Filling Affected Zone ... - // and Validate it ... - if (IsXBullish(patternDir)) - { - zone = supports[insideZoneIDX]; - } - else if (IsXBearish(patternDir)) - { - zone = resistances[insideZoneIDX]; - } - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - // Validate affected Zone based on Pattern's Bar ... - result = IsXBullish(patternDir) - ? bar.high > zone.upper - : IsXBearish(patternDir) - ? bar.low < zone.lower - : false; - // - // Validate Zone ... - if (result) - { - // - // - } - - // - // Draw Requirements ... - // if (result) - // { - // // - // // Support and Resistances ... - // CArrayObj *zoneObjs; - // poiDrawer.DrawBoxes( - // supports, - // zoneObjs // - // ); - // poiDrawer.DrawBoxes( - // resistances, - // zoneObjs // - // ); - - // // - // // Zone ... - // XCBoxObject *iZoneObj; - // bool isDrawn = poiDrawer.DrawBox( - // zone, - // iZoneObj, - // true, - // zone.type // - // ); - // if (isDrawn) - // { - // // - // XPOIStyle iStyle; - // iStyle.width = 2; - // iStyle.clr = clrYellow; - // poiDrawer.ApplyBoxStyle( - // iZoneObj, - // iStyle // - // ); - // } - - // // - // // Pattern ... - // XCBarArrowObject *iPObj; - // poiDrawer.DrawBarArrow( - // bar, - // iPObj, - // zone.IsBullish() ? X_PRICE_LOW : X_PRICE_HIGH, - // 159, - // clrYellow, - // 3, // With ... - // zone.IsBullish() ? ANCHOR_BOTTOM : ANCHOR_TOP, - // patternName // - // ); - - // // poiDrawer.DrawBoxes( - // // structure.fvgs, - // // zoneObjs, - // // false // - // // ); - - // Print("SALAM"); - // } - - if (result) - { - // - dir = patternDir; - - // - // Handle Targets Detection ... - - // - // Check Reversal FVGS ... - int idx = -1; - XTarget target; - XBoxZone targetZones[]; - int numberOfTargets = 3; - double actingDistance = 20; - double iValue = EMPTY_VALUE; - bool ignoreFirstTarget = false; - ENUM_X_DIRECTION targetsDir = Opposit(dir); - int count = ExtractByDirection( - targetZones, - structure.fvgs, - targetsDir // - ); - bool has = IsValidSize(count); - if (has) - { - // - // Calculate Value ... - double points = GetPoints(zone.symbol); - double zoneRange = zone.upper - zone.lower; - iValue = IsXBullish(dir) - ? (zone.upper + (zoneRange * defaultSignalR2R)) - : (zone.lower + (zoneRange * defaultSignalR2R)); - double defaultTarget = iValue; - - // - // Looping Back ... - for (int i = 0; i < numberOfTargets; i++) - { - // - // Detect Lowest Above Zone ... - if (IsXBullish(dir)) - { - // - idx = GetLowestAbove(iValue, targetZones); - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - iValue = targetZones[idx].lower; - } - // - // Detect Highest below Zone ... - else if (IsXBearish(dir)) - { - // - idx = GetHighestBelow(iValue, targetZones); - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - iValue = targetZones[idx].upper; - } - - // - // Validate Target Value ... - has = NotEmptyZero(iValue) && - iValue != defaultTarget; - if (has) - { - // - // Init Target ... - target.Clean(); - target.doRF = true; - target.target = iValue; - target.actingDistance = actingDistance; - has = target.IsValid(); - if (has) - { - // - // Add Target to Targets ... - AddRef( - target, - targets // - ); - } - target.Clean(); - } - } - - // - // Remove Nearest ... - has = ignoreFirstTarget && - HasChild(targets); - if (has) - { - // - ArrayRemove( - targets, - 0, - 1 // - ); - } - } - - // - // Cleanup Resources ... - target.Clean(); - XClean(targetZones); - } - - // - // Cleanup Resources ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - } - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &structure // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Detect Specified MA Cross ... - result = HasDirection(structure.maCrossDir); - - // - // Prepare zone ... - if (result) - { - // - zone.to = bar.time; - zone.from = GetBarTime( - bar.symbol, - bar.period, - bar.Index() + 2 // - ); - zone.symbol = bar.symbol; - zone.period = bar.period; - zone.dir = structure.maCrossDir; - zone.lower = bar.FindLowest(2, MODE_LOW); - zone.upper = bar.FindHighest(2, MODE_HIGH); - zone.type = name + "_" + ToXString(structure.maCrossDir); - - // - result = zone.IsValid(); - } - - // - // Check Result ... - if (result) - { - // - dir = structure.maCrossDir; - - // - // Handle Targets Detection ... - } - - // - // Cleanup Resources ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - } - - // - return result; - } - - // - // Drawer Functions ... - - /** - * Draw Specified Pattern info ... - * - * @param _bar: XOHCL, reference to Pattern's Bar ... - * @param _pivot: XPivot, reference to Pattern's Pivot ... - * @param _zone: XBoxZone, reference to Pattern's Zone ... - * @param _pattern: ENUM_X_BAR_PATTERN, Specified Bar Pattern ... - * @param _patternDir: ENUM_X_DIRECTION, Specified Bar Pattern's Direction ... - */ - void DrawPattern( - XOHCL &_bar, - XPivot &_pivot, - XBoxZone &_zone, - ENUM_X_BAR_PATTERN _pattern, - ENUM_X_DIRECTION _patternDir, - int thresholdMultiplier = 0 // - ) - { - // - // Normalize ... - thresholdMultiplier = NormalizeInt(thresholdMultiplier, 1); - - // - // Validate ... - bool has = - poiDrawer != NULL && - _bar.IsValid() && - IsXValid(_pattern) && - HasDirection(_patternDir); - if (!has) - { - return; - } - - // - // Defien Draw Requirements ... - - // - int width = 3; - bool ignoreBoxAt = true; - int arrowThreshold = 5 * thresholdMultiplier; - - // - int bullishArrow = 159; - int bearishArrow = 159; - - // - ENUM_X_PRICE arrowValePriceType = X_PRICE_LOW; - ENUM_X_PRICE arrowPeakPriceType = X_PRICE_HIGH; - - // - color bullishColor = clrAqua; - color bearishColor = clrMagenta; - - // - // Draw Bar ... - - // - // Draw Pivot ... - if (_pivot.IsValid()) - { - // - XCBarArrowObject *iObj; - has = poiDrawer.DrawBarArrow( - _bar, - iObj, - _pivot.IsPeak() - ? arrowPeakPriceType - : arrowValePriceType, - IsXBullish(_patternDir) - ? bullishArrow - : bearishArrow, - IsXBullish(_patternDir) - ? bullishColor - : bearishColor, - width, - IsXBullish(_patternDir) - ? ANCHOR_TOP - : ANCHOR_BOTTOM, - _pivot.prefix + "_Pivot_" + ToXString(TimeToSeconds(_pivot.time)), - true, // Ignore Bar Tag ... - arrowThreshold // Threshold ... - ); - if (has) - { - drawnObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Draw Box ... - if (_zone.IsValid()) - { - // - XCBoxObject *iObj; - has = poiDrawer.DrawBox( - _zone, - iObj, - ignoreBoxAt, - _zone.type + "_Zone_" + ToXString(TimeToSeconds(_zone.from)) // - ); - if (has) - { - // - XPOIStyle iStyle; - poiDrawer.GetBoxStyle( - iStyle, - _zone.dir // - ); - - // - iStyle.clr = - IsXBullish(_patternDir) - ? bullishColor - : bearishColor; - - // - poiDrawer.ApplyBoxStyle( - iObj, - iStyle // - ); - - // - drawnObjects.Add(iObj); - - // - iStyle.Clean(); - } - - // - ZeroMemory(iObj); - } - } - - /** - * Draw Specified Bar Pattern Analysis ... - * - * @param barAnalysis: XPatternAnalysis, reference to Specified Bar Pattern Analysis ... - */ - void DrawBarPatternAnalysis(XPatternAnalysis &barAnalysis) - { - // - bool has = barAnalysis.IsValid(); - if (!has) - { - return; - } - - // - // Configure Draws ... - XPatternAnalysisDrawConfig config; - config.Clean(); - - // - Add(X_BAR_PATTERN_LOW, config.allowedDraws); - Add(X_BAR_PATTERN_HIGH, config.allowedDraws); - Add(X_BAR_PATTERN_STAR, config.allowedDraws); - Add(X_BAR_PATTERN_FLAG, config.allowedDraws); - Add(X_BAR_PATTERN_PINNED, config.allowedDraws); - Add(X_BAR_PATTERN_RISING, config.allowedDraws); - Add(X_BAR_PATTERN_MOMENTUM, config.allowedDraws); - Add(X_BAR_PATTERN_ENGULFED, config.allowedDraws); - Add(X_BAR_PATTERN_PIERCING, config.allowedDraws); - Add(X_BAR_PATTERN_SIGNALKEY, config.allowedDraws); - Add(X_BAR_PATTERN_TRUE_GAPED, config.allowedDraws); - - // - Add(X_BAR_PATTERN_LOW, config.allowedDrawPivots); - Add(X_BAR_PATTERN_HIGH, config.allowedDrawPivots); - Add(X_BAR_PATTERN_PINNED, config.allowedDrawPivots); - Add(X_BAR_PATTERN_MOMENTUM, config.allowedDrawPivots); - Add(X_BAR_PATTERN_ENGULFED, config.allowedDrawPivots); - Add(X_BAR_PATTERN_TRUE_GAPED, config.allowedDrawPivots); - - // - Add(X_BAR_PATTERN_STAR, config.allowedDrawZones); - Add(X_BAR_PATTERN_FLAG, config.allowedDrawZones); - Add(X_BAR_PATTERN_RISING, config.allowedDrawZones); - Add(X_BAR_PATTERN_PIERCING, config.allowedDrawZones); - Add(X_BAR_PATTERN_SIGNALKEY, config.allowedDrawZones); - - // - Add(X_BAR_PATTERN_SUPPORT, config.allowedDraws); - Add(X_BAR_PATTERN_RESISTANCE, config.allowedDraws); - - // - Add(X_BAR_PATTERN_SUPPORT, config.allowedDrawZones); - Add(X_BAR_PATTERN_RESISTANCE, config.allowedDrawZones); - - // - config.Clean(); - - // - // Draw Bar Patterns Analysis ... - - // - bool canDraw; - bool isBullish; - bool isBearish; - XOHCL patternBar; - bool canDrawZone; - bool canDrawPivot; - XPivot patternPivot; - XBoxZone patternBox; - ENUM_X_BAR_PATTERN pattern; - ENUM_X_DIRECTION patternDir; - - // - int patternsPivotThresholdMultiplier = 0; - - // - // Support and Resistance ... - - // - // Support ... - isBearish = false; - isBullish = barAnalysis.IsSupport(); - has = isBullish; - if (has) - { - // - pattern = X_BAR_PATTERN_SUPPORT; - patternDir = X_DIRECTION_BULLISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Resistance ... - isBullish = false; - isBearish = barAnalysis.IsResistance(); - has = isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_RESISTANCE; - patternDir = X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // PV: High and Low ... - - // - // Low ... - isBearish = false; - isBullish = barAnalysis.IsLow(); - has = isBullish; - if (has) - { - // - pattern = X_BAR_PATTERN_LOW; - patternDir = X_DIRECTION_BULLISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // High ... - isBullish = false; - isBearish = barAnalysis.IsHigh(); - has = isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_HIGH; - patternDir = X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // OB ... - isBullish = barAnalysis.IsOB(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsOB(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_OB; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // FVG ... - isBullish = barAnalysis.IsFVG(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsFVG(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_FVG; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Momentum ... - isBullish = barAnalysis.IsMomentum(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsMomentum(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_MOMENTUM; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Engulfed ... - isBullish = barAnalysis.IsEngulfed(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsEngulfed(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_ENGULFED; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Pinned ... - isBullish = barAnalysis.IsPinned(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsPinned(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_PINNED; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // TrueGaped ... - isBullish = barAnalysis.IsTrueGaped(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsTrueGaped(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_TRUE_GAPED; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Star ... - isBullish = barAnalysis.IsStar(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsStar(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_STAR; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Piercing ... - isBullish = barAnalysis.IsPiercing(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsPiercing(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_PIERCING; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Rising ... - isBullish = barAnalysis.IsRising(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsRising(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_RISING; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Flag ... - isBullish = barAnalysis.IsFlag(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsFlag(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_FLAG; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // SignalKey ... - isBullish = barAnalysis.IsSignalKey(X_DIRECTION_BULLISH); - isBearish = barAnalysis.IsSignalKey(X_DIRECTION_BEARISH); - has = isBullish || isBearish; - if (has) - { - // - pattern = X_BAR_PATTERN_SIGNALKEY; - patternDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - canDraw = config.CanDraw(pattern); - if (canDraw) - { - // - has = barAnalysis.GetPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir // - ); - if (has) - { - // - canDrawZone = config.CanDrawZone(pattern); - if (!canDrawZone) - { - patternBox.Clean(); - } - - // - canDrawPivot = config.CanDrawPivot(pattern); - if (!canDrawPivot) - { - patternPivot.Clean(); - } - else - { - patternsPivotThresholdMultiplier++; - } - - // - DrawPattern( - patternBar, - patternPivot, - patternBox, - pattern, - patternDir, - patternsPivotThresholdMultiplier // - ); - } - } - } - - // - // Cleanup Resources ... - patternBar.Clean(); - patternBox.Clean(); - patternPivot.Clean(); - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.signaller.class copy 3.mq5 b/Documents/BKP/x-saherelm.xfima.signaller.class copy 3.mq5 deleted file mode 100644 index b29a2e53..00000000 --- a/Documents/BKP/x-saherelm.xfima.signaller.class copy 3.mq5 +++ /dev/null @@ -1,1657 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - bool ignoreTargets; // Ignore Signal Targets ... - CArrayObj drawnObjects; // Drawing Objects Holder ... - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - XFIMAMarketStructureConfig structureConfig; // XFIMA Market Structure Detector Config ... - XFIMAMarketStructureDrawerConfig structureDrawConfig; // XFIMA Market Structure Draw Config ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper); - - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - - // - structureConfig.Clean(); - structureDrawConfig.Clean(); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - XFIMAMarketStructure structure; // XFIMA Market Structure ... - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure ... - structureConfig.Default(); - structureDrawConfig.Default(); - - // - structure.Clean(); - - // - // Ignore Signal Targets ... - ignoreTargets = false; - } - - // - // Deconstructor ... - ~XCXFIMAStrategy1Signaller() - { - // - Destroy(); - - // - structure.Clean(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - int count = 0; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget iTargets[]; - string iName = NULL; - bool isBullish = false; - bool isBearish = false; - XFIMAConditions iFIMAConditions; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - iFIMAConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - iBar.Clean(); - iFIMAConditions.Clean(); - - // - return; - } - - // - structure.Clean(); - poiDetector.AnalyseMarket( - structure, - structureConfig, - barIndex // - ); - // poiDrawer.drawnObjects.Clear(); - // poiDrawer.DrawMarketStructure( - // structure, - // structureDrawConfig // - // ); - - // - // Strategy 1 ... - // has = Strategy1HasSignal( - // iBar, - // iZone, - // iTargets, - // iDir, - // iFIMAConditions, - // structure // - // ); - - // - // Strategy 2 ... - if (!has) - { - // // - // has = Strategy2HasSignal( - // iBar, - // iZone, - // iTargets, - // iDir, - // iFIMAConditions, - // structure // - // ); - } - - // - // Strategy 3 ... - if (!has) - { - // - // has = Strategy3HasSignal( - // iBar, - // iZone, - // iTargets, - // iDir, - // iFIMAConditions, - // structure // - // ); - } - - // - // Strategy 4 ... - has = false; - if (!has) - { - // - has = Strategy4HasSignal( - iBar, - iZone, - iTargets, - iDir, - iFIMAConditions, - structure // - ); - } - - // - has = HasDirection(iDir) && - iZone.IsValid(); - if (has) - { - // - has = false; - iZone.Clean(); - iDir = X_DIRECTION_NONE; - } - - // - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // TODO: Provided SL ... - double _point = GetPoints(iBar.symbol); - double slAddition = 5 * _point; - double atrAddition = GetAverageTrueRange( - iZone.symbol, - iZone.period, - 0 // - ); - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - - // - // Handle Signal Targets ... - if (ignoreTargets) - { - XClean(iTargets); - } - - // - has = PrepareSignal( - iSignal, - iDir, - iTargets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(iSignal); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - iFIMAConditions.Clean(); - SpecifiedClean(iTargets); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard, reference collection to holds result ... - * @param positions: XPosition, reference collection to provides positions ... - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - XPosition &positions[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &_structure // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Testing Porposes ... - result = - result && - fimaHelper.IsBoundaryFakeBreaked( - dir, - bar.Index(), - X_PRICE_CLOSE, - X_PRICE_CLOSE // - ); - - // - // Nearest Noisy ZG Pivot Must has Same Direction - // by Boundary Faked Break ... - result = - result && - HasDirection(dir) && - _structure.zgAnalysis.IsValid() && - _structure.zgAnalysis.HasPivots() && - _structure.zgAnalysis.pivots[0].dir == dir; - - // - // We Have to Detect a Zone which Nearest ZG Pivot Reject or goes inside it ... - - // - int idx = -1; - XOHCL tmpBar; - XPivot pivot; - XPivot pivots[]; - XBoxZone zones[]; - bool has = false; - int zonesCount = 0; - int pivotIndex = -1; - XBoxZone affectedZone; - double bullishScore = 0; - double bearishScore = 0; - int prevPivotIndex = -1; - XBoxZone affectedZones[]; - int affectedZonesCount = 0; - - // - Copy( - _structure.zgAnalysis.pivots, - pivots // - ); - pivot = pivots[0]; - ArrayRemove(pivots, 0, 1); - - // - bool isBullish = IsXBullish(dir); - bool isBearish = IsXBearish(dir); - - // - zonesCount = _structure.CollectZones( - zones, - dir // - ); - result = result && - IsValidSize(zonesCount); - - // - // Noisey ZG Pivot must inside atleast one of Zones ... - - // - // Initial Pivots Bar ... - result = - result && - bar.BarAt(pivot.time, tmpBar); - - // - // Extract Affected Zones ... - if (result) - { - // - affectedZonesCount = ExtractAffectedZones( - tmpBar, - zones, - affectedZones, - dir // - ); - } - - // - // Validate Affected Zones ... - result = - result && - HasChild(affectedZones) && - affectedZonesCount >= 1; - if (result) - { - affectedZone = affectedZones[0]; - } - result = - result && - affectedZone.IsValid() && - (isBullish - ? bar.close > affectedZone.upper - : bar.close < affectedZone.lower); - - // - // There Must another Same Directional ZG Pivot Exists - // which is Affect another Zone ... - idx = GetYoungest(pivots, pivot.type); - result = - result && - IsValidIndex(idx) && - affectedZone.IsValid() && - (isBullish - ? pivots[idx].value < pivot.value - : pivots[idx].value > pivot.value); - if (result) - { - // - pivot.Clean(); - tmpBar.Clean(); - pivot = pivots[idx]; - XClean(affectedZones); - ArrayRemove(pivots, idx, 1); - - // - result = bar.BarAt(pivot.time, tmpBar); - } - - // - // Extract Affected Zones ... - XClean(affectedZones); - affectedZonesCount = 0; - if (result) - { - // - affectedZonesCount = ExtractAffectedZones( - tmpBar, - zones, - affectedZones, - dir // - ); - } - result = - result && - HasChild(affectedZones) && - affectedZonesCount >= 1; - - // - // Handling Scores ... - if (result) - { - // - for (int i = 0; i < ArraySize(_structure.barsAnalysis); i++) - { - // - bullishScore += _structure.barsAnalysis[i].Count(X_DIRECTION_BULLISH); - bearishScore += _structure.barsAnalysis[i].Count(X_DIRECTION_BEARISH); - } - } - result = - isBullish - ? bullishScore > bearishScore - : bearishScore > bullishScore; - - // - // Last Validation is Candlestick Patterns of Bar ... - // XPatternAnalysis barAnalysis; - // result = - // result && - // poiDetector.AnalyseBarPatterns( - // bar, - // barAnalysis, - // structureConfig.barsAnalysisConfig // - // ); - - // - if (!result) - { - // - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // Drawa ... - if (result) - { - // - // Affected Zone ... - XCBoxObject *iObj; - has = poiDrawer.DrawBox( - affectedZone, - iObj, - true, - affectedZone.type + "_" + ToXString(TimeToSeconds(affectedZone.from)) // - ); - if (has) - { - // - XPOIStyle iStyle; - poiDrawer.GetBoxStyle( - iStyle, - affectedZone.dir // - ); - iStyle.clr = clrYellow; - poiDrawer.ApplyBoxStyle( - iObj, - iStyle // - ); - iStyle.Clean(); - - // - Print("Affected Zone ..."); - } - - // - // Draw Bar Pattern ... - // poiDrawer.DrawPatternAnalysis(barAnalysis, structureDrawConfig.barAnalysisDrawConfig); - } - - // - // Prepare zone ... - if (result) - { - // - zone = affectedZone; - - // - zone.type = name + "_" + ToXString(dir); - - // - double entry = GetEntry(bar.symbol, dir); - double points = GetPoints(bar.symbol); - double risk = MathAbs(entry - (isBullish ? zone.lower : zone.upper)); - double reward = risk * defaultSignalR2R; - - // - // Partially Close on TP 1 ... - double tp1 = isBullish - ? entry + (risk * 1) - : entry - (risk * 1); - XTarget target1; - target1.target = tp1; - target1.doRF = false; - target1.actingDistance = 2; - target1.volumeMultiplier = 0.5; - - // - // TP 3 ... - double tp3 = isBullish - ? entry + (risk * 3) - : entry - (risk * 3); - XTarget target3; - target3.target = tp3; - target3.doRF = true; - target3.actingDistance = 10; - - // - // TP 5 ... - double tp5 = isBullish - ? entry + (risk * 5) - : entry - (risk * 5); - XTarget target5; - target5.target = tp5; - target5.doRF = true; - target5.actingDistance = 10; - - // - AddRef( - target1, - targets // - ); - AddRef( - target3, - targets // - ); - AddRef( - target5, - targets // - ); - - // - result = zone.IsValid(); - } - - // - // Check Result ... - if (result) - { - // - // dir = structure.maCrossDir; - - // - // Handle Targets Detection ... - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - } - - // - pivot.Clean(); - XClean(zones); - tmpBar.Clean(); - XClean(pivots); - affectedZone.Clean(); - XClean(affectedZones); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 2 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &_structure // - ) - { - // - bool result = false; - - // - // Prepare ... - XOHCL pBar; - XOHCL p2Bar; - zone.Clean(); - pBar.Clean(); - p2Bar.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid() && - bar.GetPreviousBar(pBar) && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - return result; - } - - // - result = false; - bool isBullish = false; - bool isBearish = false; - ENUM_X_DIRECTION tmpDir; - - // - // Do Signal Detection ... - - // - // Preparing Requirement Conditions ... - // Here we Have to Prepare Some Directional Confirmations Using Indicators ... - // for Validate Signals ... - - // - int verifierBarIndex = pBar.Index(); - - // - bool hasSarSwitch = fimaHelper.HasSARSwitch(tmpDir, verifierBarIndex); - bool isSarSwitchedToBullish = hasSarSwitch && - IsXBullish(tmpDir); - bool isSarSwitchedToBearish = hasSarSwitch && - IsXBearish(tmpDir); - - // - bool hasMACross = fimaHelper.HasMACross( - tmpDir, - verifierBarIndex, - structureConfig.maCrossValidationDiffMultiplier // - ); - bool isCrossedOver = hasMACross && - IsXBullish(tmpDir); - bool isCrossedUnder = hasMACross && - IsXBearish(tmpDir); - - // - bool hasHKSwitch = fimaHelper.HasHKSwitch(tmpDir, verifierBarIndex); - bool isHKSwitchedToBullish = hasHKSwitch && - IsXBullish(tmpDir); - bool isHKSwitchedToBearish = hasHKSwitch && - IsXBearish(tmpDir); - - // - bool isBoundaryFakeBreaked = fimaHelper.IsBoundaryFakeBreaked(tmpDir, verifierBarIndex); - bool isBoundaryFakeBreakedBullish = isBoundaryFakeBreaked && - IsXBullish(tmpDir); - bool isBoundaryFakeBreakedBearish = isBoundaryFakeBreaked && - IsBearish(tmpDir); - - // - bool hasZigZagHigherLow = fimaHelper.HasZigZagHigherLow(bar.Index(), true); - bool hasZigZagLowerHigh = fimaHelper.HasZigZagLowerHigh(bar.Index(), true); - - // - // Summarize Confirmations ... - - // - bool isBullishConfirmed = - (hasZigZagHigherLow && - ( - // - isCrossedOver || - isHKSwitchedToBullish || - isSarSwitchedToBullish || - isBoundaryFakeBreakedBullish - // - )); - - // - bool isBearishConfirmed = - (hasZigZagLowerHigh && - ( - // - isCrossedUnder || - isHKSwitchedToBearish || - isSarSwitchedToBearish || - isBoundaryFakeBreakedBullish - // - )); - - // - // Validation Patterns ... - int directionalPatternsValidations = 3; - - // - // Check Bullish Conditions ... - isBullish = - // - // Confirmations Passed ... - isBullishConfirmed && - // - // Quarters Has Minor Support Zone ... - _structure.barAnalysis.HasMinorSupport() && - // - // Current Bar's Price Placed Propper ... - bar.open > _structure.barAnalysis.minorSupport.upper && - bar.close > _structure.barAnalysis.minorSupport.upper && - // - // Required Number of Pivots Validation Exists ... - (_structure.barsAnalysis[1].Count(X_DIRECTION_BULLISH) >= directionalPatternsValidations) && - // - // Bar or PBar ReTested Quarter Zone ... - (IsTested( - pBar, - _structure.barAnalysis.minorSupport // - ) || - IsTested( - p2Bar, - _structure.barAnalysis.minorSupport // - )) - // - ; - - // - // Check Bearish Conditions ... - isBearish = - // - // Confirmations Passed ... - isBearishConfirmed && - // - // Quarters Has Minor Resistance Zone ... - _structure.barAnalysis.HasMinorResistance() && - // - // Current Bar's Price Placed Propper ... - bar.open < _structure.barAnalysis.minorResistance.lower && - bar.close < _structure.barAnalysis.minorResistance.lower && - // - // Required Number of Pivots Validation Exists ... - (_structure.barsAnalysis[1].Count(X_DIRECTION_BEARISH) >= directionalPatternsValidations) && - // - // Bar or pBar ReTested Quarter Zone ... - (IsTested( - pBar, - _structure.barAnalysis.minorResistance // - ) || - IsTested( - p2Bar, - _structure.barAnalysis.minorResistance // - )) - // - ; - - // - // Summarize Conditions ... - result = - isBullish || - isBearish; - - // - // Assign Direction ... - if (result) - { - // - dir = isBullish - ? X_DIRECTION_BULLISH - : isBearish - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - if (isBullish) - { - zone = _structure.barAnalysis.minorSupport; - } - - // - if (isBearish) - { - zone = _structure.barAnalysis.minorResistance; - } - } - - // - // Validate Result ... - result = - result && - zone.IsValid() && - HasDirection(dir); - // if (result) - // { - // // - // XPOIDrawConfig iConfig = structureDrawConfig - // .barAnalysisDrawConfig - // .quarterMinorsDrawConfig; - // iConfig.zonesWidth = 3; - // iConfig.zonesFill = true; - // iConfig.bullishColor = clrYellow; - // iConfig.bearishColor = clrYellow; - - // // - // if (isBullish) - // { - // // - // poiDrawer.DrawZone( - // _structure.barAnalysis.minorSupport, - // iConfig // - // ); - - // // - // Print("Bullish Condition ..."); - // } - - // // - // if (isBearish) - // { - // // - // poiDrawer.DrawZone( - // _structure.barAnalysis.minorResistance, - // iConfig // - // ); - - // // - // Print("Bearish Condition ..."); - // } - - // // - // Print(ToXString(dir), " Detected ..."); - // } - - // - // Provide Direction and Targets if Required ... - if (result) - { - // - // Handle Targets Detection ... - - // - double spread = GetSpread(zone.symbol); - double entry = GetEntry(zone.symbol, dir); - - // - double risk = isBullish - ? entry - zone.lower - : zone.upper - entry; - double reward1 = entry + (isBullish - ? risk - : (-1 * risk) // - ); - double reward4 = entry + (isBullish - ? 4 * risk - : (-4 * risk) // - ); - double requiredDistance = PriceToPoint(spread * 2, zone.symbol); - - // - XTarget iRFOnEntryOnTP1; - iRFOnEntryOnTP1.target = reward1; - iRFOnEntryOnTP1.tpValue = reward4; - iRFOnEntryOnTP1.doRFOnEntry = true; - iRFOnEntryOnTP1.volumeMultiplier = 0.5; - iRFOnEntryOnTP1.actingDistance = requiredDistance; - - // - AddRef( - iRFOnEntryOnTP1, - targets // - ); - } - - // - // Cleanup Resources ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - } - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 3 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &_structure // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - bool isBullish = false; - bool isBearish = false; - - // - XOHCL pBar; - int barIndex = bar.Index(); - int pBarIndex = barIndex + 1; - result = bar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // Do Conditions Checking ... - - // - XBoxZone zones[]; - int zonesCount = 0; - ENUM_X_PRICE bullishPriceType = X_PRICE_LOW; - ENUM_X_PRICE bearishPriceType = X_PRICE_HIGH; - - // - isBullish = fimaHelper.IsSwitchedUnderHKBondLower(bullishPriceType, pBarIndex); - - // - isBearish = fimaHelper.IsSwitchedOverHKBondUpper(bearishPriceType, pBarIndex); - - // - result = - isBullish || - isBearish; - - // - // Do Validations ... - if (result) - { - // - // Direction Assignment ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - int lastIDX; - XBoxZone tmpZones[]; - int tmpZonesCount = 0; - int validationCount = 0; - ENUM_X_PRICE priceType = - isBullish - ? bullishPriceType - : bearishPriceType; - - // - // Detect Last Direction Change ... - if (isBullish) - { - result = fimaHelper.FindLastUnderHKBondLower(lastIDX, bullishPriceType, pBarIndex); - } - else - { - result = fimaHelper.FindLastOverHKBondUpper(lastIDX, bearishPriceType, pBarIndex); - } - - // - // Validate Direction Changed ... - if (result) - { - // - validationCount = lastIDX - pBarIndex; - result = validationCount >= 10; - } - - // - // Collect Zones ... - if (result) - { - // - // Support and Resistances ... - tmpZonesCount = poiDetector.CollectZones( - pBar, - tmpZones, - 5, - 14, // Zones Validation Length ... - 0, // Required Count ... - validationCount // Loopback ... - ); - if (IsValidSize(tmpZonesCount)) - { - // - Copy( - tmpZones, - zones, - false // ignore Clean ... - ); - } - - // - // OB ... - tmpZonesCount = poiDetector.CollectOBs( - pBar, - tmpZones, - 5, // Zones Loopback ... - 0, // Required Count ... - validationCount // Loopback ... - ); - if (IsValidSize(tmpZonesCount)) - { - // - Copy( - tmpZones, - zones, - false // ignore Clean ... - ); - } - - // - // FVG ... - tmpZonesCount = poiDetector.CollectFVGs( - pBar, - tmpZones, - 5, // Zones Loopback ... - 0, // Required Count ... - validationCount // Loopback ... - ); - if (IsValidSize(tmpZonesCount)) - { - // - Copy( - tmpZones, - zones, - false // ignore Clean ... - ); - } - - // - // Filter Zones Based on pBar ... - zonesCount = poiDetector.FilterZones( - pBar, - zones, - dir, - priceType, - dir // - ); - - // - // Extract Affected Zones ... - XClean(tmpZones); - tmpZonesCount = ExtractAffectedZones( - pBar, - zones, - tmpZones, - dir // - ); - Copy(tmpZones, zones); - zonesCount = ArraySize(zones); - - // - // Update Zones Time ... - UpdateToTime(zones); - } - - // - // Draw Zones ... - result = IsValidSize(zonesCount); - if (result) - { - // - for (int i = 0; i < zonesCount; i++) - { - poiDrawer.DrawZone(zones[i], structureDrawConfig.drawConfig); - } - } - - // - XClean(tmpZones); - } - - // - // Prepare Zone ... - if (result) - { - // - // Zone Detection ... - zone.Clean(); - if (isBullish) - { - // - int idx = GetLowest(zones); - if (IsValidIndex(idx)) - { - zone = zones[idx]; - } - } - else - { - // - int idx = GetHighest(zones); - if (IsValidIndex(idx)) - { - zone = zones[idx]; - } - } - - // zone.dir = dir; - // zone.type = name; - // zone.to = bar.time; - // zone.at = pBar.time; - // zone.from = pBar.time; - // zone.symbol = bar.symbol; - // zone.period = bar.period; - // zone.lower = MathMin(pBar.low, bar.low); - // zone.upper = MathMax(pBar.high, bar.high); - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - // Target Handling ... - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - XClean(zones); - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 4 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param zone: XBoxZone, reference to holds affected zone ... - * @param targets: XTarget, reference to detected Signal's Targets collections ... - * @param dir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy4HasSignal( - XOHCL &bar, - XBoxZone &zone, - XTarget &targets[], - ENUM_X_DIRECTION &dir, - XFIMAConditions &conditions, - XFIMAMarketStructure &_structure // - ) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - bool isBullish = false; - bool isBearish = false; - - // - XOHCL pBar; - int barIndex = bar.Index(); - int pBarIndex = barIndex + 1; - result = bar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // Do Conditions Checking ... - - // - // Reading HK Bond ... - double hkBondUpper = fimaHelper.GetHKBondUpper(pBarIndex); - double hkBondLower = fimaHelper.GetHKBondLower(pBarIndex); - bool hasHKBoundary = - NotEmptyZero(hkBondUpper) && - NotEmptyZero(hkBondLower); - - // - // Pullback Detection ... - bool isPullback = poiDetector.IsPullbackPattern( - pBar, - zone, - dir, - 2, - false // - ); - - // - isBullish = - isPullback && - hasHKBoundary && - IsXBullish(dir) && - zone.lower > hkBondLower; - - // - isBearish = - isPullback && - hasHKBoundary && - IsXBearish(dir) && - zone.upper < hkBondUpper; - - // - result = - isBullish || - isBearish; - - // - // Do Validations ... - if (result) - { - // - // Direction Assignment ... - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // TEMP ... - poiDrawer.DrawZone( - zone, - structureDrawConfig.drawConfig // - ); - } - - // - // Prepare Decision Zone ... - if (result) - { - // - // Zone Detection ... - zone.Clean(); - - // - // zone.dir = dir; - // zone.type = name; - // zone.to = bar.time; - // zone.at = pBar.time; - // zone.from = pBar.time; - // zone.symbol = bar.symbol; - // zone.period = bar.period; - // zone.lower = MathMin(pBar.low, bar.low); - // zone.upper = MathMax(pBar.high, bar.high); - - // - result = zone.IsValid(); - } - - // - // Prepare Targets ... - if (result) - { - // - // Target Handling ... - } - - // - // Cleanup ... - if (!result) - { - // - zone.Clean(); - XClean(targets); - dir = X_DIRECTION_NONE; - } - pBar.Clean(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.signaller.class copy.mq5 b/Documents/BKP/x-saherelm.xfima.signaller.class copy.mq5 deleted file mode 100644 index 89475e93..00000000 --- a/Documents/BKP/x-saherelm.xfima.signaller.class copy.mq5 +++ /dev/null @@ -1,1697 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Protected Actions ... - - /** - * Check Specified Bar has Pattern or not ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param name: string, reference to holds Detected Patterns Name ... - * @param dir: ENUM_X_DIRECTION, reference to holds Detected Patterns Direction ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool HasPattern( - XOHCL &bar, - string &patternName, - ENUM_X_DIRECTION &patternDir, - XFIMAMarketStructure &structure // - ) - { - // - bool result = false; - - // - // Prepare ... - patternName = NULL; - patternDir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(structure.pinnedDir); - bool hasEngulfedBar = HasDirection(structure.engulfedDir); - bool hasFlagPattern = HasDirection(structure.flagPatternDir); - bool hasStarPattern = HasDirection(structure.starPatternDir); - bool hasRisingPattern = HasDirection(structure.risingPatternDir); - bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - - // - // Check Bar Pattern Exists ... - // and Select Pattern Direction and Price and Price Type ... - result = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - - // - if (result) - { - // - if (hasPinnedBar) - { - // - patternDir = structure.pinnedDir; - patternName = "XPinned_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - patternDir = structure.engulfedDir; - patternName = "XEngulfed_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - patternDir = structure.flagPatternDir; - patternName = "XFlag_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - patternDir = structure.starPatternDir; - patternName = "XStar_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - patternDir = structure.risingPatternDir; - patternName = "XRising_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - patternDir = structure.piercingPatternDir; - patternName = "XPiercing_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - patternDir = structure.signalKeyBarPatternDir; - patternName = "XSignalKey_" + ToXString(patternDir) + ToXString(TimeToSeconds(bar.time)); - } - } - - // - result = - result && - IsXValid(patternName) && - HasDirection(patternDir); - - // - return result; - } - - /** - * Validate a Pattern based on MA Band ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param patternName: string, detected pattern's name ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ - bool ValidatePatternBasedOnMABand( - XOHCL &bar, - string patternName, - ENUM_X_DIRECTION patternDir, - XFIMAConditions &fimaConditions // - ) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - IsXValid(patternName) && - HasDirection(patternDir); - if (!result) - { - return result; - } - - // - // Define Requirements ... - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - double iPriceEdge = EMPTY_VALUE; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_PRICE iPriceEdgeType = X_PRICE_NONE; - - // - // Calculating Price and Price Types ... - - // - isBullish = IsXBullish(patternDir); - isBearish = IsXBearish(patternDir); - - // - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - - // - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate ... - result = - NotEmptyZero(iPrice) && - IsXValid(iPriceType) && - NotEmptyZero(iPriceEdge) && - IsXValid(iPriceEdgeType) && - ((isBullish && !isBearish) || - (isBearish && !isBullish)); - if (!result) - { - return result; - } - - // - // Validate Pattern based on MA Band ... - - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fimaConditions.maBandUpperBuffer[0]; - double iMABandLower = fimaConditions.maBandLowerBuffer[0]; - - // - // Validate by Edge Price ... - result = - NotEmptyZero(iMABandUpper) && - NotEmptyZero(iMABandLower) && - (isBullish - ? iPriceEdge < iMABandLower - : iPriceEdge > iMABandUpper); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 1 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - int fvgLookupLenght; // Maximum Lenght for Looking up FVG before Crosses - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - fvgLookupLenght = 5; - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL bar; - XSignal signal; - bool has = false; - int cIdx = barIndex + 1; - int pIdx = cIdx + 1; - ENUM_X_DIRECTION signalDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = bar.Init( - symbol, - period, - cIdx // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // Retrieve Conditions ... - XFIMAConditions fimaConditions; - has = fimaHelper.GetConditions( - fimaConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - bar.Clean(); - fimaConditions.Clean(); - - // - return; - } - - // - // Analyse Conditions for Finding Signal ... - - // - // TODO: Remove this ... - - // - bool isFastCrossedOverSlow = - fimaConditions.maFastBuffer[cIdx] > fimaConditions.maSlowBuffer[cIdx] && - fimaConditions.maFastBuffer[pIdx] < fimaConditions.maSlowBuffer[pIdx]; - - // - bool isFastCrossedUnderSlow = - fimaConditions.maFastBuffer[cIdx] < fimaConditions.maSlowBuffer[cIdx] && - fimaConditions.maFastBuffer[pIdx] > fimaConditions.maSlowBuffer[pIdx]; - - // - has = - isFastCrossedOverSlow || - isFastCrossedUnderSlow; - if (has) - { - // - // Do Conditions Validating ... - // TODO: Igmore All Validations for Testing Purposes ... - - // - // Validate MA Positions ... - double iFastMa = fimaConditions.maFastBuffer[cIdx]; - double iSlowMa = fimaConditions.maSlowBuffer[cIdx]; - double iFiboUpper = fimaConditions.fiboUpperBuffer[cIdx]; - double iFiboLower = fimaConditions.fiboLowerBuffer[cIdx]; - - // - // Checking Has FVG ... - XBoxZone fvg; - ENUM_X_DIRECTION fvgDir; - bool hasFVG = patternDetector.HasFVG( - bar, - fvgDir, - fvg, - fvgLookupLenght // - ); - - // - // Checking Crossed On Shadow ... - - // - bool isCrossedOverHappensOnShadow = - isFastCrossedOverSlow && - iFastMa <= bar.GetDown() && - iFastMa >= bar.low; - - // - bool isCrossedUnderHappensOnShadow = - isFastCrossedUnderSlow && - iFastMa <= bar.high && - iFastMa >= bar.GetUp(); - - // - // Bullish Validation ... - bool isBullish = - // - // Has Cross ... - isFastCrossedOverSlow - // - // && - // // - // // Cross Places Based on Fibo ... - // MathMax(iFastMa, iSlowMa) < iFiboLower - // // - // && - // // - // ( - // // - // // Checking FVG ... - // (hasFVG && - // fvg.IsBullish()) - // // - // || - // // - // // Checking Crossed Place ... - // isCrossedOverHappensOnShadow - // // - // ) - // // - ; - - // - // Bearish Validation ... - bool isBearish = - // - // Has Cross ... - isFastCrossedUnderSlow - // - // && - // // - // // Cross Places Based on Fibo ... - // MathMin(iFastMa, iSlowMa) > iFiboUpper - // // - // && - // // - // ( - // // - // // Checking FVG ... - // (hasFVG && - // fvg.IsBearish()) - // // - // || - // // - // // Checking Crossed Place ... - // isCrossedUnderHappensOnShadow - // // - // ) - // // - ; - - // - has = - (isBullish && !isBearish) || - (isBearish && !isBullish); - if (has) - { - // - signalDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - } - - // - // Check Signal Founded ... - has = HasDirection(signalDir); - if (has) - { - // - // Prepare Founded Signal ... - XTarget targets[]; - has = PrepareSignal( - signal, - signalDir, - targets // - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(signal); - } - } - - // - // Cleanup Resources ... - bar.Clean(); - signal.Clean(); - fimaConditions.Clean(); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Lookup FVG ... - bool LookupFVG( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XBoxZone &fvgBox // - ) - { - // - bool result = false; - - // - return result; - } - - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy2Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - XFIMAPatternDetectorConfig analyserConfig; - - // - // Constructor ... - XCXFIMAStrategy2Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA2", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure Detector ... - // - analyserConfig.Default(); - analyserConfig.validMACrossDiffMultiplier = 4; - - // - analyserConfig.FullDetect(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy2Signaller() - { - // - Destroy(); - - // - analyserConfig.Clean(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - XOHCL iBar; - int count = 0; - XBoxZone iZone; - XSignal iSignal; - bool has = false; - XTarget targets[]; - string iName = NULL; - XBoxZone supports[]; - XBoxZone resistances[]; - bool isBullish = false; - bool isBearish = false; - int numberOfPivots = 25; - XFIMAConditions iFIMAConditions; - XFIMAMarketStructure iStructure; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - XPivot pvPivots[]; - string pvTrendName = "XXIFMA2PVTrend"; - CChartObjectTrend *pvTrendLine = NULL; - ENUM_X_DIRECTION pvTrend = X_DIRECTION_NONE; - - // - XPivot zgPivots[]; - string zgTrendName = "XFIMA2ZGTrend"; - CChartObjectTrend *zgTrendLine = NULL; - ENUM_X_DIRECTION zgTrend = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - iBar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - iFIMAConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - iBar.Clean(); - iFIMAConditions.Clean(); - - // - return; - } - - // - // Analyse Market ... - poiDetector.AnalyseMarket( - iBar, - iStructure, - analyserConfig // - ); - - // - // Collect Support and Resistance Zones and Validate by them ... - - // - // PV Trend Line ... - bool hasPVAnalysis = iStructure.pvAnalysis.IsValid(); - if (hasPVAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = iStructure.pvAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = iBar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = iStructure.pvAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = iBar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractPVPivots( - pivots, - barIndex, - numberOfPivots // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - pvTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(pvTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(pvTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - pvTrendLine, - pvTrendName, - true // Ray Right ... - ); - if (has) - { - pvTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - pvPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // ZigZag Trend Line ... - bool hasZGAnalysis = iStructure.zigzagAnalysis.IsValid(); - if (hasZGAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = iStructure.zigzagAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = iBar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = iStructure.zigzagAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = iBar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractZigZagPivots( - pivots, - barIndex, - numberOfPivots // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - zgTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(zgTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(zgTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - zgTrendLine, - zgTrendName, - true // Ray Right ... - ); - if (has) - { - zgTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - zgPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Support ... - bool hasSupport = iStructure.support.IsValid(); - if (hasSupport) - { - // - iStructure.support.to = iBar.time; - AddIfNotExists( - iStructure.support, - supports // - ); - } - - // - // Resistance ... - bool hasResistance = iStructure.resistance.IsValid(); - if (hasResistance) - { - // - iStructure.resistance.to = iBar.time; - AddIfNotExists( - iStructure.resistance, - resistances // - ); - } - - // - // Disable Signallers ... - has = false; - - // - // Strategy 1 ... - // Works on Support or Resistances Areas ... - // has = Strategy1HasSignal( - // iBar, - // iZone, - // supports, - // resistances, - // iDir, - // iStructure, - // iFIMAConditions // - // ); - - // - // Strategy 2 ... - // Works on MA Crosses ... - has = Strategy2HasSignal( - iBar, - iZone, - supports, - resistances, - iDir, - iStructure, - iFIMAConditions // - ); - - // - has = HasDirection(iDir); - if (has) - { - // - isBullish = IsXBullish(iDir); - isBearish = IsXBearish(iDir); - - // - // TODO: Provided SL ... - double _point = GetPoints(iBar.symbol); - double slAddition = 5 * _point; - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - has = PrepareSignal( - iSignal, - iDir, - targets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(iSignal); - } - } - - // - // Cleanup Resources ... - iBar.Clean(); - iZone.Clean(); - iSignal.Clean(); - iStructure.Clean(); - iFIMAConditions.Clean(); - SpecifiedClean(targets); - SpecifiedClean(pvPivots); - SpecifiedClean(zgPivots); - SpecifiedClean(supports); - SpecifiedClean(resistances); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Implementing Strategies ... - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param iDir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &iZone, - XBoxZone &supports[], - XBoxZone &resistances[], - ENUM_X_DIRECTION &iDir, - XFIMAMarketStructure &structure, - XFIMAConditions &conditions // - ) - { - // - bool result = false; - - // - // Prepare ... - iZone.Clean(); - iDir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Check Pattern Exists ... - string patternName = NULL; - ENUM_X_DIRECTION patternDir = X_DIRECTION_NONE; - result = HasPattern( - bar, - patternName, - patternDir, - structure // - ); - if (!result) - { - return result; - } - - // - // Validate Pattern Based on MA Band ... - result = ValidatePatternBasedOnMABand( - bar, - patternName, - patternDir, - conditions // - ); - if (!result) - { - return result; - } - - // - // Check Affected Zone ... - // Select a Support or Resistance ... - int insideZoneIDX = -1; - result = - (IsXBullish(patternDir) - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : IsXBearish(patternDir) - ? HasInside( - insideZoneIDX, - bar, - resistances // - ) - : false // - ); - if (!result) - { - return result; - } - - // - // Filling Affected Zone ... - // and Validate it ... - if (IsXBullish(patternDir)) - { - iZone = supports[insideZoneIDX]; - } - else if (IsXBearish(patternDir)) - { - iZone = resistances[insideZoneIDX]; - } - result = iZone.IsValid(); - if (!result) - { - return result; - } - - // - // Validate affected Zone based on Pattern's Bar ... - result = IsXBullish(patternDir) - ? bar.high > iZone.upper - : IsXBearish(patternDir) - ? bar.low < iZone.lower - : false; - if (result) - { - iDir = patternDir; - } - - // - // Cleanup Resources ... - if (!result) - { - iZone.Clean(); - } - - // - return result; - } - - /** - * Check Bar Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param iDir: ENUM_X_DIRECTION, detected Signal's direction ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * @param conditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &iZone, - XBoxZone &supports[], - XBoxZone &resistances[], - ENUM_X_DIRECTION &iDir, - XFIMAMarketStructure &structure, - XFIMAConditions &conditions // - ) - { - // - bool result = false; - - // - // Prepare ... - iZone.Clean(); - iDir = X_DIRECTION_NONE; - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Detect Specified MA Cross ... - result = HasDirection(structure.maCrossDir); - - // - // Validate Conditions ... - - // - // Prepare iZone ... - iZone.to = bar.time; - iZone.from = GetBarTime( - bar.symbol, - bar.period, - bar.Index() + 2 // - ); - iZone.symbol = bar.symbol; - iZone.period = bar.period; - iZone.dir = structure.maCrossDir; - iZone.lower = bar.FindLowest(2, MODE_LOW); - iZone.upper = bar.FindHighest(2, MODE_HIGH); - iZone.type = name + "_" + ToXString(structure.maCrossDir); - - // - // Check Result ... - result = iZone.IsValid(); - if (result) - { - iDir = structure.maCrossDir; - } - - // - // Cleanup Resources ... - if (!result) - { - iZone.Clean(); - } - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.signaller.class.mq5 b/Documents/BKP/x-saherelm.xfima.signaller.class.mq5 deleted file mode 100644 index bffdfd93..00000000 --- a/Documents/BKP/x-saherelm.xfima.signaller.class.mq5 +++ /dev/null @@ -1,3804 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMASignaller ... -// Description: XFIMA Signaller Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA Signaller Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-signaller.class.mq5" -#include "../../Helpers/x-saherelm.xfima.helper.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.detector.class.mq5" -#include "../Classes/x-saherelm.xfima.x-poi.drawer.class.mq5" - -// -// Implementation ... - -// -// Base XFIMA base Signaller ... -class XCXFIMABaseSignaller : public XCBaseSignaller -{ - // - // Public ... - public: - // - // Props ... - - // - XFIMAInputs fimaInputs; // XFIMA Inputs ... - XCXFIMAHelper *fimaHelper; // XFIMA Indicator Helper ... - XCXFIMAPOIDrawer *poiDrawer; // XFIMA POI Drawer ... - XCXFIMAPOIDetector *poiDetector; // XFIMA POI Detector ... - - // - // Constructor ... - XCXFIMABaseSignaller( - string _name, // Name ... - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCBaseSignaller(_name, - _symbol, - _period, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Instantiating XFIMA Indicator Helper Class ... - if (_fimaInputs.IsValid()) - { - // - fimaHelper = new XCXFIMAHelper(); - bool isInited = fimaHelper.Init( - _symbol, - _period, - _fimaInputs // - ); - if (isInited) - { - fimaInputs = _fimaInputs; - } - else - { - // - delete fimaHelper; - ZeroMemory(fimaHelper); - } - } - - // - poiDrawer = new XCXFIMAPOIDrawer(); - poiDetector = new XCXFIMAPOIDetector(fimaHelper); - } - - // - // Deconstructor ... - ~XCXFIMABaseSignaller() - { - Destroy(); - } - - // - // Overrides ... - - // - // Actions ... - - /** - * Destroy ... - */ - void Destroy() - { - // - BeforeDestroy(); - - // - fimaInputs.Clean(); - - // - delete fimaHelper; - ZeroMemory(fimaHelper); - - // - delete poiDrawer; - ZeroMemory(poiDrawer); - - // - delete poiDetector; - ZeroMemory(poiDetector); - } - - // - // Virtuals ... - - /** - * Before Destroy ... - */ - void virtual BeforeDestroy() - { - } - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - /** - * Check Additional Validations on Childs Instances ... - * - * @return ( bool virtual ) - */ - bool virtual CheckAdditionslSignallerValidations() - { - // - bool result = false; - - // - // Validate Fima Helper Requirements ... - result = fimaInputs.IsValid() && - fimaHelper != NULL && - poiDetector != NULL; - - // - return result; - } - - /** - * Normalizing Signal by Signaller Custom Props ... - * - * @param signal: XSignal ... - */ - void virtual NormalizeSignal(XSignal &signal) - { - } - - // - // Protected ... - protected: - // - - // - // Private ... - private: - // -}; - -// -// XFIMA Strategy 1 Signaller Class ... -class XCXFIMAStrategy1Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - int fvgLookupLenght; // Maximum Lenght for Looking up FVG before Crosses - - // - // Constructor ... - XCXFIMAStrategy1Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA1", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - fvgLookupLenght = 5; - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Update Helper ... - fimaHelper.Update(barIndex); - - // - XOHCL bar; - XSignal signal; - bool has = false; - int cIdx = barIndex + 1; - int pIdx = cIdx + 1; - ENUM_X_DIRECTION signalDir = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = bar.Init( - symbol, - period, - cIdx // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // Retrieve Conditions ... - XFIMAConditions fimaConditions; - has = fimaHelper.GetConditions( - fimaConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - bar.Clean(); - fimaConditions.Clean(); - - // - return; - } - - // - // Analyse Conditions for Finding Signal ... - - // - // TODO: Remove this ... - - // - bool isFastCrossedOverSlow = - fimaConditions.maFastBuffer[cIdx] > fimaConditions.maSlowBuffer[cIdx] && - fimaConditions.maFastBuffer[pIdx] < fimaConditions.maSlowBuffer[pIdx]; - - // - bool isFastCrossedUnderSlow = - fimaConditions.maFastBuffer[cIdx] < fimaConditions.maSlowBuffer[cIdx] && - fimaConditions.maFastBuffer[pIdx] > fimaConditions.maSlowBuffer[pIdx]; - - // - has = - isFastCrossedOverSlow || - isFastCrossedUnderSlow; - if (has) - { - // - // Do Conditions Validating ... - // TODO: Igmore All Validations for Testing Purposes ... - - // - // Validate MA Positions ... - double iFastMa = fimaConditions.maFastBuffer[cIdx]; - double iSlowMa = fimaConditions.maSlowBuffer[cIdx]; - double iFiboUpper = fimaConditions.fiboUpperBuffer[cIdx]; - double iFiboLower = fimaConditions.fiboLowerBuffer[cIdx]; - - // - // Checking Has FVG ... - XBoxZone fvg; - ENUM_X_DIRECTION fvgDir; - bool hasFVG = patternDetector.HasFVG( - bar, - fvgDir, - fvg, - fvgLookupLenght // - ); - - // - // Checking Crossed On Shadow ... - - // - bool isCrossedOverHappensOnShadow = - isFastCrossedOverSlow && - iFastMa <= bar.GetDown() && - iFastMa >= bar.low; - - // - bool isCrossedUnderHappensOnShadow = - isFastCrossedUnderSlow && - iFastMa <= bar.high && - iFastMa >= bar.GetUp(); - - // - // Bullish Validation ... - bool isBullish = - // - // Has Cross ... - isFastCrossedOverSlow - // - // && - // // - // // Cross Places Based on Fibo ... - // MathMax(iFastMa, iSlowMa) < iFiboLower - // // - // && - // // - // ( - // // - // // Checking FVG ... - // (hasFVG && - // fvg.IsBullish()) - // // - // || - // // - // // Checking Crossed Place ... - // isCrossedOverHappensOnShadow - // // - // ) - // // - ; - - // - // Bearish Validation ... - bool isBearish = - // - // Has Cross ... - isFastCrossedUnderSlow - // - // && - // // - // // Cross Places Based on Fibo ... - // MathMin(iFastMa, iSlowMa) > iFiboUpper - // // - // && - // // - // ( - // // - // // Checking FVG ... - // (hasFVG && - // fvg.IsBearish()) - // // - // || - // // - // // Checking Crossed Place ... - // isCrossedUnderHappensOnShadow - // // - // ) - // // - ; - - // - has = - (isBullish && !isBearish) || - (isBearish && !isBullish); - if (has) - { - // - signalDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - } - - // - // Check Signal Founded ... - has = HasDirection(signalDir); - if (has) - { - // - // Prepare Founded Signal ... - XTarget targets[]; - has = PrepareSignal( - signal, - signalDir, - targets // - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(signal); - } - } - - // - // Cleanup Resources ... - bar.Clean(); - signal.Clean(); - fimaConditions.Clean(); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Lookup FVG ... - bool LookupFVG( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - XBoxZone &fvgBox // - ) - { - // - bool result = false; - - // - return result; - } - - // -}; - -// -// XFIMA Strategy 2 Signaller Class ... -class XCXFIMAStrategy2Signaller : public XCXFIMABaseSignaller -{ - // - // Public ... - public: - // - // Props ... - XFIMAPatternDetectorConfig analyserConfig; - - // - // Constructor ... - XCXFIMAStrategy2Signaller( - string _symbol, // Symbol ... - ENUM_TIMEFRAMES _period, // Period ... - XFIMAInputs &_fimaInputs, // XFIMAInputs ... - bool _processAllTicks = false, // Process All Ticks ... - double _defaultSignalR2R = 1.5, // Default Signal Risk To Reward Ratio ... - double _defaultSignalRiskInPoint = 50, // Default Signal Risk In Point ... - double _defaultSignalVolume = 0.01 // Default Signal Volume ... - ) : XCXFIMABaseSignaller("XFIMA2", - _symbol, - _period, - _fimaInputs, - _processAllTicks, - _defaultSignalR2R, - _defaultSignalRiskInPoint, - _defaultSignalVolume // - ) - { - // - // Configure Detector ... - analyserConfig.Default(); - analyserConfig.FullDetect(); - } - - // - // Deconstructor ... - ~XCXFIMAStrategy2Signaller() - { - // - Destroy(); - - // - analyserConfig.Clean(); - } - - // - // Overrides ... - - /** - * Processing Tick ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessTick(int barIndex = 0) - { - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - void ProcessNewBarNKP(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Update Helper ... - fimaHelper.Update(barIndex); - - // - XOHCL bar; - XSignal signal; - XBoxZone iZone; - int count = 0; - bool has = false; - int cIdx = barIndex + 1; - int pIdx = cIdx + 1; - string iName = NULL; - XBoxZone supports[]; - XBoxZone resistances[]; - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - XFIMAMarketStructure structure; - XFIMAConditions fimaConditions; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - XPivot pvPivots[]; - string pvTrendName = "XXIFMA2PVTrend"; - CChartObjectTrend *pvTrendLine = NULL; - ENUM_X_DIRECTION pvTrend = X_DIRECTION_NONE; - - // - XPivot zgPivots[]; - string zgTrendName = "XFIMA2ZGTrend"; - CChartObjectTrend *zgTrendLine = NULL; - ENUM_X_DIRECTION zgTrend = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = bar.Init( - symbol, - period, - cIdx // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - fimaConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - bar.Clean(); - fimaConditions.Clean(); - - // - return; - } - - // - // Analyse Market ... - poiDetector.AnalyseMarket( - bar, - structure, - analyserConfig // - ); - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(structure.pinnedDir); - bool hasEngulfedBar = HasDirection(structure.engulfedDir); - bool hasFlagPattern = HasDirection(structure.flagPatternDir); - bool hasStarPattern = HasDirection(structure.starPatternDir); - bool hasRisingPattern = HasDirection(structure.risingPatternDir); - bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - - // - // Check Bar Pattern Exists ... - has = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - - // - // Select Pattern Direction and Price and Price Type ... - if (has) - { - // - if (hasPinnedBar) - { - // - iDir = structure.pinnedDir; - iName = "XPinned_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - iDir = structure.engulfedDir; - iName = "XEngulfed_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - iDir = structure.flagPatternDir; - iName = "XFlag_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - iDir = structure.starPatternDir; - iName = "XStar_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - iDir = structure.risingPatternDir; - iName = "XRising_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - iDir = structure.piercingPatternDir; - iName = "XPiercing_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - iDir = structure.signalKeyBarPatternDir; - iName = "XSignalKey_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - - // - isBullish = IsSpecifiedBullish(iDir); - isBearish = IsSpecifiedBearish(iDir); - - // - // Retrieve Price Type for Validate ... - iPriceType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - iPrice = bar.GetPrice(iPriceType); - - // - has = HasDirection(iDir); - } - - // - // Chekc Bullish or Bearish Starter Conditions Exists ... - has = - isBullish || - isBearish; - if (has) - { - // - // Do Conditions Validating ... - - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fimaHelper.GetMABandUpper(barIndex); - double iMABandLower = fimaHelper.GetMABandLower(barIndex); - - // - // Validate ... - has = isBullish - ? iPrice < iMABandLower - : iPrice > iMABandUpper; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - - // - // Collect Support and Resistance Zones and Validate by them ... - - // - // PV Trend Line ... - bool hasPVAnalysis = structure.pvAnalysis.IsValid(); - if (hasPVAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.pvAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - // has = poiDrawer.DrawBox( - // supportBox, - // iSupportObj, - // true, // Ignore At ... - // supportBox.type // Name ... - // ); - // if (has) - // { - // // - // XPOIStyle iStyle; - // poiDrawer.GetBoxStyle( - // iStyle, - // supportBox.dir // - // ); - // poiDrawer.ApplyBoxStyle( - // iSupportObj, - // iStyle // - // ); - // iStyle.Clean(); - // } - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.pvAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - // has = poiDrawer.DrawBox( - // resistanceBox, - // iResistanceObj, - // true, // Ignore At ... - // resistanceBox.type // Name ... - // ); - // if (has) - // { - // // - // XPOIStyle iStyle; - // poiDrawer.GetBoxStyle( - // iStyle, - // resistanceBox.dir // - // ); - // poiDrawer.ApplyBoxStyle( - // iResistanceObj, - // iStyle // - // ); - // iStyle.Clean(); - // } - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractPVPivots( - pivots, - barIndex, - 50 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - pvTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(pvTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(pvTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - pvTrendLine, - pvTrendName, - true // Ray Right ... - ); - if (has) - { - pvTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - pvPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // ZigZag Trend Line ... - bool hasZGAnalysis = structure.zigzagAnalysis.IsValid(); - if (hasZGAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.zigzagAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.zigzagAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractZigZagPivots( - pivots, - barIndex, - 10 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - zgTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(zgTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(zgTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - zgTrendLine, - zgTrendName, - true // Ray Right ... - ); - if (has) - { - zgTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - zgPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Support ... - bool hasSupport = structure.support.IsValid(); - if (hasSupport) - { - // - AddIfNotExists( - structure.support, - supports // - ); - - // // - // XCBoxObject *iObj; - // has = fima2Signaller.poiDrawer.DrawBox( - // structure.support, - // iObj); - // if (has) - // { - // } - } - - // - // Resistance ... - bool hasResistance = structure.resistance.IsValid(); - if (hasResistance) - { - // - AddIfNotExists( - structure.resistance, - resistances // - ); - - // // - // XCBoxObject *iObj; - // has = fima2Signaller.poiDrawer.DrawBox( - // structure.resistance, - // iObj); - // if (has) - // { - // } - } - - // - // Validate Positions Support and Resistance Zone ... - int insideZoneIDX = -1; - has = has && - (isBullish - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : HasInside( - insideZoneIDX, - bar, - resistances // - )); - - // - // Validate Selected Inside Zone ... - // whith Bars Edge ... - has = IsValidIndex(insideZoneIDX); - if (has) - { - // - if (isBullish) - { - iZone = supports[insideZoneIDX]; - } - else - { - iZone = resistances[insideZoneIDX]; - } - - // - has = isBullish - ? bar.high > supports[insideZoneIDX].upper - : bar.low < resistances[insideZoneIDX].lower; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - else - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - - // - // Checking Liquidities ... - - // - // Do all Draws Here ... - bool canDraw = false; - if (canDraw) - { - // - int iWidth = 2; - XPOIStyle iStyle; - XCBoxObject *iBoxObj = NULL; - color iClr = isBullish - ? clrYellow - : clrDarkOrange; - - // - // Supports ... - has = HasChild(supports); - if (has) - { - // - count = ArraySize(supports); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - supports[i], - iBoxObj, - true, // Ignore At ... - supports[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - supports[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Resistances ... - has = HasChild(resistances); - if (has) - { - // - count = ArraySize(resistances); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - resistances[i], - iBoxObj, - true, // Ignore At ... - resistances[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - resistances[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Selected Zone ... - has = iZone.IsValid(); - if (has) - { - // - has = poiDrawer.DrawBox( - iZone, - iBoxObj, - true, // Ignore At ... - iZone.type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - iZone.dir // - ); - - // - iStyle.clr = iClr; - iStyle.width = iWidth; - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - } - - // - // TrendLines ... - - // - // Pivots ... - - // - has = HasChild(pvPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - pvPivots, - drawnPivots // - ); - } - - // - has = HasChild(zgPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - zgPivots, - drawnPivots // - ); - } - - // - // Patterns Bar ... - has = HasDirection(iDir); - if (has) - { - // - int iCode = 159; - ENUM_ARROW_ANCHOR iAnchor = isBullish - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - - // - XCBarArrowObject *iPatternObj; - has = poiDrawer.DrawBarArrow( - bar, - iPatternObj, - iPriceType, - iCode, - iClr, - iWidth, - iAnchor, - iName, - true, // Ignore Bar Tag ... - 10 // Threshold ... - ); - } - } - - // - // Check Signal Founded ... - has = HasDirection(iDir); - if (has) - { - // - // TODO: Provided SL ... - double _point = GetPoints(bar.symbol); - double slAddition = 5 * _point; - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - XTarget targets[]; - has = PrepareSignal( - signal, - iDir, - targets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(signal); - } - } - - // - // Cleanup Resources ... - bar.Clean(); - iZone.Clean(); - signal.Clean(); - structure.Clean(); - fimaConditions.Clean(); - SpecifiedClean(pvPivots); - SpecifiedClean(zgPivots); - SpecifiedClean(supports); - SpecifiedClean(resistances); - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - void ProcessNewBarNKP1(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Update Helper ... - fimaHelper.Update(barIndex); - - // - XOHCL bar; - XSignal signal; - XBoxZone iZone; - int count = 0; - bool has = false; - int cIdx = 0; - int pIdx = cIdx + 1; - string iName = NULL; - XBoxZone supports[]; - XBoxZone resistances[]; - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - double iPriceEdge = EMPTY_VALUE; - XFIMAMarketStructure structure; - XFIMAConditions fimaConditions; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PRICE iPriceEdgeType = X_PRICE_NONE; - - // - XPivot pvPivots[]; - string pvTrendName = "XXIFMA2PVTrend"; - CChartObjectTrend *pvTrendLine = NULL; - ENUM_X_DIRECTION pvTrend = X_DIRECTION_NONE; - - // - XPivot zgPivots[]; - string zgTrendName = "XFIMA2ZGTrend"; - CChartObjectTrend *zgTrendLine = NULL; - ENUM_X_DIRECTION zgTrend = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - fimaConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - bar.Clean(); - fimaConditions.Clean(); - - // - return; - } - - // - // Analyse Market ... - poiDetector.AnalyseMarket( - bar, - structure, - analyserConfig // - ); - - // - // Collect Support and Resistance Zones and Validate by them ... - - // - // PV Trend Line ... - bool hasPVAnalysis = structure.pvAnalysis.IsValid(); - if (hasPVAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.pvAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.pvAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractPVPivots( - pivots, - barIndex, - 50 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - pvTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(pvTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(pvTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - pvTrendLine, - pvTrendName, - true // Ray Right ... - ); - if (has) - { - pvTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - pvPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // ZigZag Trend Line ... - bool hasZGAnalysis = structure.zigzagAnalysis.IsValid(); - if (hasZGAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.zigzagAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.zigzagAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractZigZagPivots( - pivots, - barIndex, - 10 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - zgTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(zgTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(zgTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - zgTrendLine, - zgTrendName, - true // Ray Right ... - ); - if (has) - { - zgTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - zgPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Support ... - bool hasSupport = structure.support.IsValid(); - if (hasSupport) - { - // - AddIfNotExists( - structure.support, - supports // - ); - } - - // - // Resistance ... - bool hasResistance = structure.resistance.IsValid(); - if (hasResistance) - { - // - AddIfNotExists( - structure.resistance, - resistances // - ); - } - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(structure.pinnedDir); - bool hasEngulfedBar = HasDirection(structure.engulfedDir); - bool hasFlagPattern = HasDirection(structure.flagPatternDir); - bool hasStarPattern = HasDirection(structure.starPatternDir); - bool hasRisingPattern = HasDirection(structure.risingPatternDir); - bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - - // - // Check Bar Pattern Exists ... - // and Select Pattern Direction and Price and Price Type ... - has = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - if (has) - { - // - if (hasPinnedBar) - { - // - iDir = structure.pinnedDir; - iName = "XPinned_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - iDir = structure.engulfedDir; - iName = "XEngulfed_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - iDir = structure.flagPatternDir; - iName = "XFlag_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - iDir = structure.starPatternDir; - iName = "XStar_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - iDir = structure.risingPatternDir; - iName = "XRising_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - iDir = structure.piercingPatternDir; - iName = "XPiercing_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - iDir = structure.signalKeyBarPatternDir; - iName = "XSignalKey_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - - // - isBullish = IsSpecifiedBullish(iDir); - isBearish = IsSpecifiedBearish(iDir); - - // - // Retrieve Price Type for Validate ... - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate Calculations ... - has = HasDirection(iDir) && - (isBullish || - isBearish) && - NotEmptyZero(iPrice) && - NotEmptyZero(iPriceEdge) && - iPrice != iPriceEdge; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - - // - // Check Petterns Happens ... - // Chekc Bullish or Bearish Starter Conditions Exists ... - has = HasDirection(iDir); - if (has) - { - // - // Do Conditions Validating ... - - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fimaConditions.maBandUpperBuffer[cIdx]; - double iMABandLower = fimaConditions.maBandLowerBuffer[cIdx]; - - // - // Validate ... - - // - // Validate by Edge Price ... - has = isBullish - ? iPriceEdge < iMABandLower - : iPriceEdge > iMABandUpper; - - // - // Validate by Body Price ... - // has = isBullish - // ? iPrice < iMABandLower - // : iPrice > iMABandUpper; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - - // - // Validate ... - // Detect Support and Resistances ... - // and Validate Price based on it's ... - has = HasDirection(iDir); - if (has) - { - // - // Validate Positions Support and Resistance Zone ... - int insideZoneIDX = -1; - has = has && - (isBullish - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : HasInside( - insideZoneIDX, - bar, - resistances // - )); - - // - // Validate Selected Inside Zone ... - // whith Bars Edge ... - has = IsValidIndex(insideZoneIDX); - if (has) - { - // - if (isBullish) - { - iZone = supports[insideZoneIDX]; - } - else - { - iZone = resistances[insideZoneIDX]; - } - - // - has = isBullish - ? bar.high > supports[insideZoneIDX].upper - : bar.low < resistances[insideZoneIDX].lower; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - else - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - - // - // Checking Liquidities ... - - // - // Do all Draws Here ... - bool canDraw = true; - if (canDraw) - { - // - int iWidth = 2; - XPOIStyle iStyle; - XCBoxObject *iBoxObj = NULL; - color iClr = isBullish - ? clrYellow - : clrDarkOrange; - - // - // Supports ... - has = HasChild(supports); - if (has) - { - // - count = ArraySize(supports); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - supports[i], - iBoxObj, - true, // Ignore At ... - supports[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - supports[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Resistances ... - has = HasChild(resistances); - if (has) - { - // - count = ArraySize(resistances); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - resistances[i], - iBoxObj, - true, // Ignore At ... - resistances[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - resistances[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Selected Zone ... - has = iZone.IsValid(); - if (has) - { - // - has = poiDrawer.DrawBox( - iZone, - iBoxObj, - true, // Ignore At ... - iZone.type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - iZone.dir // - ); - - // - iStyle.clr = iClr; - iStyle.width = iWidth; - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - } - - // - // TrendLines ... - - // - // Pivots ... - - // - has = HasChild(pvPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - pvPivots, - drawnPivots // - ); - } - - // - has = HasChild(zgPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - zgPivots, - drawnPivots // - ); - } - - // - // Patterns Bar ... - has = HasDirection(iDir); - if (has) - { - // - int iCode = 159; - ENUM_ARROW_ANCHOR iAnchor = isBullish - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - - // - XCBarArrowObject *iPatternObj; - has = poiDrawer.DrawBarArrow( - bar, - iPatternObj, - iPriceType, - iCode, - iClr, - iWidth, - iAnchor, - iName, - true, // Ignore Bar Tag ... - 10 // Threshold ... - ); - } - } - - // - // Check Signal Founded ... - has = HasDirection(iDir); - - // - if (has) - { - Print("a Valid ", ToXString(iDir), " Pattern Exists ..."); - } - - // - if (has) - { - // - // TODO: Provided SL ... - double _point = GetPoints(bar.symbol); - double slAddition = 5 * _point; - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - XTarget targets[]; - has = PrepareSignal( - signal, - iDir, - targets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(signal); - } - } - - // - // Cleanup Resources ... - bar.Clean(); - iZone.Clean(); - signal.Clean(); - structure.Clean(); - fimaConditions.Clean(); - SpecifiedClean(pvPivots); - SpecifiedClean(zgPivots); - SpecifiedClean(supports); - SpecifiedClean(resistances); - } - - /** - * Processing New Bar ... - * - * @param barIndex: int, Specified Bar Index ... - */ - virtual void ProcessNewBar(int barIndex = 0) - { - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Update Helper ... - fimaHelper.Update(barIndex); - - // - XOHCL bar; - XSignal signal; - XBoxZone iZone; - int count = 0; - bool has = false; - int cIdx = 0; - int pIdx = cIdx + 1; - string iName = NULL; - XBoxZone supports[]; - XBoxZone resistances[]; - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - double iPriceEdge = EMPTY_VALUE; - XFIMAMarketStructure structure; - XFIMAConditions fimaConditions; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_PRICE iPriceEdgeType = X_PRICE_NONE; - - // - XPivot pvPivots[]; - string pvTrendName = "XXIFMA2PVTrend"; - CChartObjectTrend *pvTrendLine = NULL; - ENUM_X_DIRECTION pvTrend = X_DIRECTION_NONE; - - // - XPivot zgPivots[]; - string zgTrendName = "XFIMA2ZGTrend"; - CChartObjectTrend *zgTrendLine = NULL; - ENUM_X_DIRECTION zgTrend = X_DIRECTION_NONE; - - // - // Initialize Bar as CBar ... - has = bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - bar.Clean(); - return; - } - - // - // Retrieve Conditions ... - has = fimaHelper.GetConditions( - fimaConditions, - barIndex, - 10 // Loopback ... - ); - if (!has) - { - // - bar.Clean(); - fimaConditions.Clean(); - - // - return; - } - - // - // Analyse Market ... - poiDetector.AnalyseMarket( - bar, - structure, - analyserConfig // - ); - - // - // Collect Support and Resistance Zones and Validate by them ... - - // - // PV Trend Line ... - bool hasPVAnalysis = structure.pvAnalysis.IsValid(); - if (hasPVAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.pvAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.pvAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractPVPivots( - pivots, - barIndex, - 50 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - pvTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(pvTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(pvTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - pvTrendLine, - pvTrendName, - true // Ray Right ... - ); - if (has) - { - pvTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - pvPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // ZigZag Trend Line ... - bool hasZGAnalysis = structure.zigzagAnalysis.IsValid(); - if (hasZGAnalysis) - { - // - // Support ... - XBoxZone supportBox; - has = structure.zigzagAnalysis.HasSupportBox(supportBox); - if (has) - { - // - supportBox.to = bar.time; - AddIfNotExists( - supportBox, - supports // - ); - } - - // - // Resistance ... - XBoxZone resistanceBox; - has = structure.zigzagAnalysis.HasResistanceBox(resistanceBox); - if (has) - { - // - resistanceBox.to = bar.time; - AddIfNotExists( - resistanceBox, - supports // - ); - } - - // - // Pivots ... - XPivot pivots[]; - count = poiDetector.ExtractZigZagPivots( - pivots, - barIndex, - 10 // - ); - has = IsValidSize(count); - - // - // Sort ... - Sort( - pivots, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Remove Newest ... - ArrayRemove( - pivots, - 0, - 1 // - ); - - // - // Check Trend ... - if (has) - { - // - XPivot highs[]; - int highsCount = ExtractPivots( - highs, - pivots, - X_PIVOT_TYPE_PEAK // - ); - Sort( - highs, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - XPivot lows[]; - int lowsCount = ExtractPivots( - lows, - pivots, - X_PIVOT_TYPE_VALE // - ); - Sort( - lows, - X_SORT_BY_DATE, - X_DIRECTION_BEARISH // - ); - - // - // Check Highs and Lows ... - has = IsValidSize(lowsCount) && - IsValidSize(highsCount) && - lowsCount >= 2 && - highsCount >= 2; - if (has) - { - // - // Try to Get Market Strucutre ... - - // - bool hasLowerHigh = highs[0].value < highs[1].value; - bool hasLowerLow = lows[0].value < lows[1].value; - - // - bool hasHigherHigh = highs[0].value > highs[1].value; - bool hasHigherLow = lows[0].value > lows[1].value; - - // - zgTrend = - (hasHigherHigh && - hasHigherLow) - ? X_DIRECTION_BULLISH - : (hasLowerHigh && - hasLowerLow) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - has = HasDirection(zgTrend); - if (has) - { - // - // Select Swings for Trend Line ... - XOHCL tmpBar; - int llIDX = -1; - int hhIDX = -1; - datetime toTime = NULL; - datetime fromTime = NULL; - double toPrice = EMPTY_VALUE; - color trendColor = CLR_NONE; - double fromPrice = EMPTY_VALUE; - if (IsSpecifiedBullish(zgTrend)) - { - // - llIDX = GetLowest(lows); - hhIDX = GetHighest(lows); - - // - trendColor = clrAqua; - - // - toTime = lows[hhIDX].time; - toPrice = lows[hhIDX].value; - - // - fromTime = lows[llIDX].time; - fromPrice = lows[llIDX].value; - } - else - { - // - llIDX = GetLowest(highs); - hhIDX = GetHighest(highs); - - // - trendColor = clrMagenta; - - // - toTime = highs[llIDX].time; - toPrice = highs[llIDX].value; - - // - fromTime = highs[hhIDX].time; - fromPrice = highs[hhIDX].value; - } - - // - // Check Requirements for Trend ... - has = - NotEmptyZero(toPrice) && - NotEmptyZero(fromPrice) && - IsSpecifiedValid(toTime) && - IsSpecifiedValid(fromTime); - if (has) - { - // - has = poiDrawer.DrawTrendLine( - fromPrice, - fromTime, - toPrice, - toTime, - zgTrendLine, - zgTrendName, - true // Ray Right ... - ); - if (has) - { - zgTrendLine.Color(trendColor); - } - } - - // - // Cleanup Resources ... - tmpBar.Clean(); - } - - // - if (!has) - { - SpecifiedClean(pivots); - } - } - - // - // Cleanup Resources ... - SpecifiedClean(lows); - SpecifiedClean(highs); - } - - // - // Draw Pivots ... - has = HasChild(pivots); - if (has) - { - // - Copy( - pivots, - zgPivots // - ); - } - - // - // Cleanup Resources ... - SpecifiedClean(pivots); - } - - // - // Support ... - bool hasSupport = structure.support.IsValid(); - if (hasSupport) - { - // - AddIfNotExists( - structure.support, - supports // - ); - } - - // - // Resistance ... - bool hasResistance = structure.resistance.IsValid(); - if (hasResistance) - { - // - AddIfNotExists( - structure.resistance, - resistances // - ); - } - - // - // Check Required Pattern Exists ... - bool hasPinnedBar = HasDirection(structure.pinnedDir); - bool hasEngulfedBar = HasDirection(structure.engulfedDir); - bool hasFlagPattern = HasDirection(structure.flagPatternDir); - bool hasStarPattern = HasDirection(structure.starPatternDir); - bool hasRisingPattern = HasDirection(structure.risingPatternDir); - bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); - bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - - // - // Check Bar Pattern Exists ... - // and Select Pattern Direction and Price and Price Type ... - has = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; - if (has) - { - // - if (hasPinnedBar) - { - // - iDir = structure.pinnedDir; - iName = "XPinned_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - iDir = structure.engulfedDir; - iName = "XEngulfed_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - iDir = structure.flagPatternDir; - iName = "XFlag_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - iDir = structure.starPatternDir; - iName = "XStar_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - iDir = structure.risingPatternDir; - iName = "XRising_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - iDir = structure.piercingPatternDir; - iName = "XPiercing_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - iDir = structure.signalKeyBarPatternDir; - iName = "XSignalKey_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - - // - isBullish = IsSpecifiedBullish(iDir); - isBearish = IsSpecifiedBearish(iDir); - - // - // Retrieve Price Type for Validate ... - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate Calculations ... - has = HasDirection(iDir) && - (isBullish || - isBearish) && - NotEmptyZero(iPrice) && - NotEmptyZero(iPriceEdge) && - iPrice != iPriceEdge; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } - } - - // - // Strategy 1 ... - has = Strategy1HasSignal( - bar, - iZone, - iName, - supports, - resistances, - iDir, - fimaConditions, - structure // - ); - - // - // Do all Draws Here ... - bool canDraw = true; - if (canDraw && has) - { - // - int iWidth = 2; - XPOIStyle iStyle; - XCBoxObject *iBoxObj = NULL; - color iClr = isBullish - ? clrYellow - : clrDarkOrange; - - // - // Supports ... - has = HasChild(supports); - if (has) - { - // - count = ArraySize(supports); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - supports[i], - iBoxObj, - true, // Ignore At ... - supports[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - supports[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Resistances ... - has = HasChild(resistances); - if (has) - { - // - count = ArraySize(resistances); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - resistances[i], - iBoxObj, - true, // Ignore At ... - resistances[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - resistances[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Selected Zone ... - has = iZone.IsValid(); - if (has) - { - // - has = poiDrawer.DrawBox( - iZone, - iBoxObj, - true, // Ignore At ... - iZone.type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - iZone.dir // - ); - - // - iStyle.clr = iClr; - iStyle.width = iWidth; - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - } - - // - // TrendLines ... - - // - // Pivots ... - - // - has = HasChild(pvPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - pvPivots, - drawnPivots // - ); - } - - // - has = HasChild(zgPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - zgPivots, - drawnPivots // - ); - } - - // - // Patterns Bar ... - has = HasDirection(iDir); - if (has) - { - // - int iCode = 159; - ENUM_ARROW_ANCHOR iAnchor = isBullish - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - - // - XCBarArrowObject *iPatternObj; - has = poiDrawer.DrawBarArrow( - bar, - iPatternObj, - iPriceType, - iCode, - iClr, - iWidth, - iAnchor, - iName, - true, // Ignore Bar Tag ... - 10 // Threshold ... - ); - } - } - - // - if (has) - { - Print("a Valid ", ToXString(iDir), " Pattern Exists ..."); - } - - // - if (has) - { - // - // TODO: Provided SL ... - double _point = GetPoints(bar.symbol); - double slAddition = 5 * _point; - double slPrice = - isBullish - ? iZone.lower - slAddition - : iZone.upper + slAddition; - - // - // Prepare Founded Signal ... - XTarget targets[]; - has = PrepareSignal( - signal, - iDir, - targets, - 0, // Use Default R2R ... - slPrice, // Provided Price for SL ... - 0 // Specified Risk in Point .... - ); - if (has) - { - // - // Notify On Signal Event ... - NotifySignalEventListeners(signal); - } - } - - // - // Cleanup Resources ... - bar.Clean(); - iZone.Clean(); - signal.Clean(); - structure.Clean(); - fimaConditions.Clean(); - SpecifiedClean(pvPivots); - SpecifiedClean(zgPivots); - SpecifiedClean(supports); - SpecifiedClean(resistances); - } - - /** - * Check Guards Based on MarketConditions ... - * - * @param guards: XGuard[] - * @param barIndex: int - * - * @return ( int ) - */ - int virtual CheckForGuard( - XGuard &guards[], - int barIndex = 0 // - ) - { - // - int result = 0; - - // - SpecifiedClean(guards); - - // - result = ArraySize(guards); - - // - return result; - } - - // - // Private ... - private: - // - // Props ... - - // - // Implementing Strategies ... - - /** - * Validate a Pattern based on MA Band ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param patternName: string, detected pattern's name ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ - bool ValidatePatternBasedOnMABand( - XOHCL &bar, - string patternName, - ENUM_X_DIRECTION patternDir, - XFIMAConditions &fimaConditions // - ) - { - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - IsXValid(patternName) && - HasDirection(patternDir) && - fimaConditions.IsValid(); - if (!result) - { - return result; - } - - // - // Define Requirements ... - bool isBullish = false; - bool isBearish = false; - double iPrice = EMPTY_VALUE; - double iPriceEdge = EMPTY_VALUE; - ENUM_X_PRICE iPriceType = X_PRICE_NONE; - ENUM_X_PRICE iPriceEdgeType = X_PRICE_NONE; - - // - // Calculating Price and Price Types ... - - // - isBullish = IsXBullish(patternDir); - isBearish = IsXBearish(patternDir); - - // - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - - // - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate ... - result = - NotEmptyZero(iPrice) && - IsXValid(iPriceType) && - NotEmptyZero(iPriceEdge) && - IsXValid(iPriceEdgeType) && - ((isBullish && !isBearish) || - (isBearish && !isBullish)); - if (!result) - { - return result; - } - - // - // Validate Pattern based on MA Band ... - - // - // Retrieve MA Band for Validation ... - double iMABandUpper = fimaConditions.maBandUpperBuffer[cIdx]; - double iMABandLower = fimaConditions.maBandLowerBuffer[cIdx]; - - // - // Validate by Edge Price ... - result = isBullish - ? iPriceEdge < iMABandLower - : iPriceEdge > iMABandUpper; - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Check Pattern Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param patternName: string, detected pattern's name ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param fimaMarketStructure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy1HasSignal( - XOHCL &bar, - XBoxZone &iZone, - string patternName, - XBoxZone &supports[], - XBoxZone &resistances[], - ENUM_X_DIRECTION patternDir, - XFIMAMarketStructure &structure, - XFIMAConditions &fimaConditions, - XFIMAMarketStructure &fimaMarketStructure // - ) - { - // - bool result = false; - - // - // Prepare ... - iZone.Clean(); - - // - // Validate ... - result = bar.IsValid() && - IsXValid(patternName) && - HasDirection(patternDir) && - fimaConditions.IsValid(); - if (!result) - { - return result; - } - - // - // Validate Pattern Based on MA Band ... - result = ValidatePatternBasedOnMABand( - bar, - patternName, - patternDir, - fimaConditions // - ); - if (!result) - { - return result; - } - - // - // Check Affected Zone ... - // Select a Support or Resistance ... - int insideZoneIDX = -1; - result = - (isBullish - ? HasInside( - insideZoneIDX, - bar, - supports // - ) - : HasInside( - insideZoneIDX, - bar, - resistances // - )); - if (!result) - { - return result; - } - - // - // Filling Affected Zone ... - // and Validate it ... - if (IsXBullish(patternDir)) - { - iZone = supports[insideZoneIDX]; - } - else if (IsXBearish(patternDir)) - { - iZone = resistances[insideZoneIDX]; - } - result = iZOne.IsValid(); - if (!result) - { - return result; - } - - // - // Validate affected Zone based on Pattern's Bar ... - result = IsXBullish(patternDir) - ? bar.high > iZZone.upper - : IsXBearish(patternDir) - ? bar.low < iZone.lower - : false; - // - // Cleanup Resources ... - if (!result) - { - iZone.Clean(); - } - - // - return result; - } - - /** - * Check Pattern Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param patternName: string, detected pattern's name ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param fimaMarketStructure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ - bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &iZone, - string patternName, - XBoxZone &supports[], - XBoxZone &resistances[], - ENUM_X_DIRECTION patternDir, - XFIMAMarketStructure &structure, - XFIMAConditions &fimaConditions, - XFIMAMarketStructure &fimaMarketStructure // - ) - { - // - bool result = false; - - // - // Prepare ... - - // - // Validate ... - - // - // Do Detection ... - - // - // Validate result ... - - // - // Cleanup Resources ... - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.x-poi.detector.class.mq5 b/Documents/BKP/x-saherelm.xfima.x-poi.detector.class.mq5 deleted file mode 100644 index ac1fcbd5..00000000 --- a/Documents/BKP/x-saherelm.xfima.x-poi.detector.class.mq5 +++ /dev/null @@ -1,495 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMAPoiDetector ... -// Description: XFIMA POI Detector Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA POI Detector Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.base.class.mq5" -#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../../Classes/x-saherelm.x-market.pattern.class.mq5" -#include "../Libraries/x-saherelm.xfima.lib.mq5" - -// -// Implementation ... -class XCXFIMAPOIDetector : public XCMarketPatternDetector -{ - // - // Public ... - public: - // - // Props ... - XCBarAnalyser *barAnalyser; // Bar Analyser ... - XCXFIMAHelper *fimaHelper; // XFIMA Helper ... - - // - // Constructor ... - XCXFIMAPOIDetector( - XCXFIMAHelper *_fimaHelper // - ) : XCMarketPatternDetector() - { - // - barAnalyser = new XCBarAnalyser(); - fimaHelper = _fimaHelper; - } - - // - // Deconstructor ... - ~XCXFIMAPOIDetector() - { - Destroy(); - } - - // - // Actions and Tools ... - - // - // Pivot Analysors ... - - /** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( bool ) - */ - bool AnalysePVPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractPVPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength, // Max Allowed Loopback ... - validationLength // Validation Length ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XPV", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; - } - - /** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * @param validationLength: int, Specified Pivots Validation Length ignore if <= 0 ... - * - * @return ( bool ) - */ - bool AnalyseMAPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500, - int validationLength = 0 // - ) - { - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractMAPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength, // Max Allowed Loopback ... - validationLength // Validation Length ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XMA", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; - } - - /** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( bool ) - */ - bool AnalyseSARPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractSARPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength // Max Allowed Loopback ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XSAR", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; - } - - /** - * Analyse Market based on Specified Kind of Pivots ... - * - * @param analysis: XPivotAnalysis, reference to hold result ... - * @param barIndex: int, Bar Index ... - * @param requiredNumberOFPivots: int, Specified which Number of Pivots must be Extracted ... - * @param maxAllowedLoopbackLength: int, Specified Maximum Loopback Length for Pivot Extraction ... - * - * @return ( bool ) - */ - bool AnalyseZigZagPivots( - XPivotAnalysis &analysis, - int barIndex = 0, - int requiredNumberOFPivots = 50, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - bool result = false; - - // - // Prepare ... - analysis.Clean(); - - // - // Reading Pivots ... - XPivot pivots[]; - int count = fimaHelper.ExtractZigZagPivots( - pivots, // Result ... - barIndex, // Bar Index ... - requiredNumberOFPivots, // Required Number of Pivots ... - maxAllowedLoopbackLength // Max Allowed Loopback ... - ); - result = IsValidSize(count); - if (!result) - { - // - SpecifiedClean(pivots); - return result; - } - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - - // - // Initialize Analysis ... - result = analysis.Init( - "XFIMA_XZG", - symbol, - period, - pivots // - ); - - // - // Cleanup Resources ... - if (!result) - { - analysis.Clean(); - } - SpecifiedClean(pivots); - - // - return result; - } - - /** - * Destroy ... - */ - void Destroy() - { - // - delete barAnalyser; - ZeroMemory(barAnalyser); - } - - // - // Testers ... - - /** - * Analyse Market based on Specified Bar ... - * - * @param structure: XFIMAMarketStructure, reference to holds result ... - * @param config: XFIMAMarketStructureConfig, reference to Configure Detector ... - * @param barIndex: int, Bar Index ... - */ - void AnalyseMarket( - XFIMAMarketStructure &structure, - XFIMAMarketStructureConfig &config, - int barIndex = 0 // - ) - { - // - // Prepare ... - structure.Clean(); - - // - // Normalize ... - barIndex = NormalizeInt(barIndex, 0); - - // - bool has = false; - - // - string symbol = fimaHelper.GetSymbol(); - ENUM_TIMEFRAMES period = fimaHelper.GetPeriod(); - has = structure.bar.Init( - symbol, - period, - barIndex // - ); - if (!has) - { - // - structure.Clean(); - return; - } - - // - // Reading Bar Patterns ... - XOHCL iBar; - XPatternAnalysis iPatternAnalysis; - for (int i = barIndex; i < barIndex + config.loopback; i++) - { - // - // Cleanup ... - iBar.Clean(); - iPatternAnalysis.Clean(); - - // - // Initialize Indexed Bar ... - // - has = structure.bar.BarAt(i, iBar); - if (!has) - { - break; - } - - // - // Analyse Indexed Bar ... - has = AnalyseBarPatterns(iBar, iPatternAnalysis, config.barsAnalysisConfig); - if (has) - { - // - AddRef( - iPatternAnalysis, - structure.barsAnalysis // - ); - - // - if (i == barIndex) - { - structure.barAnalysis = iPatternAnalysis; - } - } - - // - // Check Satisfied ... - has = ArraySize(structure.barsAnalysis) >= config.requiredPivots; - if (has) - { - break; - } - } - - // - // Handle Pivot Analysis ... - - // - // XPV ... - if (config.analysePVPivots) - { - // - // Reading Pivots ... - has = AnalysePVPivots( - structure.pvAnalysis, - barIndex, - config.requiredPivots, - config.loopback, - config.pvPivotsValidationLength // - ); - if (!has) - { - structure.pvAnalysis.Clean(); - } - } - - // - // XZG ... - if (config.analyseZGPivots) - { - // - // Reading Pivots ... - has = AnalyseZigZagPivots( - structure.zgAnalysis, - barIndex, - config.requiredPivots, - config.loopback // - ); - if (!has) - { - structure.zgAnalysis.Clean(); - } - } - - // - // Cleanup ... - iBar.Clean(); - iPatternAnalysis.Clean(); - } - - // - // Protected ... - protected: - // - // Props ... - - // - // Private ... - private: - // - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class copy.mq5 b/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class copy.mq5 deleted file mode 100644 index 808c889b..00000000 --- a/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class copy.mq5 +++ /dev/null @@ -1,1775 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMAPoiDrawer ... -// Description: XFIMA POI Drawer Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA POI Drawer Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.xfima.lib.mq5" - -// -// Implementation ... -class XCXFIMAPOIDrawer : public XCPOIDrawer -{ - // - public: - // - // Props ... - - // - // Tested Zones ... - color testedBullishColor; - color testedBearishColor; - - // - // Breaked Zones ... - color breakedBullishColor; - color breakedBearishColor; - - // - // FakeBreaked Zones ... - color fakeBreakedBullishColor; - color fakeBreakedBearishColor; - - // - // Constructor ... - XCXFIMAPOIDrawer() : XCPOIDrawer() - { - Default(); - } - - // - // Deconstructor ... - ~XCXFIMAPOIDrawer() - { - } - - // - // Overrides ... - - /** - * Do additional Configurations for Child Classes ... - */ - void virtual Default() override - { - // - // Apply Default Props ... - - // - Prefix(NULL); - ChartIdentification(0); - SubWindowIdentification(0); - - // - defaultBullishStyle.width = 1; - defaultBullishStyle.clr = clrAqua; - defaultBullishStyle.style = STYLE_SOLID; - - // - defaultBearishStyle.width = 1; - defaultBearishStyle.clr = clrMagenta; - defaultBearishStyle.style = STYLE_SOLID; - - // - boxBullishStyle = defaultBullishStyle; - boxBearishStyle = defaultBearishStyle; - - // - testedBullishColor = clrLime; - breakedBullishColor = clrGreen; - fakeBreakedBullishColor = clrYellow; - - // - testedBearishColor = clrRed; - breakedBearishColor = clrDarkRed; - fakeBreakedBearishColor = clrDarkOrange; - } - - // - // Get Specified Directional Arrow Anchor ... - ENUM_ARROW_ANCHOR GetArrowAnchor(ENUM_X_DIRECTION forDir) - { - // - ENUM_ARROW_ANCHOR result = ANCHOR_BOTTOM; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Code ... - int GetArrowCode(ENUM_X_DIRECTION forDir) - { - // - int result = 159; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? 233 - : 234; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Code ... - color GetArrowColor(ENUM_X_DIRECTION forDir) - { - // - color result = clrYellow; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? clrAqua - : clrMagenta; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Price Type ... - ENUM_X_PRICE GetArrowPriceType(ENUM_X_DIRECTION forDir) - { - // - ENUM_X_PRICE result = X_PRICE_CLOSE; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? X_PRICE_LOW - : X_PRICE_HIGH; - } - - // - return result; - } - - /** - * Get Tested Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetTestedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? testedBullishColor - : testedBearishColor; - - // - return result; - } - - /** - * Get Patterns Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetPatternStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetPatternStyle( - style, - zone.dir // - ); - - // - return result; - } - - /** - * Get Patterns Zone Style ... - * - * @param style: reference to hold result ... - * @param forDir: Specified Direction ... - * - * @return ( bool ) - */ - bool GetPatternStyle( - XPOIStyle &style, - ENUM_X_DIRECTION forDir // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - forDir // - ); - - // - style.width = 2; - style.style = STYLE_DASH; - - // - return result; - } - - /** - * Get Breaked Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetBreakedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? breakedBullishColor - : breakedBearishColor; - - // - return result; - } - - /** - * Get Fake Breaked Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetFakeBreakedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? fakeBreakedBullishColor - : fakeBreakedBearishColor; - - // - return result; - } - - /** - * Fill Arrow Based Drawing Specs ... - * - * @param forDir: Specified Direction ... - * @param arrowPriceType: ENUM_X_PRICE, refrence for Arrow Price ... - * @param arrowCode: int, reference for Arrow Code ... - * @param arrowWidth: int, reference for Arrow Width ... - * @param arrowColor: color, reference for Arrow Color ... - * @param arrowAnchor: ENUM_ARROW_ANCHOR, reference for Arrow Anchor ... - */ - void FillArrowSpecs( - ENUM_X_DIRECTION forDir, - ENUM_X_PRICE &arrowPriceType, - int &arrowCode, - int &arrowWidth, - color &arrowColor, - ENUM_ARROW_ANCHOR &arrowAnchor // - ) - { - // - // Prepare ... - arrowCode = 159; - arrowWidth = 2; - arrowColor = CLR_NONE; - arrowAnchor = ANCHOR_BOTTOM; - arrowPriceType = X_PRICE_CLOSE; - - // - if (HasDirection(forDir)) - { - // - arrowCode = GetArrowCode(forDir); - arrowColor = GetArrowColor(forDir); - arrowAnchor = GetArrowAnchor(forDir); - arrowPriceType = GetArrowPriceType(forDir); - } - } - - /** - * Apply Tested Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyTestedStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetTestedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Breaked Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyBreakedStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetBreakedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Tested Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyFakeBreakStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetFakeBreakedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Pattern Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyPatternStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetPatternStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Patterns Style ... - * - * @param object: reference pointer to Object ... - */ - void ApplyPatternsStyle( - CArrayObj *&objects // - ) - { - // - if (objects == NULL || - objects.Total() == 0) - { - return; - } - - // - bool has = false; - XPOIStyle iStyle; - string iName = NULL; - XCBoxObject *iBoxObj = NULL; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - for (int i = 0; i < objects.Total(); i++) - { - // - iBoxObj = (XCBoxObject *)objects.At(i); - iName = iBoxObj.ObjName(); - - // - iDir = - IsSpecifiedValid(iName) && - Contains( - "BULL", - iName // - ) - ? X_DIRECTION_BULLISH - : IsSpecifiedValid(iName) && - Contains( - "BEAR", - iName // - ) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - has = GetPatternStyle(iStyle, iDir); - if (has) - { - // - ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - /** - * Apply Style to Specified Pivot Object ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyPivotStyle( - XCBarArrowObject *&object, - XPOIStyle &style // - ) - { - // - if (object == NULL) - { - return; - } - - // - object.ArrowColor(style.clr); - object.ArrowWidth(style.width); - } - - /** - * Apply Patterns Style ... - * - * @param object: reference pointer to Object ... - */ - void ApplyPivotsStyle( - CArrayObj *&objects // - ) - { - // - if (objects == NULL || - objects.Total() == 0) - { - return; - } - - // - bool has = false; - XPOIStyle iStyle; - string iName = NULL; - XCBarArrowObject *iObj = NULL; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - for (int i = 0; i < objects.Total(); i++) - { - // - iObj = (XCBarArrowObject *)objects.At(i); - iName = iObj.ObjName(); - - // - iDir = - IsSpecifiedValid(iName) && - Contains( - "BULL", - iName // - ) - ? X_DIRECTION_BULLISH - : IsSpecifiedValid(iName) && - Contains( - "BEAR", - iName // - ) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - has = GetPatternStyle(iStyle, iDir); - if (has) - { - // - ApplyPivotStyle( - iObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iObj); - } - } - - /** - * Draw Specified Market Structure Based on Given Configs ... - * - * @param structure: XFIMAMarketStructure, reference to Provide Specifid Market Structure ... - * @param config: XFIMAMarketStructureDrawerConfig, reference to Provide Drawing Configurations ... - * @param objects: CArrayObj, pointer reference to Holds drawn Objects instances ... - * - * @return ( int ) - */ - int DrawMarketStructure( - XFIMAMarketStructure &structure, - XFIMAMarketStructureDrawerConfig &config, - CArrayObj *&objects // - ) - { - // - int result = 0; - - // - // Normalize ... - if (objects == NULL) - { - objects = new CArrayObj(); - } - - // - // Prepare ... - // objects.Clear(); - - // - int count = 0; - bool has = false; - int arrowCode = -1; - int arrowWidth = 3; - string arrowName = NULL; - color arrowColor = CLR_NONE; - ENUM_X_PRICE arrowPriceType = X_PRICE_CLOSE; - ENUM_ARROW_ANCHOR arrowAnchor = ANCHOR_BOTTOM; - - // - int bullArrowCode = GetArrowCode(X_DIRECTION_BULLISH); - int bearArrowCode = GetArrowCode(X_DIRECTION_BEARISH); - - // - // Validate ... - has = structure.bar.IsValid(); - if (!has) - { - return result; - } - - // - // Apply Drawing Methods ... - - // // - // // OB ... - // if (config.drawOB) - // { - // // - // // Validate ... - // has = structure.ob.IsValid(); - // if (has) - // { - // // - // XCBoxObject *iObj; - // has = DrawBox( - // structure.ob, - // iObj // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // FVG ... - // if (config.drawFVG) - // { - // // - // // Validate ... - // has = structure.fvg.IsValid(); - // if (has) - // { - // // - // XCBoxObject *iObj; - // has = DrawBox( - // structure.fvg, - // iObj // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Support ... - // if (config.drawSupport) - // { - // // - // // Validate ... - // has = structure.support.IsValid(); - // if (has) - // { - // // - // XCBoxObject *iObj; - // has = DrawBox( - // structure.support, - // iObj // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Resistance ... - // if (config.drawResistance) - // { - // // - // // Validate ... - // has = structure.resistance.IsValid(); - // if (has) - // { - // // - // XCBoxObject *iObj; - // has = DrawBox( - // structure.resistance, - // iObj // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Swing Trend ... - // if (config.drawSwingTrend) - // { - // // - // // Validate ... - // has = HasDirection(structure.trendDir) && - // HasChild(structure.trendSwings); - // if (has) - // { - // // - // CChartObjectTrend *iObj; - // has = DrawSwingTrend( - // structure.trendSwings, - // structure.trendDir, - // iObj, // - // config.swingTrendRayRight, // Ray Right ... - // config.swingTrendRayLeft // Ray Left ... - // ); - // if (has) - // { - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Start Pattern ... - // if (config.drawStarPattern) - // { - // // - // // Validate ... - // has = HasDirection(structure.starPatternDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.starPatternDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XStar_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Flag Pattern ... - // if (config.drawFlagPattern) - // { - // // - // // Validate ... - // has = HasDirection(structure.flagPatternDir) && - // structure.flagSwing.IsValid(); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.flagPatternDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XFlag_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Rising Pattern ... - // if (config.drawRisingPattern) - // { - // // - // // Validate ... - // has = HasDirection(structure.risingPatternDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.risingPatternDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XRise_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Piercing Pattern ... - // if (config.drawPiercingPattern) - // { - // // - // // Validate ... - // has = HasDirection(structure.piercingPatternDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.piercingPatternDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XPiercing_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Signal Key Bar Pattern ... - // if (config.drawSignalKeyBarPattern) - // { - // // - // // Validate ... - // has = HasDirection(structure.signalKeyBarPatternDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.signalKeyBarPatternDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XSignalKey_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Pinned Bar ... - // if (config.drawPinned) - // { - // // - // // Validate ... - // has = HasDirection(structure.pinnedDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.pinnedDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XPin_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Momentum Bar ... - // if (config.drawMomentum) - // { - // // - // // Validate ... - // has = HasDirection(structure.momentumDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.momentumDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XMomentum_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Engulfed Bar ... - // if (config.drawEngulfed) - // { - // // - // // Validate ... - // has = HasDirection(structure.engulfedDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.engulfedDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XEngulf_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // True Gaped Bar ... - // if (config.drawTrueGaped) - // { - // // - // // Validate ... - // has = HasDirection(structure.trueGapedDir); - // if (has) - // { - // // - // FillArrowSpecs( - // structure.trueGapedDir, - // arrowPriceType, - // arrowCode, - // arrowWidth, - // arrowColor, - // arrowAnchor // - // ); - // XCBarArrowObject *iObj; - // arrowName = "XTrueGap_" + ToMD5(structure.bar.time); - // has = DrawBarArrow( - // structure.bar, - // iObj, - // arrowPriceType, - // arrowCode, - // arrowColor, - // arrowWidth, - // arrowAnchor, - // arrowName // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // XFIMA PV Analysis ... - // if (config.drawFIMAPVPivotsAnalysis) - // { - // // - // // Validate ... - // has = structure.pvAnalysis.IsValid(); - // if (has) - // { - // // - // XCPivotAnalysisObject *iObj; - // has = DrawPivotAnalysis( - // structure.pvAnalysis, - // iObj, - // config.drawFIMAPVPivotsAnalysisTrends, - // config.drawFIMAPVPivotsAnalysisZones, - // config.drawFIMAPVPivotsAnalysisPivots, - // bearArrowCode, - // bullArrowCode // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // XFIMA Sar Analysis ... - // if (config.drawFIMASARPivotsAnalysis) - // { - // // - // // Validate ... - // has = structure.sarAnalysis.IsValid(); - // if (has) - // { - // // - // XCPivotAnalysisObject *iObj; - // has = DrawPivotAnalysis( - // structure.pvAnalysis, - // iObj, - // config.drawFIMASARPivotsAnalysisTrends, - // config.drawFIMASARPivotsAnalysisZones, - // config.drawFIMASARPivotsAnalysisPivots, - // bearArrowCode, - // bullArrowCode // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // XFIMA ZigZag Analysis ... - // if (config.drawFIMAZigZagPivotsAnalysis) - // { - // // - // // Validate ... - // has = structure.zigzagAnalysis.IsValid(); - // if (has) - // { - // // - // XCPivotAnalysisObject *iObj; - // has = DrawPivotAnalysis( - // structure.pvAnalysis, - // iObj, - // config.drawFIMAZigZagPivotsAnalysisTrends, - // config.drawFIMAZigZagPivotsAnalysisZones, - // config.drawFIMAZigZagPivotsAnalysisPivots, - // bearArrowCode, - // bullArrowCode // - // ); - // if (has) - // { - // objects.Add(iObj); - // } - // } - // } - - // // - // // Fake Breaked Zone ... - // if (config.drawFakeBreakedZone && - // structure.fakeBreakedZone.IsValid()) - // { - // // - // XCBoxObject *iObj; - // has = DrawBox( - // structure.fakeBreakedZone, - // iObj // - // ); - // if (has) - // { - // // - // // Apply Style ... - // ApplyFakeBreakStyle( - // iObj, - // structure.fakeBreakedZone // - // ); - - // // - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - - // // - // // Recently Tested Zones ... - // if (config.drawRecentlyTestedZones && - // HasChild(structure.recentlyTestedZones)) - // { - // // - // XCBoxObject *iObj; - // count = ArraySize(structure.recentlyTestedZones); - // for (int i = 0; i < count; i++) - // { - // // - // // Draw Box ... - // has = DrawBox( - // structure.recentlyTestedZones[i], - // iObj // - // ); - // if (has) - // { - // // - // ApplyTestedStyle( - // iObj, - // structure.recentlyTestedZones[i] // - // ); - - // // - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Recently Breaked Zones ... - // if (config.drawRecentlyBreakedZones && - // HasChild(structure.recentlyBreakedZones)) - // { - // // - // XCBoxObject *iObj; - // count = ArraySize(structure.recentlyBreakedZones); - // for (int i = 0; i < count; i++) - // { - // // - // // Draw Box ... - // has = DrawBox( - // structure.recentlyBreakedZones[i], - // iObj // - // ); - // if (has) - // { - // // - // ApplyBreakedStyle( - // iObj, - // structure.recentlyBreakedZones[i] // - // ); - - // // - // objects.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - // } - // } - - // // - // // Draw Recent Patterns ... - // if (config.drawRecentPatterns) - // { - // // - // int baseArrowCode = 159; - // CArrayObj *patternObjects; - - // // - // // Order Blocs ... - // if (config.drawOB && - // HasChild(structure.obs)) - // { - // // - // count = DrawBoxes( - // structure.obs, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Fair Value Gaps ... - // if (config.drawFVG && - // HasChild(structure.fvgs)) - // { - // // - // count = DrawBoxes( - // structure.fvgs, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Supports ... - // if (config.drawSupport && - // HasChild(structure.supports)) - // { - // // - // count = DrawBoxes( - // structure.supports, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Resistances ... - // if (config.drawResistance && - // HasChild(structure.obs)) - // { - // // - // count = DrawBoxes( - // structure.resistances, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Pin Bars ... - // if (config.drawPinned && - // HasChild(structure.pinBars)) - // { - // // - // count = DrawPivots( - // structure.pinBars, - // patternObjects, - // baseArrowCode, - // baseArrowCode // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPivotsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Engulf Bars ... - // if (config.drawEngulfed && - // HasChild(structure.engulfBars)) - // { - // // - // count = DrawPivots( - // structure.engulfBars, - // patternObjects, - // baseArrowCode, - // baseArrowCode // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPivotsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // TrueGap Bars ... - // if (config.drawTrueGaped && - // HasChild(structure.trueGapBars)) - // { - // // - // count = DrawPivots( - // structure.trueGapBars, - // patternObjects, - // baseArrowCode, - // baseArrowCode // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPivotsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Momentum Bars ... - // if (config.drawMomentum && - // HasChild(structure.momentumBars)) - // { - // // - // count = DrawPivots( - // structure.momentumBars, - // patternObjects, - // baseArrowCode, - // baseArrowCode // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPivotsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Flag Pattern ... - // if (config.drawFlagPattern && - // HasChild(structure.flagPatterns)) - // { - // // - // count = DrawBoxes( - // structure.flagPatterns, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Star Pattern ... - // if (config.drawStarPattern && - // HasChild(structure.starPatterns)) - // { - // // - // count = DrawBoxes( - // structure.starPatterns, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Rising Pattern ... - // if (config.drawRisingPattern && - // HasChild(structure.risingPatterns)) - // { - // // - // count = DrawBoxes( - // structure.risingPatterns, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // Piercing Pattern ... - // if (config.drawPiercingPattern && - // HasChild(structure.piercingPatterns)) - // { - // // - // count = DrawBoxes( - // structure.piercingPatterns, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - - // // - // // SignalKeyBar Pattern ... - // if (config.drawSignalKeyBarPattern && - // HasChild(structure.signalKeyBarPatterns)) - // { - // // - // count = DrawBoxes( - // structure.signalKeyBarPatterns, - // patternObjects // - // ); - // has = IsValidSize(count); - // if (has) - // { - // // - // ApplyPatternsStyle(patternObjects); - - // // - // AddObjects( - // patternObjects, - // objects // - // ); - // } - - // // - // ZeroMemory(patternObjects); - // } - // } - - // - result = objects.Total(); - - // - return result; - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class.mq5 b/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class.mq5 deleted file mode 100644 index 8e2661c4..00000000 --- a/Documents/BKP/x-saherelm.xfima.x-poi.drawer.class.mq5 +++ /dev/null @@ -1,1949 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class -// ------------------------------------------------- -// Name: XCXFIMAPoiDrawer ... -// Description: XFIMA POI Drawer Class ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XFIMA POI Drawer Class" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.xfima.lib.mq5" - -// -// Implementation ... -class XCXFIMAPOIDrawer : public XCPOIDrawer -{ - // - public: - // - // Props ... - - // - // Tested Zones ... - color testedBullishColor; - color testedBearishColor; - - // - // Breaked Zones ... - color breakedBullishColor; - color breakedBearishColor; - - // - // FakeBreaked Zones ... - color fakeBreakedBullishColor; - color fakeBreakedBearishColor; - - // - // Constructor ... - XCXFIMAPOIDrawer() : XCPOIDrawer() - { - Default(); - } - - // - // Deconstructor ... - ~XCXFIMAPOIDrawer() - { - } - - // - // Overrides ... - - /** - * Do additional Configurations for Child Classes ... - */ - void virtual Default() override - { - // - // Apply Default Props ... - - // - Prefix(NULL); - ChartIdentification(0); - SubWindowIdentification(0); - - // - defaultBullishStyle.width = 1; - defaultBullishStyle.clr = clrAqua; - defaultBullishStyle.style = STYLE_SOLID; - - // - defaultBearishStyle.width = 1; - defaultBearishStyle.clr = clrMagenta; - defaultBearishStyle.style = STYLE_SOLID; - - // - boxBullishStyle = defaultBullishStyle; - boxBearishStyle = defaultBearishStyle; - - // - testedBullishColor = clrLime; - breakedBullishColor = clrGreen; - fakeBreakedBullishColor = clrYellow; - - // - testedBearishColor = clrRed; - breakedBearishColor = clrDarkRed; - fakeBreakedBearishColor = clrDarkOrange; - } - - // - // Get Specified Directional Arrow Anchor ... - ENUM_ARROW_ANCHOR GetArrowAnchor(ENUM_X_DIRECTION forDir) - { - // - ENUM_ARROW_ANCHOR result = ANCHOR_BOTTOM; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Code ... - int GetArrowCode(ENUM_X_DIRECTION forDir) - { - // - int result = 159; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? 233 - : 234; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Code ... - color GetArrowColor(ENUM_X_DIRECTION forDir) - { - // - color result = clrYellow; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? clrAqua - : clrMagenta; - } - - // - return result; - } - - // - // Get Specified Directional Arrow Price Type ... - ENUM_X_PRICE GetArrowPriceType(ENUM_X_DIRECTION forDir) - { - // - ENUM_X_PRICE result = X_PRICE_CLOSE; - - // - if (HasDirection(forDir)) - { - // - result = - IsSpecifiedBullish(forDir) - ? X_PRICE_LOW - : X_PRICE_HIGH; - } - - // - return result; - } - - /** - * Get Tested Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetTestedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? testedBullishColor - : testedBearishColor; - - // - return result; - } - - /** - * Get Patterns Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetPatternStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetPatternStyle( - style, - zone.dir // - ); - - // - return result; - } - - /** - * Get Patterns Zone Style ... - * - * @param style: reference to hold result ... - * @param forDir: Specified Direction ... - * - * @return ( bool ) - */ - bool GetPatternStyle( - XPOIStyle &style, - ENUM_X_DIRECTION forDir // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - forDir // - ); - - // - style.width = 2; - style.style = STYLE_DASH; - - // - return result; - } - - /** - * Get Breaked Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetBreakedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? breakedBullishColor - : breakedBearishColor; - - // - return result; - } - - /** - * Get Fake Breaked Zone Style ... - * - * @param style: reference to hold result ... - * @param zone: Specified Zone ... - * - * @return ( bool ) - */ - bool GetFakeBreakedStyle( - XPOIStyle &style, - XBoxZone &zone // - ) - { - // - bool result = false; - - // - style.Clean(); - - // - result = zone.IsValid(); - if (!result) - { - return result; - } - - // - GetBoxStyle( - style, - zone.dir // - ); - - // - style.width = 3; - style.clr = - zone.IsBullish() - ? fakeBreakedBullishColor - : fakeBreakedBearishColor; - - // - return result; - } - - /** - * Fill Arrow Based Drawing Specs ... - * - * @param forDir: Specified Direction ... - * @param arrowPriceType: ENUM_X_PRICE, refrence for Arrow Price ... - * @param arrowCode: int, reference for Arrow Code ... - * @param arrowWidth: int, reference for Arrow Width ... - * @param arrowColor: color, reference for Arrow Color ... - * @param arrowAnchor: ENUM_ARROW_ANCHOR, reference for Arrow Anchor ... - */ - void FillArrowSpecs( - ENUM_X_DIRECTION forDir, - ENUM_X_PRICE &arrowPriceType, - int &arrowCode, - int &arrowWidth, - color &arrowColor, - ENUM_ARROW_ANCHOR &arrowAnchor // - ) - { - // - // Prepare ... - arrowCode = 159; - arrowWidth = 2; - arrowColor = CLR_NONE; - arrowAnchor = ANCHOR_BOTTOM; - arrowPriceType = X_PRICE_CLOSE; - - // - if (HasDirection(forDir)) - { - // - arrowCode = GetArrowCode(forDir); - arrowColor = GetArrowColor(forDir); - arrowAnchor = GetArrowAnchor(forDir); - arrowPriceType = GetArrowPriceType(forDir); - } - } - - /** - * Apply Tested Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyTestedStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetTestedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Breaked Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyBreakedStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetBreakedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Tested Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyFakeBreakStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetFakeBreakedStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Pattern Style ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyPatternStyle( - XCBoxObject *&object, - XBoxZone &zone // - ) - { - // - if (!zone.IsValid() || - object == NULL) - { - return; - } - - // - XPOIStyle style; - if (!GetPatternStyle(style, zone)) - { - return; - } - - // - ApplyBoxStyle( - object, - style // - ); - } - - /** - * Apply Patterns Style ... - * - * @param object: reference pointer to Object ... - */ - void ApplyPatternsStyle( - CArrayObj *&objects // - ) - { - // - if (objects == NULL || - objects.Total() == 0) - { - return; - } - - // - bool has = false; - XPOIStyle iStyle; - string iName = NULL; - XCBoxObject *iBoxObj = NULL; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - for (int i = 0; i < objects.Total(); i++) - { - // - iBoxObj = (XCBoxObject *)objects.At(i); - iName = iBoxObj.ObjName(); - - // - iDir = - IsSpecifiedValid(iName) && - Contains( - "BULL", - iName // - ) - ? X_DIRECTION_BULLISH - : IsSpecifiedValid(iName) && - Contains( - "BEAR", - iName // - ) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - has = GetPatternStyle(iStyle, iDir); - if (has) - { - // - ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - /** - * Apply Style to Specified Pivot Object ... - * - * @param object: reference pointer to Object ... - * @param zone: reference to Zone ... - */ - void ApplyPivotStyle( - XCBarArrowObject *&object, - XPOIStyle &style // - ) - { - // - if (object == NULL) - { - return; - } - - // - object.ArrowColor(style.clr); - object.ArrowWidth(style.width); - } - - /** - * Apply Patterns Style ... - * - * @param object: reference pointer to Object ... - */ - void ApplyPivotsStyle( - CArrayObj *&objects // - ) - { - // - if (objects == NULL || - objects.Total() == 0) - { - return; - } - - // - bool has = false; - XPOIStyle iStyle; - string iName = NULL; - XCBarArrowObject *iObj = NULL; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - for (int i = 0; i < objects.Total(); i++) - { - // - iObj = (XCBarArrowObject *)objects.At(i); - iName = iObj.ObjName(); - - // - iDir = - IsSpecifiedValid(iName) && - Contains( - "BULL", - iName // - ) - ? X_DIRECTION_BULLISH - : IsSpecifiedValid(iName) && - Contains( - "BEAR", - iName // - ) - ? X_DIRECTION_BEARISH - : X_DIRECTION_NONE; - - // - has = GetPatternStyle(iStyle, iDir); - if (has) - { - // - ApplyPivotStyle( - iObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iObj); - } - } - - /** - * Draw Specified Market Structure Based on Given Configs ... - * - * @param structure: XFIMAMarketStructure, reference to Provide Specifid Market Structure ... - * @param config: XFIMAMarketStructureDrawerConfig, reference to Provide Drawing Configurations ... - * @param objects: CArrayObj, pointer reference to Holds drawn Objects instances ... - * - * @return ( int ) - */ - int DrawMarketStructure( - XFIMAMarketStructure &structure, - XFIMAMarketStructureDrawerConfig &config, - CArrayObj *&objects // - ) - { - // - int result = 0; - - // - // Normalize ... - if (objects == NULL) - { - objects = new CArrayObj(); - } - - // - // Prepare ... - // objects.Clear(); - - // - int count = 0; - bool has = false; - int arrowCode = -1; - int arrowWidth = 3; - string arrowName = NULL; - color arrowColor = CLR_NONE; - ENUM_X_PRICE arrowPriceType = X_PRICE_CLOSE; - ENUM_ARROW_ANCHOR arrowAnchor = ANCHOR_BOTTOM; - - // - int bullArrowCode = GetArrowCode(X_DIRECTION_BULLISH); - int bearArrowCode = GetArrowCode(X_DIRECTION_BEARISH); - - // - // Validate ... - has = structure.bar.IsValid(); - if (!has) - { - return result; - } - - // - // Apply Drawing Methods ... - - // - // OB ... - if (config.drawOB) - { - // - // Validate ... - has = structure.ob.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = DrawBox( - structure.ob, - iObj // - ); - if (has) - { - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // FVG ... - if (config.drawFVG) - { - // - // Validate ... - has = structure.fvg.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = DrawBox( - structure.fvg, - iObj // - ); - if (has) - { - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Support ... - if (config.drawSupport) - { - // - // Validate ... - has = structure.support.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = DrawBox( - structure.support, - iObj // - ); - if (has) - { - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Resistance ... - if (config.drawResistance) - { - // - // Validate ... - has = structure.resistance.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = DrawBox( - structure.resistance, - iObj // - ); - if (has) - { - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Swing Trend ... - if (config.drawSwingTrend) - { - // - // Validate ... - has = HasDirection(structure.trendDir) && - HasChild(structure.trendSwings); - if (has) - { - // - CChartObjectTrend *iObj; - has = DrawSwingTrend( - structure.trendSwings, - structure.trendDir, - iObj, // - config.swingTrendRayRight, // Ray Right ... - config.swingTrendRayLeft // Ray Left ... - ); - if (has) - { - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Start Pattern ... - if (config.drawStarPattern) - { - // - // Validate ... - has = HasDirection(structure.starPatternDir); - if (has) - { - // - FillArrowSpecs( - structure.starPatternDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XStar_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Flag Pattern ... - if (config.drawFlagPattern) - { - // - // Validate ... - has = HasDirection(structure.flagPatternDir) && - structure.flagSwing.IsValid(); - if (has) - { - // - FillArrowSpecs( - structure.flagPatternDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XFlag_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Rising Pattern ... - if (config.drawRisingPattern) - { - // - // Validate ... - has = HasDirection(structure.risingPatternDir); - if (has) - { - // - FillArrowSpecs( - structure.risingPatternDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XRise_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Piercing Pattern ... - if (config.drawPiercingPattern) - { - // - // Validate ... - has = HasDirection(structure.piercingPatternDir); - if (has) - { - // - FillArrowSpecs( - structure.piercingPatternDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XPiercing_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Signal Key Bar Pattern ... - if (config.drawSignalKeyBarPattern) - { - // - // Validate ... - has = HasDirection(structure.signalKeyBarPatternDir); - if (has) - { - // - FillArrowSpecs( - structure.signalKeyBarPatternDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XSignalKey_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Pinned Bar ... - if (config.drawPinned) - { - // - // Validate ... - has = HasDirection(structure.pinnedDir); - if (has) - { - // - FillArrowSpecs( - structure.pinnedDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XPin_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Momentum Bar ... - if (config.drawMomentum) - { - // - // Validate ... - has = HasDirection(structure.momentumDir); - if (has) - { - // - FillArrowSpecs( - structure.momentumDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XMomentum_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Engulfed Bar ... - if (config.drawEngulfed) - { - // - // Validate ... - has = HasDirection(structure.engulfedDir); - if (has) - { - // - FillArrowSpecs( - structure.engulfedDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XEngulf_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // True Gaped Bar ... - if (config.drawTrueGaped) - { - // - // Validate ... - has = HasDirection(structure.trueGapedDir); - if (has) - { - // - FillArrowSpecs( - structure.trueGapedDir, - arrowPriceType, - arrowCode, - arrowWidth, - arrowColor, - arrowAnchor // - ); - XCBarArrowObject *iObj; - arrowName = "XTrueGap_" + ToMD5(structure.bar.time); - has = DrawBarArrow( - structure.bar, - iObj, - arrowPriceType, - arrowCode, - arrowColor, - arrowWidth, - arrowAnchor, - arrowName // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // XFIMA PV Analysis ... - if (config.drawFIMAPVPivotsAnalysis) - { - // - // Validate ... - has = structure.pvAnalysis.IsValid(); - if (has) - { - // - XCPivotAnalysisObject *iObj; - has = DrawPivotAnalysis( - structure.pvAnalysis, - iObj, - config.drawFIMAPVPivotsAnalysisTrends, - config.drawFIMAPVPivotsAnalysisZones, - config.drawFIMAPVPivotsAnalysisPivots, - bearArrowCode, - bullArrowCode // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // XFIMA Sar Analysis ... - if (config.drawFIMASARPivotsAnalysis) - { - // - // Validate ... - has = structure.sarAnalysis.IsValid(); - if (has) - { - // - XCPivotAnalysisObject *iObj; - has = DrawPivotAnalysis( - structure.pvAnalysis, - iObj, - config.drawFIMASARPivotsAnalysisTrends, - config.drawFIMASARPivotsAnalysisZones, - config.drawFIMASARPivotsAnalysisPivots, - bearArrowCode, - bullArrowCode // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // XFIMA ZigZag Analysis ... - if (config.drawFIMAZigZagPivotsAnalysis) - { - // - // Validate ... - has = structure.zigzagAnalysis.IsValid(); - if (has) - { - // - XCPivotAnalysisObject *iObj; - has = DrawPivotAnalysis( - structure.pvAnalysis, - iObj, - config.drawFIMAZigZagPivotsAnalysisTrends, - config.drawFIMAZigZagPivotsAnalysisZones, - config.drawFIMAZigZagPivotsAnalysisPivots, - bearArrowCode, - bullArrowCode // - ); - if (has) - { - objects.Add(iObj); - } - } - } - - // - // Fake Breaked Zone ... - if (config.drawFakeBreakedZone && - structure.fakeBreakedZone.IsValid()) - { - // - XCBoxObject *iObj; - has = DrawBox( - structure.fakeBreakedZone, - iObj // - ); - if (has) - { - // - // Apply Style ... - ApplyFakeBreakStyle( - iObj, - structure.fakeBreakedZone // - ); - - // - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Recently Tested Zones ... - if (config.drawRecentlyTestedZones && - HasChild(structure.recentlyTestedZones)) - { - // - XCBoxObject *iObj; - count = ArraySize(structure.recentlyTestedZones); - for (int i = 0; i < count; i++) - { - // - // Draw Box ... - has = DrawBox( - structure.recentlyTestedZones[i], - iObj // - ); - if (has) - { - // - ApplyTestedStyle( - iObj, - structure.recentlyTestedZones[i] // - ); - - // - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Recently Breaked Zones ... - if (config.drawRecentlyBreakedZones && - HasChild(structure.recentlyBreakedZones)) - { - // - XCBoxObject *iObj; - count = ArraySize(structure.recentlyBreakedZones); - for (int i = 0; i < count; i++) - { - // - // Draw Box ... - has = DrawBox( - structure.recentlyBreakedZones[i], - iObj // - ); - if (has) - { - // - ApplyBreakedStyle( - iObj, - structure.recentlyBreakedZones[i] // - ); - - // - objects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - } - - // - // Draw Recent Patterns ... - if (config.drawRecentPatterns) - { - // - int baseArrowCode = 159; - CArrayObj *patternObjects; - - // - // Order Blocs ... - if (config.drawOB && - HasChild(structure.obs)) - { - // - count = DrawBoxes( - structure.obs, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Fair Value Gaps ... - if (config.drawFVG && - HasChild(structure.fvgs)) - { - // - count = DrawBoxes( - structure.fvgs, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Supports ... - if (config.drawSupport && - HasChild(structure.supports)) - { - // - count = DrawBoxes( - structure.supports, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Resistances ... - if (config.drawResistance && - HasChild(structure.obs)) - { - // - count = DrawBoxes( - structure.resistances, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Pin Bars ... - if (config.drawPinned && - HasChild(structure.pinBars)) - { - // - count = DrawPivots( - structure.pinBars, - patternObjects, - baseArrowCode, - baseArrowCode // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPivotsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Engulf Bars ... - if (config.drawEngulfed && - HasChild(structure.engulfBars)) - { - // - count = DrawPivots( - structure.engulfBars, - patternObjects, - baseArrowCode, - baseArrowCode // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPivotsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // TrueGap Bars ... - if (config.drawTrueGaped && - HasChild(structure.trueGapBars)) - { - // - count = DrawPivots( - structure.trueGapBars, - patternObjects, - baseArrowCode, - baseArrowCode // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPivotsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Momentum Bars ... - if (config.drawMomentum && - HasChild(structure.momentumBars)) - { - // - count = DrawPivots( - structure.momentumBars, - patternObjects, - baseArrowCode, - baseArrowCode // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPivotsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Flag Pattern ... - if (config.drawFlagPattern && - HasChild(structure.flagPatterns)) - { - // - count = DrawBoxes( - structure.flagPatterns, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Star Pattern ... - if (config.drawStarPattern && - HasChild(structure.starPatterns)) - { - // - count = DrawBoxes( - structure.starPatterns, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Rising Pattern ... - if (config.drawRisingPattern && - HasChild(structure.risingPatterns)) - { - // - count = DrawBoxes( - structure.risingPatterns, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // Piercing Pattern ... - if (config.drawPiercingPattern && - HasChild(structure.piercingPatterns)) - { - // - count = DrawBoxes( - structure.piercingPatterns, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - - // - // SignalKeyBar Pattern ... - if (config.drawSignalKeyBarPattern && - HasChild(structure.signalKeyBarPatterns)) - { - // - count = DrawBoxes( - structure.signalKeyBarPatterns, - patternObjects // - ); - has = IsValidSize(count); - if (has) - { - // - ApplyPatternsStyle(patternObjects); - - // - AddObjects( - patternObjects, - objects // - ); - } - - // - ZeroMemory(patternObjects); - } - } - - // - result = objects.Total(); - - // - return result; - } - - // -}; - -/** - * Draw Pivot Analysis ... - * - * @param analysis: XPivotAnalysis, referece Specified Pivot Analysis ... - * @param object: XCPivotAnalysisObject, pointer reference for Drawn Object ... - * @param drawTrends: Specified to Draw Trends or not ... - * @param drawZones: Specified to Draw Support and Resistance Zones or not ... - * @param drawPivots: Specified to Draw Pivots or not ... - * @param peakArrow: int, Specified Arrow Code for Peak Pivots ... - * @param valeArrow: int, Specified Arrow Code for Vale Pivots ... - * @param threshold: int, distance between price and arrow in Point ... - * - * @return ( bool ) - */ -bool DrawPivotAnalysis( - XPivotAnalysis &analysis, - XCPivotAnalysisObject *&object, - bool drawTrends = true, - bool drawZones = true, - bool drawPivots = true, - int peakArrow = 159, - int valeArrow = 159, - int threshold = 5 // -) -{ - // - bool result = false; - - // - // Prepare ... - object = NULL; - - // - // Normalize ... - - // - // Validate ... - result = analysis.IsValid() && - analysis.IsAnalysed(); - if (!result) - { - return result; - } - - // - object = new XCPivotAnalysisObject(); - result = object.Create( - ChartIdentification(), - SubWindowIdentification(), - analysis, - drawTrends, - drawZones, - drawPivots, - peakArrow, - valeArrow, - threshold // - ); - if (result) - { - // - ApplyPivotAnalysisStyle( - object, - analysis // - ); - } - - // - return result; -} - -/** - * Apply Specified Style to Specified Object ... - * - * @param object: CChartObject, pointer reference of Object ... - * @param model: XPivotAnalysis, referece to access requirements ... - */ -void ApplyPivotAnalysisStyle( - XCPivotAnalysisObject *&object, - XPivotAnalysis &model // -) -{ - // - // Validate ... - bool has = model.IsValid() && - model.IsAnalysed() && - object != NULL; - if (!has) - { - return; - } - - // - XPOIStyle style; - - // - // Support ... - style = defaultBullishStyle; - object.SupportColor(style.clr); - object.SupportWidth(style.width); - object.SupportStyle(style.style); - - // - // Resistance ... - style = defaultBearishStyle; - object.ResistanceColor(style.clr); - object.ResistanceWidth(style.width); - object.ResistanceStyle(style.style); - - // - // Upper ... - if (model.IsPeakAnalysed()) - { - // - GetStyle( - style, - model.peakDir // - ); - if (!HasDirection(model.peakDir)) - { - // - style.Default(); - style.clr = clrGray; - } - - // - object.UpperColor(style.clr); - object.UpperWidth(style.width); - object.UpperStyle(style.style); - object.UpperRayLeft(false); - object.UpperRayRight(true); - } - - // - // Lower ... - if (model.IsValeAnalysed()) - { - // - GetStyle( - style, - model.valeDir // - ); - if (!HasDirection(model.valeDir)) - { - // - style.Default(); - style.clr = clrGray; - } - - // - object.LowerColor(style.clr); - object.LowerWidth(style.width); - object.LowerStyle(style.style); - object.UpperRayLeft(false); - object.LowerRayRight(true); - } - - // - // Peak Pivots ... - style = defaultBearishStyle; - object.PeaksColor(style.clr); - object.PeaksWidth(style.width); - object.PeaksAnchor(ANCHOR_BOTTOM); - - // - // Vale Pivots ... - style = defaultBullishStyle; - object.ValesColor(style.clr); - object.ValesWidth(style.width); - object.ValesAnchor(ANCHOR_TOP); - - // - style.Clean(); -} - -// \ No newline at end of file diff --git a/Documents/BKP/x-tmp-market-analyser.codes.mq5 b/Documents/BKP/x-tmp-market-analyser.codes.mq5 deleted file mode 100644 index 14786e63..00000000 --- a/Documents/BKP/x-tmp-market-analyser.codes.mq5 +++ /dev/null @@ -1,826 +0,0 @@ - -/** - * Analyse Market based on Specified Bar ... - * - * @param forBar: XOHCL, reference Specified Bar for Analyse Market ... - * @param structure: XFIMAMarketStructure, reference to holds result ... - * @param config: XFIMAPatternDetectorConfig, reference to Configure Detector ... - */ -void AnalyseMarket( - XOHCL &forBar, - XFIMAMarketStructure &structure, - XFIMAPatternDetectorConfig &config // -) -{ - // - // Prepare ... - structure.Clean(); - - // - // Validate ... - if (!forBar.IsValid()) - { - return; - } - - // - // Do Analysis ... - - // - structure.bar = forBar; - - // - int idx = -1; - bool has = false; - int maxAllowedCollecting = 50; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Detecting POI Based on Config ... - - // - // Order Block ... - if (config.detectOB) - { - // - bool isOB = HasOB( - forBar, - iDir, - structure.ob, - config.obLoopback // - ); - bool isBullishOB = isOB && - IsSpecifiedBullish(iDir); - bool isBearishOB = isOB && - IsSpecifiedBearish(iDir); - if (!isOB) - { - structure.ob.Clean(); - } - - // - // Detect Touches ... - if (isOB) - { - // - AddIfNotExists( - structure.ob, - obs, - maxAllowedCollecting // - ); - - // - XOHCL pBar; - bool has = forBar.GetPreviousBar(pBar); - if (has) - { - // - structure.isOBTouched = - isBullishOB - ? pBar.low < structure.ob.upper - : pBar.high > structure.ob.lower; - } - - // - pBar.Clean(); - } - } - - // - // Fair Value Gap ... - if (config.detectFVG) - { - // - bool isFVG = HasFVG( - forBar, - iDir, - structure.fvg, - config.fvgLoopback // - ); - bool isBullishFVG = isFVG && - IsSpecifiedBullish(iDir); - bool isBearishFVG = isFVG && - IsSpecifiedBearish(iDir); - if (!isFVG) - { - structure.fvg.Clean(); - } - - // - // Detect Touches ... - if (isFVG) - { - // - AddIfNotExists( - structure.fvg, - fvgs, - maxAllowedCollecting // - ); - - // - XOHCL pBar; - bool has = forBar.GetPreviousBar(pBar); - if (has) - { - // - structure.isFVGTouched = - isBullishFVG - ? pBar.low < structure.fvg.upper - : pBar.high > structure.fvg.lower; - } - - // - pBar.Clean(); - } - } - - // - // Checking Momentum Bar ... - if (config.detectMomentum) - { - // - bool isMomentum = IsMomentumBar( - forBar, - iDir, - config.momentumBarRangeLength, - config.momentumBarApprovedMultiplier // - ); - bool isBullishMomentum = isMomentum && - IsSpecifiedBullish(iDir); - bool isBearishMomentum = isMomentum && - IsSpecifiedBearish(iDir); - if (isMomentum) - { - structure.momentumDir = iDir; - } - } - - // - // Checking Engulfed Bar ... - if (config.detectEngulfed) - { - // - bool isEngulfed = IsEngulfedBar( - forBar, - iDir // - ); - bool isBullishEngulfed = isEngulfed && - IsSpecifiedBullish(iDir); - bool isBearishEngulfed = isEngulfed && - IsSpecifiedBearish(iDir); - if (isEngulfed) - { - structure.engulfedDir = iDir; - } - } - - // - // Checking TruGaped Bar ... - if (config.detectTrueGaped) - { - // - bool isTrueGaped = IsTrueGapedBar( - forBar, - iDir, - config.truwGapApprovedPointMultiplier // - ); - bool isBullishTrueGaped = isTrueGaped && - IsSpecifiedBullish(iDir); - bool isBearishTrueGaped = isTrueGaped && - IsSpecifiedBearish(iDir); - if (isTrueGaped) - { - structure.trueGapedDir = iDir; - } - } - - // - // Checking Pinned Bar ... - if (config.detectPinned) - { - // - bool isPinned = IsPinnedBar( - forBar, - iDir, - config.pinnedBaarShadowApprovedMultiplier, - config.pinnedBarMinimumPinBarRangeMultiplier, - config.pinnedBarForceDirection // - ); - bool isBullishPinned = isPinned && - IsSpecifiedBullish(iDir); - bool isBearishPinned = isPinned && - IsSpecifiedBearish(iDir); - if (isPinned) - { - structure.pinnedDir = iDir; - } - } - - // - // Checking Star Pattern ... - if (config.detectStarPattern) - { - // - bool isStarPattern = IsStartPattern( - forBar, - iDir // - ); - bool isBullishStarPattern = isStarPattern && - IsSpecifiedBullish(iDir); - bool isBearishStarPattern = isStarPattern && - IsSpecifiedBearish(iDir); - if (isStarPattern) - { - structure.starPatternDir = iDir; - } - } - - // - // Checking Piercing Pattern ... - if (config.detectPiercingPattern) - { - // - bool isPiercingPattern = IsPiercingPattern( - forBar, - iDir // - ); - bool isBullishPiercingPattern = isPiercingPattern && - IsSpecifiedBullish(iDir); - bool isBearishPiercingPattern = isPiercingPattern && - IsSpecifiedBearish(iDir); - if (isPiercingPattern) - { - structure.piercingPatternDir = iDir; - } - } - - // - // Checking Rising Pattern ... - if (config.detectRisingPattern) - { - // - bool isRisingPattern = IsRisingPattern( - forBar, - iDir // - ); - bool isBullishRisingPattern = isRisingPattern && - IsSpecifiedBullish(iDir); - bool isBearishRisingPattern = isRisingPattern && - IsSpecifiedBearish(iDir); - if (isRisingPattern) - { - structure.risingPatternDir = iDir; - } - } - - // - // Checking Flag Pattern ... - if (config.detectFlagPattern) - { - // - XOHCL swingBar; - bool isFlagPattern = IsFlagPattern( - forBar, - iDir, - swingBar, - config.flagPatternMinimumPullbackBars // - ); - bool isBullishFlagPattern = isFlagPattern && - IsSpecifiedBullish(iDir); - bool isBearishFlagPattern = isFlagPattern && - IsSpecifiedBearish(iDir); - if (isFlagPattern) - { - // - structure.flagSwing = swingBar; - structure.flagPatternDir = iDir; - } - swingBar.Clean(); - } - - // - // Detect SignalKey Bar Pattern ... - if (config.detectSignalKeyBarPattern) - { - // - bool isSignalKeyBar = IsSignalKeyBarPattern( - forBar, - iDir, - config.signalKeyBarShadowApprovedMultiplier, - config.signalKeyBarMinimumPinBarRangeMultiplier, - config.signalKeyBarForceDirection // - ); - bool isBullishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBullish(iDir); - bool isBearishSignalKeyBar = isSignalKeyBar && - IsSpecifiedBearish(iDir); - if (isSignalKeyBar) - { - structure.signalKeyBarPatternDir = iDir; - } - } - - // - // Detect Swing Trend ... - if (config.detectSwingTrend) - { - // - XOHCL swings[]; - bool hasSwingTrend = HasSwingTrend( - forBar, - iDir, - swings, - config.trendingNumberOfSwings, - config.trendingSwingShoulders // - ); - bool hasBullishSwingTrend = hasSwingTrend && - IsSpecifiedBullish(iDir); - bool hasBearishSwingTrend = hasSwingTrend && - IsSpecifiedBearish(iDir); - if (hasSwingTrend) - { - // - Copy( - swings, - structure.trendSwings // - ); - structure.trendDir = iDir; - } - SpecifiedClean(swings); - } - - // - // Detect Supports ... - if (config.detectSupport) - { - // - XOHCL support; - bool hasSupport = HasSupport( - forBar, - support, - config.supportAndResistanceValidationLength, - config.supportAndResistanceMaxAllowedLoopback // - ); - if (hasSupport) - { - // - XBoxZone supportBox; - has = ToSupportBox(support, supportBox); - - // - // Validate Zone Strength if Provided ... - if (config.minAllowdSupportAndResistanceStrength > 0) - { - // - has = has && - ValidateStrength( - supportBox, - config.minAllowdSupportAndResistanceStrength // - ); - } - - // - if (has) - { - // - AddIfNotExists( - supportBox, - supports, - maxAllowedCollecting // - ); - - // - structure.support = supportBox; - } - - // - // Check for Support Touches ... - XOHCL pBar; - has = has && - forBar.GetPreviousBar(pBar); - if (has) - { - structure.isSupportTouched = pBar.low < supportBox.upper; - } - - // - pBar.Clean(); - supportBox.Clean(); - } - support.Clean(); - } - - // - // Detect Resistance ... - if (config.detectResistance) - { - // - XOHCL resistance; - bool hasResistance = HasResistance( - forBar, - resistance, - config.supportAndResistanceValidationLength, - config.supportAndResistanceMaxAllowedLoopback // - ); - if (hasResistance) - { - // - XBoxZone resistanceBox; - has = ToResistanceBox(resistance, resistanceBox); - - // - // Validate Zone Strength if Provided ... - if (config.minAllowdSupportAndResistanceStrength > 0) - { - // - has = has && - ValidateStrength( - resistanceBox, - config.minAllowdSupportAndResistanceStrength // - ); - } - - // - if (has) - { - // - AddIfNotExists( - resistanceBox, - resistances, - maxAllowedCollecting // - ); - - // - structure.resistance = resistanceBox; - } - - // - // Check for Resistance Touches ... - XOHCL pBar; - has = has && - forBar.GetPreviousBar(pBar); - if (has) - { - structure.isResistanceTouched = pBar.high > resistanceBox.upper; - } - - // - pBar.Clean(); - resistanceBox.Clean(); - } - resistance.Clean(); - } - - // - // Analysers ... - - // - // Analyse Based on PV ... - if (config.analyseFIMAPVPivots) - { - // - XPivotAnalysis analysis; - has = AnalysePVPivots( - analysis, // Result ... - forBar.Index(), // Bar Index ... - config.numberOfRequiredPivotsForAnalysis, // Required Number of Pivots ... - config.maxAllowedLoopbackLengthForAnalysis, // Max Allowed Loopback ... - config.pvPivotsValidationLength // Validation Length ... - ); - if (has) - { - structure.pvAnalysis = analysis; - } - } - - // - // Analyse Based on MA ... - if (config.analyseFIMAMAPivots) - { - // - XPivotAnalysis analysis; - has = AnalyseMAPivots( - analysis, // Result ... - forBar.Index(), // Bar Index ... - config.numberOfRequiredPivotsForAnalysis, // Required Number of Pivots ... - config.maxAllowedLoopbackLengthForAnalysis, // Max Allowed Loopback ... - config.pvPivotsValidationLength // Validation Length ... - ); - if (has) - { - structure.maAnalysis = analysis; - } - } - - // - // Analyse Based on SAR ... - if (config.analyseFIMASARPivots) - { - // - XPivotAnalysis analysis; - has = AnalyseSARPivots( - analysis, // Result ... - forBar.Index(), // Bar Index ... - config.numberOfRequiredPivotsForAnalysis, // Required Number of Pivots ... - config.maxAllowedLoopbackLengthForAnalysis // Max Allowed Loopback ... - ); - if (has) - { - structure.sarAnalysis = analysis; - } - } - - // - // Analyse Based on ZigZag ... - if (config.analyseFIMAZigZagPivots) - { - // - XPivotAnalysis analysis; - has = AnalyseZigZagPivots( - analysis, // Result ... - forBar.Index(), // Bar Index ... - config.numberOfRequiredPivotsForAnalysis, // Required Number of Pivots ... - config.maxAllowedLoopbackLengthForAnalysis // Max Allowed Loopback ... - ); - if (has) - { - structure.zigzagAnalysis = analysis; - } - } - - // - // COMPLEX Actions ... - - // - // Lockup For Previous Zone ... - has = structure.isSupportTouched || - structure.isResistanceTouched; - if (has) - { - // - if (structure.isSupportTouched) - { - // - idx = GetYoungestBefore( - structure.support.from, - supports // - ); - has = IsValidIndex(idx); - if (has) - { - structure.prevZone = supports[idx]; - } - } - else if (structure.isResistanceTouched) - { - // - idx = GetYoungestBefore( - structure.resistance.from, - resistances // - ); - has = IsValidIndex(idx); - if (has) - { - structure.prevZone = resistances[idx]; - } - } - } - - // - // Detect Recently Tested Zones ... - if ((config.detectSupport || - config.detectResistance) && - config.recentlyTestedZonesMaxLookup > 0) - { - // - XOHCL iBar; - int idx = -1; - bool has = false; - - // - int start = forBar.Index() + 1; - int end = start + config.recentlyTestedZonesMaxLookup; - for (int i = start; i < end; i++) - { - // - // Initialize Indexed Bar ... - has = forBar.BarAt(i, iBar); - if (!has) - { - continue; - } - - // - // Selecting Support and Resistances ... - - // - // Supports ... - idx = GetYoungestBefore(iBar.time, supports); - has = IsValidIndex(idx); - if (has) - { - // - // Check Testing ... - has = IsTested(iBar, supports[idx]); - if (has) - { - // - AddIfNotExists( - supports[idx], - structure.recentlyTestedZones // - ); - } - } - - // - // Resistances ... - idx = GetYoungestBefore(iBar.time, resistances); - has = IsValidIndex(idx); - if (has) - { - // - // Check Testing ... - has = IsTested(iBar, resistances[idx]); - if (has) - { - // - AddIfNotExists( - resistances[idx], - structure.recentlyTestedZones // - ); - } - } - } - } - - // - // Checkup for FakeBreaked Zones ... - if (config.detectSupport || - config.detectResistance) - { - // - // Retrieve Previous Bar ... - int idx = -1; - XOHCL pForBar; - XOHCL breakerBar; - XBoxZone pSupport; - XOHCL pBreakerBar; - XBoxZone pResistance; - - // - // Selecting Previously Touched Support / Resistance ... - has = forBar.GetPreviousBar(pForBar); - if (has) - { - // - // Detecting Nearest Above Lows Support ... - idx = GetYoungestAbove( - pForBar.low, - supports // - ); - has = IsValidIndex(idx) && - IsBreaked( - forBar, - supports[idx] // - ); - if (has) - { - pSupport = supports[idx]; - } - - // - // Detecting Nearest Below Highs Resistance ... - idx = GetYoungestBelow( - pForBar.high, - resistances // - ); - has = IsValidIndex(idx) && - IsBreaked( - forBar, - resistances[idx] // - ); - if (has) - { - pResistance = resistances[idx]; - } - } - - // - // Check at least a zone Exists ... - // Selecting pTestedZone ... - has = pSupport.IsValid() || - pResistance.IsValid(); - if (has) - { - // - // Support ... - has = pSupport.IsValid(); - if (has) - { - // - structure.isPTest = true; - structure.pTestedZone = pSupport; - } - - // - // Resistance ... - has = pResistance.IsValid(); - if (has) - { - // - structure.isPTest = true; - structure.pTestedZone = pResistance; - } - } - - // - // Check pTestedZone Existance ... - has = structure.isPTest && - structure.pTestedZone.IsValid(); - if (has) - { - // - // Get Breaker Bars ... - XOHCL breakerBars[]; - int breakerBarsCount = GetBreakerBars( - structure.pTestedZone, - breakerBars // - ); - has = IsValidSize(breakerBarsCount); - if (has) - { - // - idx = GetYoungestBar(breakerBars); - has = IsValidIndex(idx); - if (has) - { - breakerBar = breakerBars[idx]; - } - } - - // - SpecifiedClean(breakerBars); - } - - // - // Check Zone Breaker Bar Exists ... - // Validate Zone Fake Breake Langth ... - has = breakerBar.IsValid(); - if (has) - { - // - // Validate Breake Length ... - has = (breakerBar.Index() - pForBar.Index()) <= config.supportAndResistanceBreakeValidationLength; - } - - // - // Cleanup Resources ... - // - if (!has) - { - // - structure.isPTest = false; - structure.pTestedZone.Clean(); - } - pForBar.Clean(); - pSupport.Clean(); - breakerBar.Clean(); - pBreakerBar.Clean(); - pResistance.Clean(); - } -} - -// -// Lockup For Previous Zone ... -has = structure.isSupportTouched || - structure.isResistanceTouched; -if (has) -{ - // - if (structure.isSupportTouched) - { - // - idx = GetYoungestBefore( - structure.support.from, - supports // - ); - has = IsValidIndex(idx); - if (has) - { - structure.prevZone = supports[idx]; - } - } - else if (structure.isResistanceTouched) - { - // - idx = GetYoungestBefore( - structure.resistance.from, - resistances // - ); - has = IsValidIndex(idx); - if (has) - { - structure.prevZone = resistances[idx]; - } - } -} diff --git a/Documents/BKP/xfima-zone-detector.bkp.mq5 b/Documents/BKP/xfima-zone-detector.bkp.mq5 deleted file mode 100644 index abc73a71..00000000 --- a/Documents/BKP/xfima-zone-detector.bkp.mq5 +++ /dev/null @@ -1,1219 +0,0 @@ - - // - // Detectors ... - - /** - * Detect Zones (Support / Resistance) based on XFIMA Validators ... - * - * @param zones: XBoxZone, reference to Collection for holding Detected Zones ... - * @param barIndex: int, Specified Start Looking Bar Index ... - * @param onlyValidZones: bool, Only Validation Zones ... - * @param requiredNumberOfZones: int, Specified how many zones looking for ... - * @param shadowMultiplier: double, a valid zone's Shadow side multiplier ... - * @param validationStrength: double, Validation Strength ... - * @param validationLength: int, Validation Length ... - * @param maxAllowedLoopbackLength: int, Specified Max Allowed Looping back trhough Bars for Detection ... - * - * @return ( int ) - */ - int DetectXFIMAZones( - XBoxZone &zones[], - int barIndex = 0, - bool onlyValidZones = false, - int requiredNumberOfZones = 50, - double shadowMultiplier = 4, - double validationStrength = 1, - int validationLength = 7, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(zones); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 3); - shadowMultiplier = NormalizeDouble(shadowMultiplier, 2); - validationStrength = NormalizeDouble(validationStrength, 1); - requiredNumberOfZones = NormalizeInt(requiredNumberOfZones, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - XOHCL bar; - bool has = IsValid() && - bar.Init( - mSymbol, - mPeriod, - barIndex + 1 // - ); - if (!has) - { - return result; - } - - // - // Define Requirements ... - XOHCL iBar; - XBoxZone iBox; - bool isBullish = false; - bool isBearish = false; - double iUpper = EMPTY_VALUE; - double iLower = EMPTY_VALUE; - double iHKUpper = EMPTY_VALUE; - double iHKLower = EMPTY_VALUE; - double iMAUpper = EMPTY_VALUE; - double iMALower = EMPTY_VALUE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Create a Loop to Detect Zones ... - int start = barIndex; - int idx = start - 1; - int end = start + maxAllowedLoopbackLength; - while (ArraySize(zones) < requiredNumberOfZones && idx < end) - { - // - idx++; - - // - // Initialize Indexed Bar ... - has = bar.BarAt(idx, iBar); - if (!has) - { - continue; - } - - // - // Reading Bars ... - iMAUpper = GetMABondUpper(idx); - iMALower = GetMABondLower(idx); - iHKUpper = GetHKBondUpper(idx); - iHKLower = GetHKBondLower(idx); - - // - iUpper = MathMax(iMAUpper, iHKUpper); - iLower = MathMin(iMALower, iHKLower); - - // - // Check Bar State ... - has = - NotEmptyZero(iUpper) && - NotEmptyZero(iLower); - if (!has) - { - continue; - } - - // - // Check Direction of Zone ... - isBullish = iBar.low < iLower; - isBearish = iBar.high > iUpper; - has = (isBullish && !isBearish) || - (isBearish && !isBullish); - if (!has) - { - continue; - } - - // - // Validate Price Based on Bar ... - // Validate Shadow Multiplier ... - has = - isBullish - ? iBar.low < bar.low - : iBar.high > bar.high; - has = - has && - (isBullish - ? iBar.GetLowShadow() > iBar.GetHighShadow() * shadowMultiplier - : iBar.GetHighShadow() > iBar.GetLowShadow() * shadowMultiplier); - if (!has) - { - continue; - } - - // - iDir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Fill Bax ... - iBox.dir = iDir; - iBox.symbol = mSymbol; - iBox.period = mPeriod; - iBox.upper = - isBullish - ? iBar.GetDown() - : iBar.high; - iBox.lower = - isBullish - ? iBar.low - : iBar.GetUp(); - iBox.type = - (isBullish ? "XFIMA_Support" : "XFIMA_Resistance") + "_" + - ToXString(NormalizePrice(iBox.upper, iBox.symbol)) + "_" + - ToXString(NormalizePrice(iBox.lower, iBox.symbol)); - - // - iBox.at = iBar.time; - iBox.to = bar.time; - - // - // Loopback to Detect From Time ... - XOHCL pBar; - datetime fromTime = NULL; - has = iBar.GetPreviousBar(pBar); - if (has) - { - // - while (!IsXValid(fromTime)) - { - // - // Check Price Inside ... - has = - isBullish - ? pBar.GetDown() < iBox.lower - : pBar.GetUp() > iBox.upper; - if (has) - { - fromTime = pBar.time; - } - - // - // Retrieve PrevBar ... - has = pBar.GetPreviousBar(pBar); - if (!has) - { - break; - } - } - } - has = IsXValid(fromTime); - if (has) - { - iBox.from = fromTime; - } - - // - // Validate Zone Length ... - has = iBox.IsValid() && - (validationStrength >= 1 - ? iBox.GetRange() >= validationStrength * GetPoints(iBox.symbol) - : true) && - (iBox.FromIndex() - iBox.AtIndex() >= validationLength); - - // - // Validate Zone State ... - if (has) - { - // - // Cleanup Bar ... - iBar.Clean(); - - // - // Loopingh through At Index ... - for (int i = iBox.ToIndex(); i < iBox.AtIndex(); i++) - { - // - // Initialized Indexed Bar ... - has = bar.BarAt(i, iBar); - if (!has) - { - break; - } - - // - // Validate Bar ... - has = - iBox.IsBullish() - ? iBar.low > iBox.lower - : iBar.high < iBox.upper; - if (!has) - { - break; - } - } - } - - // - if (has) - { - // - AddIfNotExists( - iBox, - zones // - ); - } - - // - // Cleanup Resources ... - iBar.Clean(); - pBar.Clean(); - iBox.Clean(); - } - - // - result = ArraySize(zones); - - // - // Cleanup Resources ... - if (!result) - { - XClean(zones); - } - bar.Clean(); - iBar.Clean(); - iBox.Clean(); - - // - return result; - } - - int DetecteXFIMAPivots( - XPivot &pivots[], - int barIndex = 0, - int requiredNumberOfPivots = 50, - int validationLength = 7, - int maxAllowedLoopbackLength = 1500, // - // - // PV ... - int pvValidationLength = 7, - // - // Momentum ... - int momentumBarValidationLength = 3, - double momentumBarApprovedMultiplier = 3, - // - // TrueGap ... - double trueGapApprovedStrength = 2, - // - // Pin ... - double pinBarShadowApprovedMultiplier = 3, - double pinBarRangeMultiplier = 4, - bool pinBarForceDirection = false, - // - // Flag ... - int flagPatternPullbackLength = 3 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(pivots); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - validationLength = NormalizeInt(validationLength, 1); - requiredNumberOfPivots = NormalizeInt(requiredNumberOfPivots, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - pvValidationLength = NormalizeInt(pvValidationLength, 0); - - // - momentumBarValidationLength = NormalizeInt(momentumBarValidationLength, 2); - momentumBarApprovedMultiplier = NormalizeDouble(momentumBarApprovedMultiplier, 1); - - // - trueGapApprovedStrength = NormalizeDouble(trueGapApprovedStrength, 1); - - // - pinBarRangeMultiplier = NormalizeDouble(pinBarRangeMultiplier, 4); - pinBarShadowApprovedMultiplier = NormalizeDouble(pinBarShadowApprovedMultiplier, 3); - - // - flagPatternPullbackLength = NormalizeInt(flagPatternPullbackLength, 3); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - XOHCL iBar; - XOHCL tmpBar; - XPivot iPivot; - int count = 0; - string iPrefix = NULL; - int idx = barIndex - 1; - double iMin = EMPTY_VALUE; - double iMax = EMPTY_VALUE; - double iValue = EMPTY_VALUE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - ENUM_X_DIRECTION tmpDir = X_DIRECTION_NONE; - ENUM_X_PIVOT_TYPE iType = X_PIVOT_TYPE_NONE; - int end = barIndex + maxAllowedLoopbackLength; - while ( - idx < end && - ArraySize(pivots) < requiredNumberOfPivots) - { - // - idx++; - - // - iBar.Clean(); - iPivot.Clean(); - tmpBar.Clean(); - iPrefix = NULL; - iDir = X_DIRECTION_NONE; - - // - has = iBar.Init( - mSymbol, - mPeriod, - idx // - ); - if (!has) - { - break; - } - - // - // Pivots List ... - - // - // PV ... - bool isPV = false; - bool isPeak = false; - bool isVale = false; - tmpDir = X_DIRECTION_NONE; - if (pvValidationLength > 0) - { - // - isPV = patternDetector.IsPV( - iBar, - tmpDir, - pvValidationLength // - ); - isPeak = isPV && - IsXBearish(tmpDir); - isVale = isPV && - IsXBullish(tmpDir); - if (isPV) - { - iPrefix += isPeak ? "XPK" : "XVL"; - } - - // - // Continue Loopback if PV Validation Provided and not isPV ... - if (!isPV) - { - continue; - } - } - - // - // Momentum Bar ... - bool isMomentum = patternDetector.IsMomentumBar( - iBar, - iDir, - momentumBarValidationLength, - momentumBarApprovedMultiplier // - ); - if (isMomentum) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isMomentum = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "MNTM"; - } - } - - // - // Engulf Bar ... - bool isEngulfed = patternDetector.IsEngulfedBar( - iBar, - iDir // - ); - if (isEngulfed) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isEngulfed = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "ENGLF"; - } - } - - // - // True Gap ... - bool isTrueGaped = patternDetector.IsTrueGapedBar( - iBar, - iDir, - trueGapApprovedStrength // - ); - if (isTrueGaped) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isTrueGaped = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "TG"; - } - } - - // - // Pin Bar ... - bool isPinned = patternDetector.IsPinnedBar( - iBar, - iDir, - pinBarShadowApprovedMultiplier, - pinBarRangeMultiplier, - pinBarForceDirection // - ); - if (isPinned) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isPinned = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "PND"; - } - } - - // - // Patterns ... - - // - // Star Pattern ... - bool isStarPattern = patternDetector.IsStarPattern( - iBar, - iDir // - ); - if (isStarPattern) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isStarPattern = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "STR"; - } - } - - // - // Piercing Pattern ... - bool isPiercingPattern = patternDetector.IsPiercingPattern( - iBar, - iDir // - ); - if (isPiercingPattern) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isPiercingPattern = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "PRCG"; - } - } - - // - // Rising Pattern ... - bool isRisingPattern = patternDetector.IsRisingPattern( - iBar, - iDir // - ); - if (isRisingPattern) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isRisingPattern = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "RSG"; - } - } - - // - // Flag Pattern ... - bool isFlagPattern = patternDetector.IsFlagPattern( - iBar, - iDir, - tmpBar, - flagPatternPullbackLength // - ); - if (isFlagPattern) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isFlagPattern = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "FLG"; - } - } - - // - // Signal Key Pattern ... - bool isSignalKeyPattern = patternDetector.IsSignalKeyBarPattern( - iBar, - iDir, - pinBarShadowApprovedMultiplier, - pinBarRangeMultiplier, - pinBarForceDirection // - ); - if (isSignalKeyPattern) - { - // - if (!IsXValid(tmpDir)) - { - tmpDir = iDir; - } - - // - if (iDir != tmpDir) - { - isSignalKeyPattern = false; - } - else - { - // - count++; - iPrefix += (IsXValid(iPrefix) ? "_" : "") + "SKB"; - } - } - - // - has = - isPinned || - isMomentum || - isEngulfed || - isTrueGaped || - isStarPattern || - isFlagPattern || - isRisingPattern || - isPiercingPattern || - isSignalKeyPattern; - if (!has) - { - continue; - } - - // // - // // Validate Pivot Length ... - // // Validate Pivot vs XFIMA Values ... - // for (int i = iBar.Index(); i < iBar.Index() + validationLength; i++) - // { - // // - // tmpBar.Clean(); - // has = iBar.BarAt(i, tmpBar); - // if (!has) - // { - // break; - // } - - // // - // iMin = EMPTY_VALUE; - // iMax = EMPTY_VALUE; - // has = GetBoundaryValues( - // iMin, - // iMax, - // i // - // ); - - // // - // // Validate Bar vs TmpBar and Also Boundary Values ... - // has = - // has && - // (IsXBullish(iDir) - // ? - // // tmpBar.low < iMin && - // (tmpBar.low > iBar.low || - // tmpBar.GetDown() || iBar.GetDown()) - // : - // // tmpBar.high > iMax && - // (tmpBar.high < iBar.high || - // tmpBar.GetUp() < iBar.GetUp())); - // if (!has) - // { - // break; - // } - - // // - // iValue = IsXBullish(iDir) - // ? iBar.low - // : iBar.high; - - // // - // iType = IsXBullish(iDir) - // ? X_PIVOT_TYPE_VALE - // : X_PIVOT_TYPE_PEAK; - - // // - // tmpBar.Clean(); - // } - - // - has = IsXValid(iPrefix); - if (has) - { - // - iValue = IsXBullish(iDir) - ? iBar.low - : iBar.high; - - // - iType = IsXBullish(iDir) - ? X_PIVOT_TYPE_VALE - : X_PIVOT_TYPE_PEAK; - - // - // Preparing Pivot ... - has = iPivot.Init( - iValue, - iBar.time, - iBar.symbol, - iDir, - iBar.period, - iType // - ); - if (has) - { - // - iPivot.prefix = iPrefix; - - // - AddIfNotExists( - iPivot, - pivots // - ); - } - } - - // - } - - // - // Cleanup Resources ... - iBar.Clean(); - iPivot.Clean(); - tmpBar.Clean(); - - // - result = ArraySize(pivots); - - // - return result; - } - - /** - * Detect XFIMA Based POI Bars ... - * - * @param bars: XOHCL, reference collection to holds detected bars ... - * @param dirs: ENUM_X_DIRECTION, reference collection to holds detected bars Direction ... - * @param barIndex: int, Specified Bar Index ... - * @param forDir: ENUM_X_DIRECTION, specified which Direction of potential bars looking for ... - * @param requiredNumberOfBars: int, Specified how many bars looking for ... - * @param maxAllowedLoopbackLength: int, Specified Max Allowed Looping back trhough Bars for Detection ... - * @return ( int ) - */ - int DetectXFIMAPOIBars( - XOHCL &bars[], - ENUM_X_DIRECTION &dirs[], - int barIndex = 0, - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, - int requiredNumberOfBars = 300, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(bars); - XClean(dirs); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - requiredNumberOfBars = NormalizeInt(requiredNumberOfBars, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - XOHCL iBar; - int idx = barIndex - 1; - int start = barIndex; - bool isBullish = false; - bool isBearish = false; - double iMin = EMPTY_VALUE; - double iMax = EMPTY_VALUE; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - int end = start + maxAllowedLoopbackLength; - while (ArraySize(bars) < requiredNumberOfBars || - idx < maxAllowedLoopbackLength) - { - // - idx++; - has = iBar.Init( - mSymbol, - mPeriod, - idx // - ); - if (!has) - { - continue; - } - - // - has = GetBoundaryValues( - iMin, - iMax, - idx // - ); - if (!has) - { - continue; - } - - // - isBullish = iBar.low < iMin; - isBearish = iBar.high > iMax; - has = - !HasDirection(forDir) - ? ((isBullish && !isBearish) || - (isBearish && !isBullish)) - : IsXBullish(forDir) - ? (isBullish && !isBearish) - : (isBearish && !isBullish); - if (has) - { - // - iDir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - AddRef( - iBar, - bars // - ); - - // - Add( - iDir, - dirs // - ); - } - } - - // - result = ArraySize(bars); - - // - // Cleanup Resources ... - iBar.Clean(); - - // - return result; - } - - int DetectXFIMAReversalPOIBars( - XOHCL &bars[], - ENUM_X_DIRECTION &dirs[], - int barIndex = 0, - bool forceTouchBoundary = false, - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, - int requiredNumberOfBars = 300, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(bars); - XClean(dirs); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - requiredNumberOfBars = NormalizeInt(requiredNumberOfBars, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - // Detect POI Bars ... - XOHCL decisionBars[]; - ENUM_X_DIRECTION decisionBarDirs[]; - int decisionBarsCount = DetectXFIMAPOIBars( - decisionBars, - decisionBarDirs, - barIndex, - forDir, - requiredNumberOfBars, - maxAllowedLoopbackLength // - ); - has = IsValidSize(decisionBarsCount); - if (!has) - { - // - XClean(decisionBars); - XClean(decisionBarDirs); - - // - return result; - } - - // - bool isBullish = false; - bool isBearish = false; - double iMin = EMPTY_VALUE; - double iMax = EMPTY_VALUE; - bool isCond1Bullish = false; - bool isCond1Bearish = false; - for (int i = 0; i < decisionBarsCount; i++) - { - // - // Read Boundary Values ... - has = GetBoundaryValues(iMin, iMax, i); - if (!has) - { - continue; - } - - // - // Check Bar Decision Direction ... - isBullish = IsXBullish(decisionBarDirs[i]); - isBearish = IsXBearish(decisionBarDirs[i]); - - // - // Validate ... - - // - isCond1Bullish = decisionBars[i].IsBullish(); - - // - isCond1Bearish = decisionBars[i].IsBearish(); - - // - isBullish = - isBullish && - (isCond1Bullish); - - // - isBearish = - isBearish && - (isCond1Bearish); - - // - if (forceTouchBoundary) - { - // - isBullish = - isBullish && - (decisionBars[i].high > iMin || - decisionBars[i].GetUp() > iMin); - - // - isBearish = - isBearish && - (decisionBars[i].low < iMax || - decisionBars[i].GetDown() < iMax); - } - - // - has = - isBullish || - isBearish; - if (has) - { - // - AddRef( - decisionBars[i], - bars // - ); - - // - Add( - decisionBarDirs[i], - dirs // - ); - } - } - - // - result = ArraySize(bars); - - // - // Cleanup Resources ... - XClean(decisionBars); - XClean(decisionBarDirs); - - // - return result; - } - - int DetectXFIMAContinuationalPOIBars( - XOHCL &bars[], - ENUM_X_DIRECTION &dirs[], - int barIndex = 0, - bool forceTouchBoundary = false, - ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, - int requiredNumberOfBars = 300, - int maxAllowedLoopbackLength = 1500 // - ) - { - // - int result = 0; - - // - // Prepare ... - XClean(bars); - XClean(dirs); - - // - // Normalize ... - barIndex = NormalizeBarIndex(barIndex); - requiredNumberOfBars = NormalizeInt(requiredNumberOfBars, 5); - maxAllowedLoopbackLength = NormalizeInt(maxAllowedLoopbackLength, 50); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - // Detect POI Bars ... - XOHCL decisionBars[]; - ENUM_X_DIRECTION decisionBarDirs[]; - int decisionBarsCount = DetectXFIMAPOIBars( - decisionBars, - decisionBarDirs, - barIndex, - forDir, - requiredNumberOfBars, - maxAllowedLoopbackLength // - ); - has = IsValidSize(decisionBarsCount); - if (!has) - { - // - XClean(decisionBars); - XClean(decisionBarDirs); - - // - return result; - } - - // - bool isBullish = false; - bool isBearish = false; - double iMin = EMPTY_VALUE; - double iMax = EMPTY_VALUE; - bool isCond1Bullish = false; - bool isCond1Bearish = false; - for (int i = 0; i < decisionBarsCount; i++) - { - // - // Read Indexed Bars Boundaries ... - has = GetBoundaryValues(iMin, iMax, decisionBars[i].Index()); - if (!has) - { - continue; - } - - // - // Make Direction Opposit ... - decisionBarDirs[i] = Opposit(decisionBarDirs[i]); - - // - isBullish = IsXBullish(decisionBarDirs[i]); - isBearish = IsXBearish(decisionBarDirs[i]); - - // - // Check Bar Validations ... - - // - // Cond 1 ... - - // - isCond1Bullish = - decisionBars[i].IsBearish() && - (decisionBars[i].low >= iMax || - (decisionBars[i].low <= iMax && - decisionBars[i].GetUp() >= iMax)); - - // - isCond1Bearish = - decisionBars[i].IsBullish() && - (decisionBars[i].high <= iMin || - (decisionBars[i].high >= iMin && - decisionBars[i].GetDown() <= iMin)); - - // - isBullish = - isBullish && - (isCond1Bullish); - - // - isBearish = - isBearish && - (isCond1Bearish); - - // - if (forceTouchBoundary) - { - // - isBullish = - isBullish && - (decisionBars[i].low >= iMax || - (decisionBars[i].low <= iMax && - decisionBars[i].GetUp() >= iMax)); - - // - isBearish = - isBearish && - (decisionBars[i].high <= iMin || - (decisionBars[i].high >= iMin && - decisionBars[i].GetDown() <= iMin)); - } - - // - has = - isBullish || - isBearish; - if (has) - { - // - AddRef( - decisionBars[i], - bars // - ); - - // - Add( - decisionBarDirs[i], - dirs // - ); - } - } - - // - result = MathMin(ArraySize(bars), ArraySize(dirs)); - - // - // Cleanup Resources ... - XClean(decisionBars); - XClean(decisionBarDirs); - - // - return result; - } diff --git a/Documents/BKP/xfima.ind.tmp.mq5 b/Documents/BKP/xfima.ind.tmp.mq5 deleted file mode 100644 index f83b06de..00000000 --- a/Documents/BKP/xfima.ind.tmp.mq5 +++ /dev/null @@ -1,2648 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XFIMA -// Description: Integrates All Requirements inside -// this indicator for analyse Markets Based on OM1 ... -// -// -// 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 XFIMA Indicator" -#property icon "../Images/SaherElm_Logo_Color.ico" -#property strict - -// -// Definitions ... - -// -// Definitions ... -enum ENUM_X_ZG_SEARCH_MODE -{ - X_ZG_SEARCH_EXTREMUM = 0, // searching for the first extremum - X_ZG_SEARCH_PEAK = 1, // searching for the next ZigZag peak - X_ZG_SEARCH_VALE = -1 // searching for the next ZigZag vale -}; - -// -#define ShortName "XFIMA" - -// -// Imports ... -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Calculation"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// PV ... -input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method - -// -// Others ... -input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_236; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Upper Zone Level -input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_764; // Lower Zone Level -input double sarStep = 0.02; // SAR Step -input double sarMax = 0.2; // SAR Maximum -input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To -input int maFastLength = 7; // Fast MA Length -input int maSlowLength = 21; // Slow MA Length -input int maBondLength = 21; // MA Bond Length -input int zigzagDepth = 12; // ZigZag Depth -input int zigzagDeviation = 5; // ZigZag Deviation -input int zigzagBackStep = 3; // ZigZag Back Step -input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode -input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode -input bool hkIgnoreShadows = true; // HK Remove noises -input int hkSmoothingLength = 21; // HK Smoothing Length -input ENUM_X_MA_METHOD hkSmoothingMode = X_MA_MODE_EMA; // HK Smoothing Method - -// -// Presentation ... -input group "Presentation"; -input bool showPV = true; // Show PV -input bool showHK = true; // Show HK -input bool showSAR = true; // Show Sar -input bool showMAFast = true; // Show MA Fast -input bool showMASlow = true; // Show MA Slow -input bool showMABond = true; // Show MA Bond -input bool showHKBond = true; // Show HK Bond -input bool showZigZag = true; // Show ZigZag -input bool showFiboZone = true; // Show Fibo Zone - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -input int sarArrowCode = 159; // Parabolic Sar Arrow Code -input int peakArrowCode = 159; // Peaks Arrow Code -input int valeArrowCode = 159; // Vales Arrow Code - -// -// Non Inputs ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 44 -#property indicator_plots 16 - -// -// Plot Buffers ... - -// -// Fast MA ... - -// -#define maFastBufferIndex 0 -#define maFastBufferPlotIndex 0 -double maFastBuffer[]; - -// -#define maFastColorBufferIndex 1 -double maFastColorBuffer[]; - -// -#property indicator_label1 "FastMA" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrLime, clrLime, clrLime // clrYellow, clrOrangeRed, clrGray -#property indicator_width1 3 - -// -// Slow MA ... - -// -#define maSlowBufferIndex 2 -#define maSlowBufferPlotIndex 1 -double maSlowBuffer[]; - -// -#define maSlowColorBufferIndex 3 -double maSlowColorBuffer[]; - -// -#property indicator_label2 "SlowMA" -#property indicator_type2 DRAW_COLOR_LINE -#property indicator_color2 CLR_NONE, clrRed, clrRed, clrRed // clrLime, clrRed, clrGray -#property indicator_width2 3 - -// -// SAR ... - -// -#define sarBufferIndex 4 -#define sarBufferPlotIndex 2 -double sarBuffer[]; - -// -#define sarColorBufferIndex 5 -double sarColorBuffer[]; - -// -#property indicator_label3 "SAR" -#property indicator_type3 DRAW_COLOR_ARROW -#property indicator_color3 CLR_NONE, clrLime, clrRed, clrGray -#property indicator_width3 2 - -// -// PEAKS ... - -// -#define peakBufferIndex 6 -#define peakBufferPlotIndex 3 -double peakBuffer[]; - -// -#property indicator_label4 "PEAK" -#property indicator_type4 DRAW_ARROW -#property indicator_color4 clrMagenta -#property indicator_width4 3 - -// -// VALES ... - -// -#define valeBufferIndex 7 -#define valeBufferPlotIndex 4 -double valeBuffer[]; - -// -#property indicator_label5 "VALE" -#property indicator_type5 DRAW_ARROW -#property indicator_color5 clrAqua -#property indicator_width5 3 - -// -// FIBO Upper ... - -// -#define fiboUpperBufferIndex 8 -#define fiboUpperBufferPlotIndex 5 -double fiboUpperBuffer[]; - -// -#property indicator_label6 "FIBUP" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrAqua -#property indicator_width6 2 - -// -// FIBO Middle ... - -// -#define fiboMiddleBufferIndex 9 -#define fiboMiddleBufferPlotIndex 6 -double fiboMiddleBuffer[]; - -// -#property indicator_label7 "FIBMID" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrBrown -#property indicator_width7 2 - -// -// FIBO Lower ... - -// -#define fiboLowerBufferIndex 10 -#define fiboLowerBufferPlotIndex 7 -double fiboLowerBuffer[]; - -// -#property indicator_label8 "FIBLO" -#property indicator_type8 DRAW_LINE -#property indicator_color8 clrMagenta -#property indicator_width8 2 - -// -// ZigZag ... - -// -#define zigzagBufferIndex 11 -#define zigzagBufferPlotIndex 8 -double zigzagBuffer[]; - -// -#property indicator_label9 "XZG" -#property indicator_type9 DRAW_SECTION -#property indicator_color9 clrYellow -#property indicator_width9 2 - -// -// MA Upper ... - -// -#define maUpperBufferIndex 12 -#define maUpperBufferPlotIndex 9 -double maUpperBuffer[]; - -// -#property indicator_label10 "UpperMA" -#property indicator_type10 DRAW_LINE -#property indicator_color10 clrLime -#property indicator_width10 3 - -// -// MA Lower ... - -// -#define maLowerBufferIndex 13 -#define maLowerBufferPlotIndex 10 -double maLowerBuffer[]; - -// -#property indicator_label11 "LowerMA" -#property indicator_type11 DRAW_LINE -#property indicator_color11 clrRed -#property indicator_width11 3 - -// -// XHK ... - -// -#define hkOpenBufferIndex 14 -double hkOpenBuffer[]; - -// -#define hkHighBufferIndex 15 -double hkHighBuffer[]; - -// -#define hkLowBufferIndex 16 -double hkLowBuffer[]; - -// -#define hkCloseBufferIndex 17 -double hkCloseBuffer[]; - -// -#define hkColorBufferIndex 18 -double hkColorBuffer[]; - -// -#define hkBufferPlotIndex 11 -#property indicator_label12 "XHK Open;XHK High;XHK Low;XHK Close" -#property indicator_type12 DRAW_COLOR_CANDLES -#property indicator_color12 CLR_NONE, clrAqua, clrMagenta, clrGray - -// -#define hkBondUpperBufferIndex 19 -double hkBondUpperBuffer[]; - -// -#define hkBondUpperBufferPlotIndex 12 -#property indicator_label13 "UpperHK" -#property indicator_type13 DRAW_LINE -#property indicator_color13 clrAqua -#property indicator_width13 3 - -// -#define hkBondLowerBufferIndex 20 -double hkBondLowerBuffer[]; - -// -#define hkBondLowerBufferPlotIndex 13 -#property indicator_label14 "LowerHK" -#property indicator_type14 DRAW_LINE -#property indicator_color14 clrMagenta -#property indicator_width14 3 - -// -// XPB ... - -// -#define pbUpperBufferIndex 21 -double pbUpperBuffer[]; - -// -#define pbUpperBufferPlotIndex 14 -#property indicator_label15 "UpperPB" -#property indicator_type15 DRAW_LINE -#property indicator_color15 clrAqua -#property indicator_width15 3 - -// -#define pbLowerBufferIndex 22 -double pbLowerBuffer[]; - -// -#define pbLowerBufferPlotIndex 15 -#property indicator_label16 "LowerPB" -#property indicator_type16 DRAW_LINE -#property indicator_color16 clrMagenta -#property indicator_width16 3 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 22 - -// -// MA ... - -// -#define maFastStateBufferIndex mLastBufferIndex + 1 -double maFastStateBuffer[]; - -// -#define maSlowStateBufferIndex mLastBufferIndex + 2 -double maSlowStateBuffer[]; - -// -// SAR ... - -// -#define sarStateBufferIndex mLastBufferIndex + 3 -double sarStateBuffer[]; - -// -// CYCLES ... - -// -// SC ... - -// -#define sHHBufferIndex mLastBufferIndex + 4 -double sHHBuffer[]; - -// -#define sLLBufferIndex mLastBufferIndex + 5 -double sLLBuffer[]; - -// -// MC ... - -// -#define mHHBufferIndex mLastBufferIndex + 6 -double mHHBuffer[]; - -// -#define mLLBufferIndex mLastBufferIndex + 7 -double mLLBuffer[]; - -// -// LC ... - -// -#define lHHBufferIndex mLastBufferIndex + 8 -double lHHBuffer[]; - -// -#define lLLBufferIndex mLastBufferIndex + 9 -double lLLBuffer[]; - -// -// HC ... - -// -#define hHHBufferIndex mLastBufferIndex + 10 -double hHHBuffer[]; - -// -#define hLLBufferIndex mLastBufferIndex + 11 -double hLLBuffer[]; - -// -// ZigZag ... - -// -#define highsBufferIndex mLastBufferIndex + 12 -double highsBuffer[]; - -// -#define highsTimeBufferIndex mLastBufferIndex + 13 -double highsTimeBuffer[]; - -// -#define lowsBufferIndex mLastBufferIndex + 14 -double lowsBuffer[]; - -// -#define lowsTimeBufferIndex mLastBufferIndex + 15 -double lowsTimeBuffer[]; - -// -// XHK Data ... - -// -#define hkRawHighBufferIndex mLastBufferIndex + 16 -double hkRawHighBuffer[]; - -// -#define hkRawOpenBufferIndex mLastBufferIndex + 17 -double hkRawOpenBuffer[]; - -// -#define hkRawLowBufferIndex mLastBufferIndex + 18 -double hkRawLowBuffer[]; - -// -#define hkRawCloseBufferIndex mLastBufferIndex + 19 -double hkRawCloseBuffer[]; - -// -// XPB ... - -// -#define pbRawUpperBufferIndex mLastBufferIndex + 20 -double pbRawUpperBuffer[]; - -// -#define pbRawLowerBufferIndex mLastBufferIndex + 21 -double pbRawLowerBuffer[]; - -// -// Variables, Properties and etc ... - -// -// XMarketCycle sc; -int mSCLength = 0; -ENUM_TIMEFRAMES mSCPeriod = NULL; - -// -// XMarketCycle mc; -int mMCLength = 0; -ENUM_TIMEFRAMES mMCPeriod = NULL; - -// -// XMarketCycle lc; -int mLCLength = 0; -ENUM_TIMEFRAMES mLCPeriod = NULL; - -// -// XMarketCycle hc; -int mHCLength = 0; -ENUM_TIMEFRAMES mHCPeriod = NULL; - -// -int sarHandler = INVALID_HANDLE; -int maFastHandler = INVALID_HANDLE; -int maSlowHandler = INVALID_HANDLE; -int maUpperHandler = INVALID_HANDLE; -int maLowerHandler = INVALID_HANDLE; - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -// Requirements ... -CArrayObj mObjects; -XCPOIDrawer *mDrawer; - -// -double zigzagUppers[]; -double zigzagLowers[]; -int zigzagLowersCount = 0; -int zigzagUppersCount = 0; -int zigzagRecalc = 3; // Number of last extremes for recalculation - -// -double lastZigZagPeak = 0; -datetime lastZigZagPeakTime = NULL; - -// -double lastZigZagVale = 0; -datetime lastZigZagValeTime = NULL; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - has = InitCycles(); - if (!has) - { - return INIT_FAILED; - } - - // - // 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 ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - has = InitRequirements(); - if (!has) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -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 mDrawer; - ZeroMemory(mDrawer); - - // - mObjects.Clear(); - - // - // De Initialize all Handlers and etc ... - IndicatorRelease(sarHandler); - IndicatorRelease(maFastHandler); - IndicatorRelease(maSlowHandler); - IndicatorRelease(maUpperHandler); - IndicatorRelease(maLowerHandler); -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Do ZigZag Calculations Before ArraySet As Series ... - int calculatedZigZags = CalculateZigZag( - 0, - prev_calculated, - rates_total, - open, - high, - close, - low, - tick_volume // - ); - if (calculatedZigZags != rates_total) - { - return prev_calculated; - } - - // - // 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); - - // - // Validate Calculated Bars ... - - // - // MA ... - int maFastCalculatedBars = BarsCalculated(maFastHandler); - int maSlowCalculatedBars = BarsCalculated(maSlowHandler); - int maUpperCalculatedBars = BarsCalculated(maUpperHandler); - int maLowerCalculatedBars = BarsCalculated(maLowerHandler); - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // MA ... - maFastCalculatedBars >= maxLength && - maSlowCalculatedBars >= maxLength && - maUpperCalculatedBars >= maxLength && - maLowerCalculatedBars >= maxLength && - // - // SAR ... - sarCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // MA ... - int copiedMAFasts = CopyBuffer(maFastHandler, MAIN_LINE, 0, limit, maFastBuffer); - int copiedMASlows = CopyBuffer(maSlowHandler, MAIN_LINE, 0, limit, maSlowBuffer); - int copiedMAUppers = CopyBuffer(maUpperHandler, MAIN_LINE, 0, limit, maUpperBuffer); - int copiedMALowers = CopyBuffer(maLowerHandler, MAIN_LINE, 0, limit, maLowerBuffer); - - // - // SAR ... - int copiedSARs = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // MA ... - copiedMAFasts >= limit && - copiedMASlows >= limit && - copiedMAUppers >= limit && - copiedMALowers >= limit && - // - // SAR ... - copiedSARs >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - // MA ... - maFastLength >= 2 && - maSlowLength >= 2 && - maBondLength >= 2 && - maSlowLength > maFastLength && - // - // SAR ... - sarMax > 0 && - sarStep > 0 && - sarMax > sarStep && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) && - // - // ZIGZAG ... - zigzagDepth > 0 && - zigzagDeviation > 0 && - zigzagBackStep > 0 && - // - // Validate Upper Mode Detection ... - IsXValid(zigzagUppersMode) && - // - // Validate Lower Mode Detection ... - IsXValid(zigzagLowersMode) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(mSCLength, mMCLength); - result = MathMax(result, mLCLength); - result = MathMax(result, mHCLength); - result = MathMax(result, maFastLength); - result = MathMax(result, maSlowLength); - result = MathMax(result, maBondLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Fast MA ... - - // - ArraySetAsSeries(maFastBuffer, true); - SetIndexBuffer(maFastBufferIndex, maFastBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maFastBufferPlotIndex, PLOT_SHOW_DATA, showMAFast); - PlotIndexSetDouble(maFastBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(maFastColorBuffer, true); - SetIndexBuffer(maFastColorBufferIndex, maFastColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(maFastStateBuffer, true); - SetIndexBuffer(maFastStateBufferIndex, maFastStateBuffer, INDICATOR_CALCULATIONS); - - // - // Slow MA ... - - // - ArraySetAsSeries(maSlowBuffer, true); - SetIndexBuffer(maSlowBufferIndex, maSlowBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(maSlowBufferPlotIndex, PLOT_SHOW_DATA, showMASlow); - PlotIndexSetDouble(maSlowBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(maSlowColorBuffer, true); - SetIndexBuffer(maSlowColorBufferIndex, maSlowColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(maSlowStateBuffer, true); - SetIndexBuffer(maSlowStateBufferIndex, maSlowStateBuffer, INDICATOR_CALCULATIONS); - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSAR); - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - // PEAK / VALE ... - - // - ENUM_DRAW_TYPE pvDrawType = showPV ? DRAW_ARROW : DRAW_NONE; - - // - // PEAK ... - - // - ArraySetAsSeries(peakBuffer, true); - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ArraySetAsSeries(valeBuffer, true); - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // FIBO Zone ... - - // - ENUM_DRAW_TYPE fiboZoneDrawType = showFiboZone ? DRAW_LINE : DRAW_NONE; - - // - // Upper ... - ArraySetAsSeries(fiboUpperBuffer, true); - SetIndexBuffer(fiboUpperBufferIndex, fiboUpperBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboUpperBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboUpperBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboUpperBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // Middle ... - ArraySetAsSeries(fiboMiddleBuffer, true); - SetIndexBuffer(fiboMiddleBufferIndex, fiboMiddleBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboMiddleBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboMiddleBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboMiddleBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // Lower ... - ArraySetAsSeries(fiboLowerBuffer, true); - SetIndexBuffer(fiboLowerBufferIndex, fiboLowerBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(fiboLowerBufferPlotIndex, PLOT_SHOW_DATA, showFiboZone); - PlotIndexSetInteger(fiboLowerBufferPlotIndex, PLOT_DRAW_TYPE, fiboZoneDrawType); - PlotIndexSetDouble(fiboLowerBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // ZigZag ... - - // - ENUM_DRAW_TYPE zigzagDrawType = showZigZag ? DRAW_SECTION : DRAW_NONE; - - // - SetIndexBuffer(zigzagBufferIndex, zigzagBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_SHOW_DATA, showZigZag); - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_TYPE, zigzagDrawType); - - PlotIndexSetInteger(zigzagBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(zigzagBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // MA Bond ... - - // - ENUM_DRAW_TYPE maBondDrawType = showMABond ? DRAW_LINE : DRAW_NONE; - - // - // MA Upper Bond ... - - // - ArraySetAsSeries(maUpperBuffer, true); - SetIndexBuffer(maUpperBufferIndex, maUpperBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_SHOW_DATA, showMABond); - // PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_DRAW_TYPE, maBondDrawType); - - // PlotIndexSetInteger(maUpperBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(maUpperBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // MA Lower Bond ... - - // - ArraySetAsSeries(maLowerBuffer, true); - SetIndexBuffer(maLowerBufferIndex, maLowerBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_SHOW_DATA, showMABond); - // PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_DRAW_TYPE, maBondDrawType); - - // PlotIndexSetInteger(maLowerBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(maLowerBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // XHK ... - - // - // XHK Color ... - ArraySetAsSeries(hkColorBuffer, true); - SetIndexBuffer(hkColorBufferIndex, hkColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(hkBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(hkBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(hkOpenBuffer, true); - SetIndexBuffer(hkOpenBufferIndex, hkOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(hkHighBuffer, true); - SetIndexBuffer(hkHighBufferIndex, hkHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(hkLowBuffer, true); - SetIndexBuffer(hkLowBufferIndex, hkLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(hkCloseBuffer, true); - SetIndexBuffer(hkCloseBufferIndex, hkCloseBuffer, INDICATOR_DATA); - - // - // XHK Bond ... - - // - ENUM_DRAW_TYPE hkBondDrawType = showHKBond ? DRAW_LINE : DRAW_NONE; - - // - // Upper ... - ArraySetAsSeries(hkBondUpperBuffer, true); - SetIndexBuffer(hkBondUpperBufferIndex, hkBondUpperBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(hkBondUpperBufferPlotIndex, PLOT_SHOW_DATA, showHKBond); - // PlotIndexSetInteger(hkBondUpperBufferPlotIndex, PLOT_DRAW_TYPE, hkBondDrawType); - - // PlotIndexSetInteger(hkBondUpperBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(hkBondUpperBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // Lower ... - ArraySetAsSeries(hkBondLowerBuffer, true); - SetIndexBuffer(hkBondLowerBufferPlotIndex, hkBondLowerBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(hkBondLowerBufferPlotIndex, PLOT_SHOW_DATA, showHKBond); - // PlotIndexSetInteger(hkBondLowerBufferPlotIndex, PLOT_DRAW_TYPE, hkBondDrawType); - - // PlotIndexSetInteger(hkBondLowerBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(hkBondLowerBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // XPB Bond ... - - // - // Upper ... - ArraySetAsSeries(pbUpperBuffer, true); - SetIndexBuffer(pbUpperBufferIndex, pbUpperBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(pbUpperBufferIndex, PLOT_SHOW_DATA, showMABond); - // PlotIndexSetInteger(pbUpperBufferIndex, PLOT_DRAW_TYPE, maBondDrawType); - - // PlotIndexSetInteger(pbUpperBufferIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(pbUpperBufferIndex, PLOT_EMPTY_VALUE, 0); - - // - // Lower ... - ArraySetAsSeries(pbLowerBuffer, true); - SetIndexBuffer(pbLowerBufferIndex, pbLowerBuffer, INDICATOR_DATA); - - // // - // PlotIndexSetInteger(pbLowerBufferIndex, PLOT_SHOW_DATA, showMABond); - // PlotIndexSetInteger(pbLowerBufferIndex, PLOT_DRAW_TYPE, maBondDrawType); - - // PlotIndexSetInteger(pbLowerBufferIndex, PLOT_DRAW_BEGIN, 0); - // PlotIndexSetDouble(pbLowerBufferIndex, PLOT_EMPTY_VALUE, 0); - - // - // Data Buffers ... - - // - // CYCLES ... - - // - // SC ... - - // - ArraySetAsSeries(sHHBuffer, true); - SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(sLLBuffer, true); - SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_CALCULATIONS); - - // - // MC ... - - // - ArraySetAsSeries(mHHBuffer, true); - SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(mLLBuffer, true); - SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_CALCULATIONS); - - // - // LC ... - - // - ArraySetAsSeries(lHHBuffer, true); - SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(lLLBuffer, true); - SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_CALCULATIONS); - - // - // HC ... - - // - ArraySetAsSeries(hHHBuffer, true); - SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(hLLBuffer, true); - SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_CALCULATIONS); - - // - // Highs ... - SetIndexBuffer(highsBufferIndex, highsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(highsTimeBufferIndex, highsTimeBuffer, INDICATOR_CALCULATIONS); - - // - // Lows ... - SetIndexBuffer(lowsBufferIndex, lowsBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(lowsTimeBufferIndex, lowsTimeBuffer, INDICATOR_CALCULATIONS); - - // - // XHK Data ... - - // - ArraySetAsSeries(hkRawHighBuffer, true); - SetIndexBuffer(hkRawHighBufferIndex, hkRawHighBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(hkRawOpenBuffer, true); - SetIndexBuffer(hkRawOpenBufferIndex, hkRawOpenBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(hkRawLowBuffer, true); - SetIndexBuffer(hkRawLowBufferIndex, hkRawLowBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(hkRawCloseBuffer, true); - SetIndexBuffer(hkRawCloseBufferIndex, hkRawCloseBuffer, INDICATOR_CALCULATIONS); - - // - // XPB Bond ... - - // - // Upper ... - ArraySetAsSeries(pbRawUpperBuffer, true); - SetIndexBuffer(pbRawUpperBufferIndex, pbRawUpperBuffer, INDICATOR_CALCULATIONS); - - // - // Lower ... - ArraySetAsSeries(pbRawLowerBuffer, true); - SetIndexBuffer(pbRawLowerBufferIndex, pbRawLowerBuffer, INDICATOR_CALCULATIONS); - - // -} - -/** - * Initial Market Cycles ... - * - * @return ( bool ) - */ -bool InitCycles() -{ - // - bool result = false; - - // - int cPeriodSeconds = PeriodSeconds(_Period); - - // - // Find Cycle Period ... - if (scMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mSCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_SHORT, - _Period // - ); - } - else - { - mSCPeriod = scPeriod; - } - - // - if (IsValid(mSCPeriod)) - { - mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (mcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mMCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_MEDIUM, - _Period // - ); - } - else - { - mMCPeriod = mcPeriod; - } - - // - if (IsValid(mMCPeriod)) - { - mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (lcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mLCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_LONG, - _Period // - ); - } - else - { - mLCPeriod = lcPeriod; - } - - // - if (IsValid(mLCPeriod)) - { - mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (hcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mHCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mHCPeriod = hcPeriod; - } - - // - if (IsValid(mHCPeriod)) - { - mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; - } - - // - result = mSCLength > 0 && - mMCLength > mSCLength && - mLCLength > mMCLength && - mHCLength > mLCLength; - - // - return result; -} - -/** - * Initial all Indicator Requirements ... - * - * @return ( false ) - * - */ -bool InitRequirements() -{ - // - bool result = false; - - // - // Handlers ... - - // - // Fast MA ... - maFastHandler = iMA( - _Symbol, - _Period, - maFastLength, - 0, - maMethod, - maAppliedTo // - ); - result = maFastHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // Slow MA ... - maSlowHandler = iMA( - _Symbol, - _Period, - maSlowLength, - 0, - maMethod, - maAppliedTo // - ); - result = maSlowHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // MA Bond Upper ... - maUpperHandler = iMA( - _Symbol, - _Period, - maBondLength, - 0, - maMethod, - PRICE_HIGH // - ); - result = maUpperHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // MA Bond Lower ... - maLowerHandler = iMA( - _Symbol, - _Period, - maBondLength, - 0, - maMethod, - PRICE_LOW // - ); - result = maLowerHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - result = sarHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - mDrawer = new XCPOIDrawer(); - - // - return result; -} - -/** - * Calculate Custom Buffers ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Calculate Bars Limit and First Bar Index ... - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - if (barsLimit == 0) - { - // - barsLimit = ratesTotal; - firstBarIndex = barsLimit - 1; - } - else - { - firstBarIndex = startCalculationForLastBars; - } - - // - // bool canCalculate = true; - bool canCalculate = - barIndex <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(barIndex); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - // TODO: Fill Buffers as Empty ... -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Common Requirements ... - - // - // CYCLES Ranges ... - CalculateCycleRanges( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // PV ... - CalculatePV( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // XHK ... - CalculateHKBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Fast MA ... - double iFastMa = maFastBuffer[barIndex]; - double maFastState = close[barIndex] > iFastMa - ? bullishState - : close[barIndex] < iFastMa - ? bearishState - : neuturalState; - double maFastColor = close[barIndex] > iFastMa - ? bullishColorIDX - : close[barIndex] < iFastMa - ? bearishColorIDX - : neuturalColorIDX; - maFastStateBuffer[barIndex] = maFastState; - maFastColorBuffer[barIndex] = showMAFast - ? maFastColor - : hideColorIDX; - - // - // Slow MA ... - double iSlowMa = maSlowBuffer[barIndex]; - double maSlowState = close[barIndex] > iSlowMa - ? bullishState - : close[barIndex] < iSlowMa - ? bearishState - : neuturalState; - double maSlowColor = close[barIndex] > iSlowMa - ? bullishColorIDX - : close[barIndex] < iSlowMa - ? bearishColorIDX - : neuturalColorIDX; - maSlowStateBuffer[barIndex] = maSlowState; - maSlowColorBuffer[barIndex] = showMASlow - ? maSlowColor - : hideColorIDX; - - // // - // double iPBUpper = MathMax(open[barIndex], close[barIndex]); - // double iPBLower = MathMin(open[barIndex], close[barIndex]); - - // // - // pbRawUpperBuffer[barIndex] = iPBUpper; - // pbRawLowerBuffer[barIndex] = iPBLower; - - // // - // // Upper ... - // iMAOnBuffer( - // ratesTotal, - // prevCalculated, - // barIndex, - // maBondLength, - // pbRawUpperBuffer, - // pbUpperBuffer, - // ToXMaMethod(maMethod) // - // ); - - // // - // // Lower ... - // iMAOnBuffer( - // ratesTotal, - // prevCalculated, - // barIndex, - // maBondLength, - // pbRawLowerBuffer, - // pbLowerBuffer, - // ToXMaMethod(maMethod) // - // ); - - // - // SAR ... - double iSar = sarBuffer[barIndex]; - double sarState = low[barIndex] > iSar - ? bullishState - : high[barIndex] < iSar - ? bearishState - : neuturalState; - double sarColor = low[barIndex] > iSar - ? bullishColorIDX - : high[barIndex] < iSar - ? bearishColorIDX - : neuturalColorIDX; - sarStateBuffer[barIndex] = sarState; - sarColorBuffer[barIndex] = showSAR - ? sarColor - : hideColorIDX; - - // - // FIBO Zone ... - - // - double iPeak = peakBuffer[barIndex]; - double iVale = valeBuffer[barIndex]; - - // - double iFiboUp = GetFibonacciLevel( - iPeak, - iVale, - fiboUpperZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - double iFiboMid = GetFibonacciLevel( - iPeak, - iVale, - fiboMiddleZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - double iFiboLo = GetFibonacciLevel( - iPeak, - iVale, - fiboLowerZoneLevel, - X_DIRECTION_BULLISH // - ); - - // - fiboUpperBuffer[barIndex] = iFiboUp; - fiboMiddleBuffer[barIndex] = iFiboMid; - fiboLowerBuffer[barIndex] = iFiboLo; -} - -// -void CalculatePV( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iSHH = sHHBuffer[barIndex]; - double iSLL = sLLBuffer[barIndex]; - - // - double iMHH = mHHBuffer[barIndex]; - double iMLL = mLLBuffer[barIndex]; - - // - double iLHH = lHHBuffer[barIndex]; - double iLLL = lLLBuffer[barIndex]; - - // - double iHHH = hHHBuffer[barIndex]; - double iHLL = hLLBuffer[barIndex]; - - // - // Calculate VALE ... - bool isVale = iSLL == iMLL && - iMLL == iLLL && - iLLL == iHLL; - double iPVale = - isFirstBar - ? emptyValue - : valeBuffer[lastBarIndex]; - double iVale = - isVale - ? iSLL - : iPVale; - valeBuffer[barIndex] = iVale; - - // - // Calculate PEAK ... - bool isPeak = iSHH == iMHH && - iMHH == iLHH && - iLHH == iHHH; - double iPPeak = - isFirstBar - ? emptyValue - : peakBuffer[lastBarIndex]; - double iPeak = - isPeak - ? iSHH - : iPPeak; - peakBuffer[barIndex] = iPeak; -} - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - * - * @return ( int ) - */ -int CalculateZigZag( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int result = 0; - - // - // Define Variables ... - int i = 0; - - // - int start = 0; - int extreme_counter = 0; - int extreme_search = X_ZG_SEARCH_EXTREMUM; - int shift = 0; - int back = 0; - int last_high_pos = 0; - int last_low_pos = 0; - - // - double val = 0; - double res = 0; - double curlow = 0; - double curhigh = 0; - double last_high = 0; - double last_low = 0; - - // - // Initializing ... - if (prevCalculated == 0) - { - // - ArrayInitialize(lowsBuffer, 0); - ArrayInitialize(highsBuffer, 0); - ArrayInitialize(zigzagBuffer, 0); - ArrayInitialize(lowsTimeBuffer, 0); - ArrayInitialize(highsTimeBuffer, 0); - - // - start = zigzagDepth; - } - - // - // Preparing ZigZag Calculation High and Lows ... - - // - if (zigzagLowersCount != zigzagUppersCount || zigzagLowersCount != ratesTotal) - { - // - // Filling Upper ... - zigzagUppersCount = FillPrice( - zigzagUppersMode, - zigzagUppers, - open, - high, - close, - low // - ); - - // - // Filling Lower ... - zigzagLowersCount = FillPrice( - zigzagLowersMode, - zigzagLowers, - open, - high, - close, - low // - ); - } - - // - // Already Calculated Before ... - if (prevCalculated > 0) - { - // - i = ratesTotal - 1; - - // - // Searching for the third X_ZG_SEARCH_EXTREMUM from the last UnComplete Bar ... - while (extreme_counter < zigzagRecalc && i > ratesTotal - 100) - { - // - res = zigzagBuffer[i]; - if (res != 0) - { - extreme_counter++; - } - - // - i--; - } - - // - i++; - start = i; - - // - // What type of X_ZG_SEARCH_EXTREMUM we Search for ... - if (lowsBuffer[i] != 0) - { - // - curlow = lowsBuffer[i]; - extreme_search = X_ZG_SEARCH_PEAK; - } - else - { - // - curhigh = highsBuffer[i]; - extreme_search = X_ZG_SEARCH_VALE; - } - - // - // Clear Values ... - for (i = start + 1; i < ratesTotal && !IsStopped(); i++) - { - // - lowsBuffer[i] = 0; - highsBuffer[i] = 0; - zigzagBuffer[i] = 0; - lowsTimeBuffer[i] = 0; - highsTimeBuffer[i] = 0; - } - } - - // - // Search for High and Low Extremes ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - // Low ... - val = zigzagLowers[Lowest(zigzagLowers, zigzagDepth, shift)]; - if (val == last_low) - { - val = 0; - } - else - { - // - last_low = val; - - // - if ((zigzagLowers[shift] - val) > zigzagDeviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= zigzagBackStep; back++) - { - // - res = lowsBuffer[shift - back]; - if ((res != 0) && (res > val)) - { - // - lowsBuffer[shift - back] = 0; - lowsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagLowers[shift] == val) - { - // - lowsBuffer[shift] = val; - lowsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - // - lowsBuffer[shift] = 0; - lowsTimeBuffer[shift] = 0; - } - - // - // High ... - val = zigzagUppers[Highest(zigzagUppers, zigzagDepth, shift)]; - if (val == last_high) - { - val = 0; - } - else - { - // - last_high = val; - - // - if ((val - zigzagUppers[shift]) > zigzagDeviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= zigzagBackStep; back++) - { - // - res = highsBuffer[shift - back]; - if ((res != 0) && (res < val)) - { - // - highsBuffer[shift - back] = 0; - highsTimeBuffer[shift - back] = 0; - } - } - } - } - - // - if (zigzagUppers[shift] == val) - { - // - highsBuffer[shift] = val; - highsTimeBuffer[shift] = GetZigZagBarTime(shift); - } - else - { - highsBuffer[shift] = 0; - highsTimeBuffer[shift] = 0; - } - } - - // - // Set Last Value ... - if (extreme_search == 0) // Undefined Values ... - { - // - last_low = 0; - last_high = 0; - } - else - { - // - last_low = curlow; - last_high = curhigh; - } - - // - // Final Selection of Extreme Points for ZigZag ... - for (shift = start; shift < ratesTotal && !IsStopped(); shift++) - { - // - res = 0; - - // - switch (extreme_search) - { - // - case X_ZG_SEARCH_EXTREMUM: - // - if (last_low == 0 && last_high == 0) - { - // - if (highsBuffer[shift] != 0) - { - // - last_high_pos = shift; - last_high = zigzagUppers[shift]; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - zigzagBuffer[shift] = last_high; - - // - res = 1; - } - - // - if (lowsBuffer[shift] != 0) - { - // - last_low_pos = shift; - last_low = zigzagLowers[shift]; - - // - extreme_search = X_ZG_SEARCH_PEAK; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - } - break; - - // - case X_ZG_SEARCH_PEAK: - // - if (lowsBuffer[shift] != 0 && lowsBuffer[shift] < last_low && highsBuffer[shift] == 0) - { - // - zigzagBuffer[last_low_pos] = 0; - - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - res = 1; - } - - // - if (highsBuffer[shift] != 0 && lowsBuffer[shift] == 0) - { - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - res = 1; - } - break; - - // - case X_ZG_SEARCH_VALE: - // - if (highsBuffer[shift] != 0 && highsBuffer[shift] > last_high && lowsBuffer[shift] == 0) - { - // - zigzagBuffer[last_high_pos] = 0; - - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - zigzagBuffer[shift] = last_high; - } - - // - if (lowsBuffer[shift] != 0 && highsBuffer[shift] == 0) - { - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - zigzagBuffer[shift] = last_low; - - // - extreme_search = X_ZG_SEARCH_PEAK; - } - break; - } - } - - // - result = ratesTotal; - - // - return result; -} - -// -void CalculateHKBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double lastHKOpen = - isFirstBar - ? emptyValue - : hkOpenBuffer[lastBarIndex]; - double lastHKClose = - isFirstBar - ? emptyValue - : hkCloseBuffer[lastBarIndex]; - - // - double iHKOpenValue = (lastHKOpen + lastHKClose) / 2; - double iHKCloseValue = (open[barIndex] + high[barIndex] + close[barIndex] + low[barIndex]) / 4; - double iHKHighValue = MathMax(high[barIndex], MathMax(iHKOpenValue, iHKCloseValue)); - double iHKLowValue = MathMin(low[barIndex], MathMin(iHKOpenValue, iHKCloseValue)); - - // - bool isBullish = iHKOpenValue < iHKCloseValue; - bool isBearish = iHKOpenValue > iHKCloseValue; - - // - if (hkIgnoreShadows) - { - // - iHKHighValue = isBullish - ? iHKCloseValue - : iHKOpenValue; - - // - iHKLowValue = isBullish - ? iHKOpenValue - : iHKCloseValue; - } - - // - // XHK Buffers ... - hkOpenBuffer[barIndex] = iHKOpenValue; - hkHighBuffer[barIndex] = iHKHighValue; - hkLowBuffer[barIndex] = iHKLowValue; - hkCloseBuffer[barIndex] = iHKCloseValue; - - // - // XHK Raw Bufferss ... - hkRawOpenBuffer[barIndex] = iHKOpenValue; - hkRawHighBuffer[barIndex] = iHKHighValue; - hkRawLowBuffer[barIndex] = iHKLowValue; - hkRawCloseBuffer[barIndex] = iHKCloseValue; - - // - // Smoothing ... - if (IsXValid(hkSmoothingMode) && hkSmoothingLength > 0) - { - // - // XHK Signal ... - - // - // High ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawHighBuffer, - hkHighBuffer, - hkSmoothingMode // - ); - - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawOpenBuffer, - hkOpenBuffer, - hkSmoothingMode // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawLowBuffer, - hkLowBuffer, - hkSmoothingMode // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - hkSmoothingLength, - hkRawCloseBuffer, - hkCloseBuffer, - hkSmoothingMode // - ); - } - - // - hkBondUpperBuffer[barIndex] = hkHighBuffer[barIndex]; - hkBondLowerBuffer[barIndex] = hkLowBuffer[barIndex]; - - // - // Calculate HK Color ... - double iHKColorValue = - isBullish - ? bullishColorIDX - : isBearish - ? bearishColorIDX - : neuturalColorIDX; - hkColorBuffer[barIndex] = - showHK - ? iHKColorValue - : hideColorIDX; -} - -// -void CalculateCycleRanges( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // SHORT ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_SHORT, - sHHBuffer, - sLLBuffer // - ); - - // - // MEDIUM ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_MEDIUM, - mHHBuffer, - mLLBuffer // - ); - - // - // LONG ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_LONG, - lHHBuffer, - lLLBuffer // - ); - - // - // HIND ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_HIND, - hHHBuffer, - hLLBuffer // - ); -} - -/** - * Calculate Specified Market Cycle Info ... - * - * @param barIndex: Integer, Bar Index ... - * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... - * @param hhBuffer: Highest High Buffer Reference ... - * @param llBuffer: Lowest Low Buffer Reference ... - */ -void CalculateCycle( - int barIndex, - ENUM_X_MARKET_CYCLES cycle, - double &hhBuffer[], - double &llBuffer[] // -) -{ - // - XOHCL bar; - bool isBarInited = bar.Init( - _Symbol, - _Period, - barIndex - // - ); - if (!isBarInited) - { - return; - } - - // - int mLength = 0; - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - mLength = mSCLength; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - mLength = mMCLength; - break; - - // - case X_MARKET_CYCLE_LONG: - mLength = mLCLength; - break; - - // - case X_MARKET_CYCLE_HIND: - mLength = mHCLength; - break; - } - - // - if (mLength == 0) - { - return; - } - - // - // Find Highest High ... - double hhValue = bar.FindHighest( - mLength, - upperMode // - ); - hhBuffer[barIndex] = hhValue; - - // - // Find Lowest Low ... - double llValue = bar.FindLowest( - mLength, - lowerMode // - ); - llBuffer[barIndex] = llValue; - - // - bar.Clean(); -} - -// -// -// - -// -// Get Specified Bar Time as Double ... -double GetZigZagBarTime(int barIndex) -{ - // - if (barIndex <= 0) - { - barIndex = 0; - } - - // - datetime time = iTime(_Symbol, _Period, barIndex); - - // - double result = (double)((int)time); - - // - return result; -} - -// -// Filling Required Prices Based on MODE ... -int FillPrice( - ENUM_X_PRICE mode, - double &dest[], - const double &open[], - const double &high[], - const double &close[], - const double &low[] // -) -{ - // - int result = 0; - - // - SpecifiedClean(dest); - - // - if (!IsXValid(mode)) - { - return result; - } - - // - switch (mode) - { - // - case X_PRICE_HIGH: - // - result = ArrayCopy( - dest, - high // - ); - break; - - // - case X_PRICE_LOW: - // - result = ArrayCopy( - dest, - low // - ); - break; - - // - case X_PRICE_OPEN: - // - result = ArrayCopy( - dest, - open // - ); - break; - - // - case X_PRICE_CLOSE: - // - result = ArrayCopy( - dest, - close // - ); - break; - - // - default: - // - result = ArrayCopy( - dest, - close // - ); - break; - } - - // - return result; -} - -// -// Search for the index of the highest bar ... -int Highest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double max = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] > max) - { - // - result = i; - max = mArray[i]; - } - } - - // - // Return index of the highest bar - return result; -} - -// -// Search for the index of the lowest bar ... -int Lowest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double min = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] < min) - { - // - result = i; - min = mArray[i]; - } - } - - // - // Return index of the lowest bar - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/xfima.poi.analysis.tmp.code.mq5 b/Documents/BKP/xfima.poi.analysis.tmp.code.mq5 deleted file mode 100644 index 09b58b22..00000000 --- a/Documents/BKP/xfima.poi.analysis.tmp.code.mq5 +++ /dev/null @@ -1,641 +0,0 @@ -// // -// // Detect At lease Two PEAK and Two Vale ... -// XZigZagPoint tmpPoints[]; -// Copy( -// points, -// tmpPoints // -// ); - -// // -// // Detect Highs ... - -// // -// // Highest High ... - -// // -// XZigZagPoint iZGPeak1; -// XZigZagPoint iZGPeak2; - -// // -// // First ... -// int idx = GetHighest( -// tmpPoints, -// X_ZIGZAG_POINT_TYPE_PEAK // -// ); -// result = IsValidIndex(idx); -// if (!result) -// { -// // -// Clean(); -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// SpecifiedClean(tmpPoints); - -// // -// return result; -// } -// iZGPeak1 = tmpPoints[idx]; -// ArrayRemove( -// tmpPoints, -// idx, -// 1 // -// ); - -// // -// // Second ... -// idx = GetHighest( -// tmpPoints, -// X_ZIGZAG_POINT_TYPE_PEAK // -// ); -// result = IsValidIndex(idx); -// if (!result) -// { -// // -// Clean(); -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// SpecifiedClean(tmpPoints); - -// // -// return result; -// } -// iZGPeak2 = tmpPoints[idx]; -// ArrayRemove( -// tmpPoints, -// idx, -// 1 // -// ); - -// // -// // Detect Lows ... - -// // -// XZigZagPoint iZGVale1; -// XZigZagPoint iZGVale2; - -// // -// // First ... -// idx = GetLowest( -// tmpPoints, -// X_ZIGZAG_POINT_TYPE_VALE // -// ); -// result = IsValidIndex(idx); -// if (!result) -// { -// // -// Clean(); -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// iZGVale1.Clean(); -// iZGVale2.Clean(); -// SpecifiedClean(tmpPoints); - -// // -// return result; -// } -// iZGVale1 = tmpPoints[idx]; -// ArrayRemove( -// tmpPoints, -// idx, -// 1 // -// ); - -// // -// // Second ... -// idx = GetLowest( -// tmpPoints, -// X_ZIGZAG_POINT_TYPE_VALE // -// ); -// result = IsValidIndex(idx); -// if (!result) -// { -// // -// Clean(); -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// iZGVale1.Clean(); -// iZGVale2.Clean(); -// SpecifiedClean(tmpPoints); - -// // -// return result; -// } -// iZGVale2 = tmpPoints[idx]; -// ArrayRemove( -// tmpPoints, -// idx, -// 1 // -// ); - -// // -// // Check Directions ... -// bool isBullish = -// // -// (iZGPeak1.time > iZGPeak2.time && -// iZGVale1.time < iZGVale2.time) -// // -// ; -// bool isBearish = -// // -// (iZGPeak1.time < iZGPeak2.time && -// iZGVale1.time > iZGVale2.time) -// // -// ; -// result = -// (isBullish && !isBearish) || -// (isBearish && !isBullish); -// if (!result) -// { -// // -// Clean(); -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// iZGVale1.Clean(); -// iZGVale2.Clean(); -// SpecifiedClean(tmpPoints); - -// // -// return result; -// } - -// // -// // Setting Direction ... -// dir = -// isBullish -// ? X_DIRECTION_BULLISH -// : isBearish -// ? X_DIRECTION_BEARISH -// : X_DIRECTION_NONE; - -// // -// // Setting Points ... -// Copy( -// points, -// pivots // -// ); - -// -// Cleanup Resources ... -// iZGPeak1.Clean(); -// iZGPeak2.Clean(); -// iZGVale1.Clean(); -// iZGVale2.Clean(); -// SpecifiedClean(tmpPoints); - -/** - * Analyse Market Structure ... - * - * @param bar: XOHCL, Specified Bar ... - * @param _pivots: XZigZagPivot, Specified ZigZag Points Collection ... - * - * @return ( bool ) - */ -bool Analyse( - XOHCL &bar, - XZigZagPivot &_pivots[] // -) -{ - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasChild(_pivots) && - bar.symbol == _pivots[0].symbol; - if (!result) - { - // - Clean(); - return result; - } - - // - // AssignSymbol and Period ... - time = bar.time; - symbol = bar.symbol; - period = bar.period; - Copy(_pivots, pivots); - - // - // Calculate Peaks and Vales Regressions ... - - // - // Peaks Processing ... - double mPeak = 0; - double bPeak = 0; - result = ValidateZigZagPivots( - mPeak, - bPeak, - _pivots, - X_ZIGZAG_PIVOT_TYPE_PEAK // - ); - - // - // Vales Processing ... - double mVale = 0; - double bVale = 0; - result = - result && - ValidateZigZagPivots( - mVale, - bVale, - _pivots, - X_ZIGZAG_PIVOT_TYPE_VALE // - ); - if (!result) - { - // - Clean(); - // SpecifiedClean(recentPeaks); - // SpecifiedClean(recentVales); - - // - return result; - } - - // // - // // Extracting Pivots ... - // int numberOfPivots = 2; - - // // - // // Reading Recent Peaks ... - // XZigZagPivot recentPeaks[]; - // int recentPeaksCount = GetRecent( - // _pivots, - // recentPeaks, - // numberOfPivots, - // X_ZIGZAG_PIVOT_TYPE_PEAK // - // ); - - // // - // // Reading Recent Vales ... - // XZigZagPivot recentVales[]; - // int recentValesCount = GetRecent( - // _pivots, - // recentVales, - // numberOfPivots, - // X_ZIGZAG_PIVOT_TYPE_VALE // - // ); - - // // - // // Validate Pivots ... - // result = - // recentPeaksCount >= numberOfPivots && - // recentValesCount >= numberOfPivots; - // if (!result) - // { - // // - // Clean(); - // SpecifiedClean(recentPeaks); - // SpecifiedClean(recentVales); - - // // - // return result; - // } - - // // - // // Detect Direction ... - - // // - // int zIdx = 0; - // int pIdx = numberOfPivots - 1; - - // // - // bool isBullish = - // recentPeaks[zIdx].value > recentPeaks[pIdx].value && - // recentVales[zIdx].value > recentVales[pIdx].value; - - // // - // bool isBearish = - // recentPeaks[zIdx].value < recentPeaks[pIdx].value && - // recentVales[zIdx].value < recentVales[pIdx].value; - - // // - // result = isBullish || isBearish; - // if (!result) - // { - // // - // Clean(); - // SpecifiedClean(recentPeaks); - // SpecifiedClean(recentVales); - - // // - // return result; - // } - - // // - // dir = - // isBullish - // ? X_DIRECTION_BULLISH - // : X_DIRECTION_BEARISH; - - // - // Calculate Support and Resistance ... - - // - // Validate ... - result = IsValid(); - if (!result) - { - Clean(); - } - - // - // SpecifiedClean(recentPeaks); - // SpecifiedClean(recentVales); - - // - return result; -} - -bool ValidateZigZagPivots( - double &_pivot, - double &_processed, - XZigZagPivot &_pivots[], - ENUM_X_ZIGZAG_POINT_TYPE _type // -) -{ - // - bool result = false; - - // - // Prepare ... - _pivot = 0; - _processed = 0; - - // - // Validate ... - result = HasChild(_pivots); - if (!result) - { - return result; - } - - // - // Define Required Variables for Calculations ... - double sumT = 0; - double sumP = 0; - double sumTP = 0; - double sumT2 = 0; - bool has = false; - int typeCount = 0; - - // - // Loop Through Pivots to Calculate Specified - // Type Pivots Summaries ... - int count = ArraySize(_pivots); - for (int i = 0; i < count; i++) - { - // - // Check Type Passed ... - has = - !IsXValid(_type) - ? true - : _type == _pivots[i].type; - if (!has) - { - continue; - } - - // - typeCount++; - double iP = _pivots[i].value; - double iT = (double)_pivots[i].time; - - // - sumT += iT; - sumP += iP; - sumTP += iT * iP; - sumT2 += iT * iP; - } - - // - // Calculate Process Values ... - double denominator = typeCount * sumT2 - sumT * sumT; - if (denominator != 0) - { - // - _pivot = (typeCount * sumTP - sumT * sumP) / denominator; - _processed = (sumP - _pivot * sumT) / typeCount; - } - else - { - _processed = sumP / typeCount; - } - - // - // Validating Result ... - result = _pivot > 0 && - _processed > 0; - - // - return result; -} - -/** - * Analyse Market Structure ... - * - * @param bar: XOHCL, Specified Bar ... - * @param _pivots: XZigZagPivot, Specified ZigZag Points Collection ... - * - * @return ( bool ) - */ -bool Analyse( - XOHCL &bar, - XZigZagPivot &_pivots[] // -) -{ - // - bool result = false; - - // - // Validate ... - result = bar.IsValid() && - HasChild(_pivots) && - bar.symbol == _pivots[0].symbol; - if (!result) - { - // - Clean(); - return result; - } - - // - // Assign Requirements ... - - // - time = bar.time; - symbol = bar.symbol; - period = bar.period; - Copy(_pivots, pivots); - - // - int oldestPeakIdx = GetOldest(pivots, X_ZIGZAG_PIVOT_TYPE_PEAK); - int oldestValeIdx = GetOldest(pivots, X_ZIGZAG_PIVOT_TYPE_VALE); - int youngestPeakIdx = GetYoungest(pivots, X_ZIGZAG_PIVOT_TYPE_PEAK); - int youngestValeIdx = GetYoungest(pivots, X_ZIGZAG_PIVOT_TYPE_VALE); - - // - // Calculate Peaks and Vales Regressions ... - - // - // Peaks Processing ... - double mPeak = 0; - double bPeak = 0; - bool hasPeak = ValidateZigZagPivots( - mPeak, - bPeak, - pivots, - X_ZIGZAG_PIVOT_TYPE_PEAK // - ); - - // - // Vales Processing ... - double mVale = 0; - double bVale = 0; - bool hasVale = ValidateZigZagPivots( - mVale, - bVale, - pivots, - X_ZIGZAG_PIVOT_TYPE_VALE // - ); - - // - // Validate Calculated requirements ... - result = - (hasPeak || hasVale) && - (IsValidIndex(oldestPeakIdx) && - IsValidIndex(oldestValeIdx) && - IsValidIndex(youngestPeakIdx) && - IsValidIndex(youngestValeIdx)); - if (!result) - { - // - Clean(); - return result; - } - - // - // Calculating Values ... - - // - peakToTime = pivots[youngestPeakIdx].time; - peakFromTime = pivots[oldestPeakIdx].time; - - // - valeToTime = pivots[youngestValeIdx].time; - valeFromTime = pivots[oldestValeIdx].time; - - // - // Check Different Senarios ... - // 1-Valid Peak and Valid Vale Exists ... - if (hasPeak && hasVale) - { - // - // When Slopes Have same Sign, Use Average Slope for Parallel Lines ... - if (mPeak * mVale > 0) - { - // - // Calculating Parallel Slopes ... - double slopeParallel = (mPeak + mVale) / 2; - double bParallelPeak = pivots[youngestPeakIdx].value - slopeParallel * (double)peakToTime; - double bParallelVale = pivots[youngestValeIdx].value - slopeParallel * (double)valeToTime; - - // - // Peak ... - peakTo = slopeParallel * (double)peakToTime + bParallelPeak; - peakFrom = slopeParallel * (double)peakFromTime + bParallelPeak; - - // - // Vale ... - valeTo = slopeParallel * (double)valeToTime + bParallelVale; - valeFrom = slopeParallel * (double)valeFromTime + bParallelVale; - } - else - // - // separate trendlines if slopes differ ... - { - // - // Peak ... - peakTo = mPeak * (double)peakToTime + bPeak; - peakFrom = mPeak * (double)peakFromTime + bPeak; - - // - // Vale ... - valeTo = mVale * (double)valeToTime + bVale; - valeFrom = mVale * (double)valeFromTime + bVale; - } - } - else - // - // Only one of them Exists ... - { - // - // Valid Peak ... - if (hasPeak) - { - // - // Peak ... - peakTo = mPeak * (double)peakToTime + bPeak; - peakFrom = mPeak * (double)peakFromTime + bPeak; - } - - // - // Valid Vale ... - if (hasVale) - { - // - // Vale ... - valeTo = mVale * (double)valeToTime + bVale; - valeFrom = mVale * (double)valeFromTime + bVale; - } - } - - // - // Detecting Direction ... - - // - bool isBullish = - valeTo > valeFrom || - (valeTo > valeFrom && - peakTo > peakFrom); - - // - bool isBearish = - peakTo < peakFrom || - (peakTo < peakFrom && - valeTo < valeFrom); - - // - // Validate When Only One Direction Exists ... - result = - (isBullish && !isBearish) || - (isBearish && !isBullish); - if (!result) - { - // - Clean(); - return result; - } - - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Calculate Support and Resistance ... - - // - // Validate ... - result = IsValid(); - if (!result) - { - Clean(); - } - - // - return result; -} diff --git a/Documents/BKP/xfima.signaller.tmp.codes.mq5 b/Documents/BKP/xfima.signaller.tmp.codes.mq5 deleted file mode 100644 index 3c487b17..00000000 --- a/Documents/BKP/xfima.signaller.tmp.codes.mq5 +++ /dev/null @@ -1,511 +0,0 @@ -// -// Testing Bar Zones ... -// XBoxZone barZones[]; -// int barCounts = fima2Signaller.fimaHelper.ExtractBarZones( -// barZones, -// 1, // Bar Index ... -// 50, // Number of Zones ... -// 3, // Break Validation Length ... -// true, // Validate Fake Breakes ... -// 5, // Shadow Multiplier ... -// 1, // Strength ... -// 14 // Validation Length ... -// ); -// if (IsValidSize(barCounts)) -// { -// // -// // XCBoxObject *iObj; -// // for (int i = 0; i < barCounts; i++) -// // { -// // // -// // iObj = NULL; -// // bool isCreated = fima2Signaller.poiDrawer.DrawBox( -// // barZones[i], -// // iObj, -// // true, // Ignore At ... -// // barZones[i].type // Name ... -// // ); - -// // // -// // ZeroMemory(iObj); -// // } - -// // // -// // Print("Bar Zones Detected ..."); -// } - -// -// Testing HK Zones ... -// XBoxZone hkZones[]; -// int hkCounts = fima2Signaller.fimaHelper.ExtractHKZones( -// hkZones, -// 1, // Bar Index ... -// 50, // Number of Zones ... -// 5, // Shadow Multiplier ... -// 1, // Strength ... -// 14 // Validation Length ... -// ); -// if (IsValidSize(hkCounts)) -// { -// // // -// // XCBoxObject *iObj; -// // for (int i = 0; i < hkCounts; i++) -// // { -// // // -// // iObj = NULL; -// // bool isCreated = fima2Signaller.poiDrawer.DrawBox( -// // hkZones[i], -// // iObj, -// // true, // Ignore At ... -// // hkZones[i].type // Name ... -// // ); - -// // // -// // ZeroMemory(iObj); -// // } - -// // // -// // Print("HK Zones Detected ..."); -// } - -// -// Testing XFIMA MA Pivots ... -// XPivot maPivots[]; -// int maPivotsCount = fimaHelper.ExtractMAPivots( -// maPivots, -// 1, // Bar Index ... -// 50, // Number of Pivots ... -// 1 // Validation Diff ... -// ); -// if (IsValidSize(maPivotsCount)) -// { -// // -// // CArrayObj *iPivotsObj; -// // maPivotsCount = poiDrawer.DrawPivots( -// // maPivots, -// // iPivotsObj // -// // ); - -// // -// // Print("MA Pivots Detected ..."); -// } - -// -// Custom Indicator Direction Shifts ... -bool hasMACross = HasDirection(structure.maCrossDir); -bool hasHKSwitch = HasDirection(structure.hkSwitchDir); -bool hasSARSwitch = HasDirection(structure.sarSwitchDir); - -// -// Check Required Pattern Exists ... -bool hasPinnedBar = HasDirection(structure.pinnedDir); -bool hasEngulfedBar = HasDirection(structure.engulfedDir); -bool hasFlagPattern = HasDirection(structure.flagPatternDir); -bool hasStarPattern = HasDirection(structure.starPatternDir); -bool hasRisingPattern = HasDirection(structure.risingPatternDir); -bool hasPiercingPattern = HasDirection(structure.piercingPatternDir); -bool hasSignalKeyBar = HasDirection(structure.signalKeyBarPatternDir); - -// -// Check Bar Pattern Exists ... -// and Select Pattern Direction and Price and Price Type ... -has = hasPinnedBar || - hasEngulfedBar || - hasFlagPattern || - hasStarPattern || - hasSignalKeyBar || - hasRisingPattern || - hasPiercingPattern; -if (has) -{ - // - if (hasPinnedBar) - { - // - iDir = structure.pinnedDir; - iName = "XPinned_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasEngulfedBar) - { - // - iDir = structure.engulfedDir; - iName = "XEngulfed_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasFlagPattern) - { - // - iDir = structure.flagPatternDir; - iName = "XFlag_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasStarPattern) - { - // - iDir = structure.starPatternDir; - iName = "XStar_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasSignalKeyBar) - { - // - iDir = structure.risingPatternDir; - iName = "XRising_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasRisingPattern) - { - // - iDir = structure.piercingPatternDir; - iName = "XPiercing_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - else if (hasPiercingPattern) - { - // - iDir = structure.signalKeyBarPatternDir; - iName = "XSignalKey_" + ToXString(iDir) + ToXString(TimeToSeconds(bar.time)); - } - - // - isBullish = IsSpecifiedBullish(iDir); - isBearish = IsSpecifiedBearish(iDir); - - // - // Retrieve Price Type for Validate ... - iPriceType = isBullish - ? X_PRICE_DOWN - : X_PRICE_UP; - iPriceEdgeType = isBullish - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - iPrice = bar.GetPrice(iPriceType); - iPriceEdge = bar.GetPrice(iPriceEdgeType); - - // - // Validate Calculations ... - has = HasDirection(iDir) && - (isBullish || - isBearish) && - NotEmptyZero(iPrice) && - NotEmptyZero(iPriceEdge) && - iPrice != iPriceEdge; - if (!has) - { - // - isBullish = false; - isBearish = false; - iDir = X_DIRECTION_NONE; - } -} - -// -// Disable Signallers ... - -has = false; -// Strategy 1 ... -// Works on Support or Resistances Areas ... -// has = Strategy1HasSignal( -// bar, -// iZone, -// iName, -// supports, -// resistances, -// iDir, -// structure, -// fimaConditions // -// ); - -// -// Do all Draws Here ... -bool canDraw = false; -if (canDraw && has) -{ - // - int iWidth = 2; - XPOIStyle iStyle; - XCBoxObject *iBoxObj = NULL; - color iClr = isBullish - ? clrYellow - : clrDarkOrange; - - // - // Supports ... - has = HasChild(supports); - if (has) - { - // - count = ArraySize(supports); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - supports[i], - iBoxObj, - true, // Ignore At ... - supports[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - supports[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Resistances ... - has = HasChild(resistances); - if (has) - { - // - count = ArraySize(resistances); - for (int i = 0; i < count; i++) - { - // - has = poiDrawer.DrawBox( - resistances[i], - iBoxObj, - true, // Ignore At ... - resistances[i].type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - resistances[i].dir // - ); - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - - // - iStyle.Clean(); - ZeroMemory(iBoxObj); - } - } - - // - // Selected Zone ... - has = iZone.IsValid(); - if (has) - { - // - has = poiDrawer.DrawBox( - iZone, - iBoxObj, - true, // Ignore At ... - iZone.type // Name ... - ); - if (has) - { - // - poiDrawer.GetBoxStyle( - iStyle, - iZone.dir // - ); - - // - iStyle.clr = iClr; - iStyle.width = iWidth; - - // - poiDrawer.ApplyBoxStyle( - iBoxObj, - iStyle // - ); - } - } - - // - // TrendLines ... - - // - // Pivots ... - - // - has = HasChild(pvPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - pvPivots, - drawnPivots // - ); - } - - // - has = HasChild(zgPivots); - if (has) - { - // - CArrayObj *drawnPivots = new CArrayObj(); - count = poiDrawer.DrawPivots( - zgPivots, - drawnPivots // - ); - } - - // - // Patterns Bar ... - has = HasDirection(iDir); - if (has) - { - // - int iCode = 159; - ENUM_ARROW_ANCHOR iAnchor = isBullish - ? ANCHOR_TOP - : ANCHOR_BOTTOM; - - // - XCBarArrowObject *iPatternObj; - has = poiDrawer.DrawBarArrow( - bar, - iPatternObj, - iPriceEdgeType, - iCode, - iClr, - iWidth, - iAnchor, - iName, - true, // Ignore Bar Tag ... - 10 // Threshold ... - ); - } -} - -///////////////////////////////////////////////// - -/** - * Check Pattern Has Signal Based on Strategy 2 ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param patternName: string, detected pattern's name ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param patternDir: ENUM_X_DIRECTION, detected pattern's direction ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * @param fimaMarketStructure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * - * @return ( bool ) - */ -bool Strategy2HasSignal( - XOHCL &bar, - XBoxZone &iZone, - string patternName, - XBoxZone &supports[], - XBoxZone &resistances[], - ENUM_X_DIRECTION patternDir, - XFIMAMarketStructure &structure, - XFIMAConditions &fimaConditions, - XFIMAMarketStructure &fimaMarketStructure // -) -{ - // - bool result = false; - - // - // Prepare ... - iZone.Clean(); - - // - // Validate ... - - // - // Do Detection ... - - // - // Validate result ... - - // - // Cleanup Resources ... - - // - return result; -} - -/** - * Check Pattern Has Signal Based on Strategy 1 ... - * - * @param bar: XOHCL, reference to Pattern Bar ... - * @param iZone: XBoxZone, reference to holds affected zone ... - * @param supports: XBoxZone, array reference to Provide Exists Supports ... - * @param resistances: XBoxZone, array reference to Provide Exists Resistances ... - * @param structure: XFIMAMarketStructure, refrence to Provides Market Structure ... - * @param fimaConditions: XFIMAConditions, reference to Bar Specified XFIMA Conditions ... - * - * @return ( bool ) - */ -bool Strategy3HasSignal( - XOHCL &bar, - XBoxZone &iZone, - XBoxZone &supports[], - XBoxZone &resistances[], - XFIMAMarketStructure &structure, - XFIMAConditions &fimaConditions // -) -{ - // - bool result = false; - - // - // Prepare ... - iZone.Clean(); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Reading XHK ... - - // - // Bar 1 ... - double cHKO = fimaConditions.hkOpenBuffer[0]; - double cHKH = fimaConditions.hkHighBuffer[0]; - double cHKL = fimaConditions.hkLowBuffer[0]; - double cHKC = fimaConditions.hkCloseBuffer[0]; - - // - // Bar 2 ... - double pHKO = fimaConditions.hkOpenBuffer[1]; - double pHKH = fimaConditions.hkHighBuffer[1]; - double pHKL = fimaConditions.hkLowBuffer[1]; - double pHKC = fimaConditions.hkCloseBuffer[1]; - - // - bool isCHKBullish = cHKO < cHKC; - bool isCHKBearish = cHKO > cHKC; - - // - bool isPHKBullish = pHKO < pHKC; - bool isPHKBearish = pHKO > pHKC; - - // - bool isCHKSwitchedToBullish = isCHKBullish && !isPHKBullish; - bool isCHKSwitchedToBearish = isCHKBearish && !isPHKBearish; - - // - return result; -} diff --git a/Documents/BKP/xfima.tmp.codes.poi.mq5 b/Documents/BKP/xfima.tmp.codes.poi.mq5 deleted file mode 100644 index 2451c737..00000000 --- a/Documents/BKP/xfima.tmp.codes.poi.mq5 +++ /dev/null @@ -1,916 +0,0 @@ - -/** - * Leg Pattern Detection ... - * - * @param bar: XOHCL, reference to Specified Bar ... - * @param zone: XBoxZone, reference to Holds Detection Zone ... - * @param validationLength: int, leg minimum Validation Length ... - * @param loopback: int, Max Allowed Loopback Length ... - * - * @return ( bool ) - */ -bool IsLegPattern( - XOHCL &bar, - XLeg &leg, - int validationLength = 3, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Prepare ... - leg.Clean(); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 5); - - // - // Validate ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - // Prepare Patterns Analysis Config ... - XPatternAnalysisConfig iPatternsConfig; - iPatternsConfig.Default(); - iPatternsConfig.CleanPatterns(); - iPatternsConfig.AddPattern(X_BAR_PATTERN_LOW); - iPatternsConfig.AddPattern(X_BAR_PATTERN_HIGH); - iPatternsConfig.AddPattern(X_BAR_PATTERN_FLAG); - iPatternsConfig.AddPattern(X_BAR_PATTERN_STAR); - iPatternsConfig.AddPattern(X_BAR_PATTERN_RISING); - iPatternsConfig.AddPattern(X_BAR_PATTERN_PIERCING); - iPatternsConfig.AddPattern(X_BAR_PATTERN_ENGULFED); - iPatternsConfig.AddPattern(X_BAR_PATTERN_MOMENTUM); - iPatternsConfig.AddPattern(X_BAR_PATTERN_SIGNALKEY); - iPatternsConfig.AddPattern(X_BAR_PATTERN_TRUE_GAPED); - - // - XOHCL iBar; - XOHCL pBar; - XOHCL iZBar; - XBoxZone zone; - XBoxZone iZone; - XBoxZone jZone; - bool has = false; - XBoxZone supports[]; - XOHCL bullishBars[]; - XOHCL bearishBars[]; - XBoxZone bullishFVGs[]; - XBoxZone bearishFVGs[]; - bool isBullish = false; - bool isBearish = false; - XBoxZone resistances[]; - double bullishPower = 0; - double bearishPower = 0; - int bullishBarsCount = 0; - int bearishBarsCount = 0; - int barIndex = bar.Index(); - int start = barIndex + 1; - XPatternAnalysis iPattern; - int end = start + loopback; - XPatternAnalysis patterns[]; - int bullishPatternsCount = 0; - int bearishPatternsCount = 0; - int sequentialsBullishBarsCount = 0; - int sequentialsBearishBarsCount = 0; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - for (int i = end; i >= start; i--) - { - // - // Initialize Indexed Bar ... - iBar.Clean(); - pBar.Clean(); - result = bar.BarAt(i, iBar); - result = result && - iBar.GetPreviousBar(pBar); - if (!result) - { - break; - } - - // - // Fill Bar Direction ... - isBullish = iBar.IsBullish(); - isBearish = iBar.IsBearish(); - - // - // Directional ... - - // - if (isBullish) - { - // - bullishBarsCount++; - - // - bullishPower += iBar.GetBody(); - bullishPower += iBar.GetLowShadow(); - bullishPower -= iBar.GetHighShadow(); - - // - AddIfNotExists(iBar, bullishBars); - } - - // - if (isBearish) - { - // - bearishBarsCount++; - - // - bearishPower += iBar.GetBody(); - bearishPower -= iBar.GetLowShadow(); - bearishPower += iBar.GetHighShadow(); - - // - AddIfNotExists(iBar, bearishBars); - } - - // - // Sequentail .... - - // - // Bullish ... - if (isBullish) - { - // - if (pBar.IsBullish()) - { - sequentialsBullishBarsCount++; - } - else if (pBar.IsBearish()) - { - sequentialsBullishBarsCount = 0; - } - } - - // - // Bearish ... - if (isBearish) - { - // - if (pBar.IsBearish()) - { - sequentialsBearishBarsCount++; - } - else if (pBar.IsBullish()) - { - sequentialsBearishBarsCount = 0; - } - } - - // - // Detect Patterns ... - iPattern.Clean(); - has = AnalyseBarPatterns(iBar, iPattern, iPatternsConfig); - if (has) - { - // - AddRef(iPattern, patterns); - - // - bullishPatternsCount += iPattern.Count(X_DIRECTION_BULLISH); - bearishPatternsCount += iPattern.Count(X_DIRECTION_BEARISH); - } - - // - // FVG Detection ... - CleanDirection(iDir); - has = HasFVG(iBar, iDir, iZone); - if (has) - { - // - if (iZone.IsBullish()) - { - AddIfNotExists(iZone, bullishFVGs); - } - else - { - AddIfNotExists(iZone, bearishFVGs); - } - } - - // - // Support / Resistance Detection ... - has = HasSupportResistance( - iBar, - iZone, - jZone, - 5 // - ); - if (has) - { - // - if (iZone.IsValid()) - { - AddIfNotExists(iZone, supports); - } - - // - if (jZone.IsValid()) - { - AddIfNotExists(jZone, resistances); - } - } - } - - // - // Summarizing ... - - // - // Detect Direction ... - zone.Clean(); - isBullish = false; - isBearish = false; - CleanDirection(iDir); - - // - isBullish = - // - bullishPower > 0 && - bullishBarsCount > 0 && - bullishPatternsCount > 0 && - sequentialsBullishBarsCount > 0 && - // - bullishPower > bearishPower && - bullishBarsCount > bearishBarsCount && - bullishPatternsCount > bearishPatternsCount && - sequentialsBullishBarsCount > sequentialsBearishBarsCount - // - ; - - // - isBearish = - // - bearishPower > 0 && - bearishBarsCount > 0 && - bearishPatternsCount > 0 && - sequentialsBearishBarsCount > 0 && - // - bearishPower > bullishPower && - bearishBarsCount > bullishBarsCount && - bearishPatternsCount > bullishPatternsCount && - sequentialsBearishBarsCount > sequentialsBullishBarsCount - // - ; - - // - // Validate ... - result = - (isBullish && !isBearish) || - (isBearish && !isBullish); - - // - // PRICE Types ... - ENUM_X_PRICE lowerPriceType = X_PRICE_LOW; - ENUM_X_PRICE upperPriceType = X_PRICE_HIGH; - - // - // Prepare Zone ... - if (result) - { - // - zone.at = bar.time; - zone.to = bar.time; - zone.period = bar.period; - zone.symbol = bar.symbol; - - // - zone.type = ToXString(X_BAR_PATTERN_LEG); - zone.dir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - int idx = -1; - if (isBullish) - { - idx = GetOldest(bullishBars); - } - else - { - idx = GetOldest(bearishBars); - } - - // - result = IsValidIndex(idx); - if (result) - { - // - iZBar.Clean(); - if (isBullish) - { - iZBar = bullishBars[idx]; - } - else - { - iZBar = bearishBars[idx]; - } - - // - zone.from = iZBar.time; - - // - iZBar.Clean(); - } - - // - if (isBullish) - { - // - // Prepare Upper and Lower ... - - // - // Upper ... - idx = GetHighestBarPrice(bullishBars, upperPriceType); - if (IsValidIndex(idx)) - { - zone.upper = bullishBars[idx].GetPrice(upperPriceType); - } - - // - // Lower ... - idx = GetLowestBarPrice(bullishBars, upperPriceType); - if (IsValidIndex(idx)) - { - zone.lower = bullishBars[idx].GetPrice(lowerPriceType); - } - } - else - { - // - // Prepare Upper and Lower ... - - // - // Upper ... - idx = GetHighestBarPrice(bearishBars, upperPriceType); - if (IsValidIndex(idx)) - { - zone.upper = bearishBars[idx].GetPrice(upperPriceType); - } - - // - // Lower ... - idx = GetLowestBarPrice(bearishBars, upperPriceType); - if (IsValidIndex(idx)) - { - zone.lower = bearishBars[idx].GetPrice(lowerPriceType); - } - } - - // - result = zone.IsValid(); - } - - // - // Prepare XLeg ... - if (result) - { - // - leg.dir = zone.dir; - leg.time = zone.from; - leg.upper = zone.upper; - leg.lower = zone.lower; - leg.symbol = zone.symbol; - leg.period = zone.period; - Copy(patterns, leg.patterns); - Copy(supports, leg.supports); - Copy(bullishBars, leg.bullishBars); - Copy(bearishBars, leg.bearishBars); - Copy(resistances, leg.resistances); - Copy(bullishFVGs, leg.bullishFVGs); - Copy(bearishFVGs, leg.bearishFVGs); - leg.sequentialBullishBars = sequentialsBullishBarsCount; - leg.sequentialBearishBars = sequentialsBearishBarsCount; - - // - result = leg.IsValid(); - } - - // - // Cleanup ... - if (!result) - { - zone.Clean(); - } - iBar.Clean(); - pBar.Clean(); - zone.Clean(); - iZBar.Clean(); - iZone.Clean(); - jZone.Clean(); - iPattern.Clean(); - XClean(supports); - XClean(patterns); - XClean(bullishBars); - XClean(bearishBars); - XClean(bullishFVGs); - XClean(bearishFVGs); - XClean(resistances); - - // - return result; -} - -bool IsLegPattern1( - XOHCL &bar, - XLeg &leg, - int validationLength = 5, - int loopback = 500 // -) -{ - // - bool result = false; - - // - // Prepare ... - leg.Clean(); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - validationLength = NormalizeInt(validationLength, 3); - - // - // Validate ... - result = bar.IsValid() && - fimaParser.IsValid(); - if (!result) - { - return result; - } - - // - int idx = bar.Index(); - while (idx < bar.Index() + loopback) - { - // - } - - // - return result; -} - -////////////////////////////////////////////////// - -// -// Leg ... - -XLeg leg; // Exists Leg ... -bool drawLeg; // Draw Leg ... -bool manageLegs; - -// -bool HasLeg() -{ - return leg.IsValid(); -} - -// -bool ValidateLeg(XOHCL &bar) -{ - // - bool result = false; - - // - result = HasLeg() && - bar.IsValid(); - if (!result) - { - return result; - } - - // - result = - leg.IsBullish() - ? bar.low > leg.lower - : leg.IsBearish() - ? bar.high < leg.upper - : false; - - // - return result; -} - -// -void DrawLeg() -{ - // - if (!drawLeg) - { - return; - } - - // - if (!HasLeg()) - { - return; - } - - // - // Update to Times ... - leg.UpdateTimes(); - - // - // Draw Leg Box ... - XBoxZone legZone; - leg.ToBox(legZone); - if (legZone.IsValid()) - { - // - legZone.to = TimeCurrent(); - poiDrawer.DrawZone(legZone, structureDrawConfig.drawConfig); - } - - // - // Draw Legs Other Stufs ... - return; - - // - // FVGs ... - poiDrawer.DrawZones(leg.bullishFVGs, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.bearishFVGs, structureDrawConfig.drawConfig); - - // - // Support and Resistances ... - poiDrawer.DrawZones(leg.supports, structureDrawConfig.drawConfig); - poiDrawer.DrawZones(leg.resistances, structureDrawConfig.drawConfig); - - // - // Patterns ... - poiDrawer.DrawPatternAnalysises(leg.patterns, structureDrawConfig.barAnalysisDrawConfig); -} - -// -void ManageLeg(XOHCL &bar) -{ - // - // Validate Exists ... - if (HasLeg()) - { - // - if (!ValidateLeg(bar)) - { - // - // Invalidate XLeg ... - leg.Clean(); - } - } - - // - // Detect New ... - if (!HasLeg()) - { - poiDetector.IsLegPattern(bar, leg); - } - - // - // Update Exists ... - if (HasLeg()) - { - // - // Update to Times ... - leg.UpdateTimes(); - - // - DrawLeg(); - } -} - -// -// -// - -ManageLeg(bar); - -// -// Checking For Leg Pattern ... -bool hasLeg = poiDetector.IsLegPattern( - pBar, - _leg, - 3, - 10 // -); -if (hasLeg) -{ - hasLeg = _leg.ToBox(legZone); -} -bool hasBullishLeg = hasLeg && _leg.IsBullish(); -bool hasBearishLeg = hasLeg && _leg.IsBearish(); - -// -// -// - -int CollectPivots( - XPivot &pivots[], - int barIndex = 0, - int loopback = 500 // -) -{ - // - int result = 0; - - // - // Prepare ... - XClean(pivots); - - // - // Normalize ... - loopback = NormalizeInt(loopback, 50); - barIndex = NormalizeBarIndex(barIndex); - - // - // Validate ... - bool has = IsValid(); - if (!has) - { - return result; - } - - // - has = false; - XOHCL tmpBar; - XPivot tmpPivot; - double tmpValue; - datetime tmpTime; - bool isBullish = false; - bool isBearish = false; - string tmpSymbol = symbol; - ENUM_TIMEFRAMES tmpPeriod = period; - ENUM_X_DIRECTION tmpDir = X_DIRECTION_NONE; - for (int i = barIndex; i < barIndex + loopback; i++) - { - // - tmpBar.Clean(); - tmpPivot.Clean(); - - // - has = tmpBar.Init(tmpSymbol, tmpPeriod, i); - if (!has) - { - continue; - } - - // - // XSAR ... - isBullish = IsSARSwitchedToBullish(i); - isBearish = IsSARSwitchedToBearish(i); - has = isBullish || isBearish; - if (has) - { - } - - // - // XMA Fast / Slow ... - - // - // States ... - isBullish = IsMASlowSwitchedToBullish(i); - isBearish = IsMASlowSwitchedToBearish(i); - has = isBullish || isBearish; - if (has) - { - } - - // - // Crossed Fast Slow ... - isBullish = IsMAFastCrossedOverSlow(i); - isBearish = IsMAFastCrossedUnderSlow(i); - has = isBullish || isBearish; - if (has) - { - } - - // - // Crossed Last ... - isBullish = IsMASlowCrossedOverLast(i); - isBearish = IsMASlowCrossedUnderLast(i); - has = isBullish || isBearish; - if (has) - { - } - - // - // XHK ... - isBullish = IsHKSwitchedToBullish(i); - isBearish = IsHKSwitchedToBearish(i); - has = isBullish || isBearish; - if (has) - { - } - } - - // - result = ArraySize(pivots); - - // - return result; -} - -// -// -// - - -/** - * an strucutre to Model Specified Leg Pattern ... - **/ -struct XLeg -{ - // - // Props ... - - // - datetime time; - string symbol; - ENUM_X_DIRECTION dir; - ENUM_TIMEFRAMES period; - - // - double upper; - double lower; - - // - XOHCL bullishBars[]; - XOHCL bearishBars[]; - - // - XBoxZone supports[]; - XBoxZone resistances[]; - - // - XBoxZone bullishFVGs[]; - XBoxZone bearishFVGs[]; - - // - XPatternAnalysis patterns[]; - - // - int sequentialBullishBars; - int sequentialBearishBars; - - // - // Constructor ... - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - time = NULL; - symbol = NULL; - period = NULL; - dir = X_DIRECTION_NONE; - - // - upper = 0; - lower = 0; - sequentialBullishBars = 0; - sequentialBearishBars = 0; - - // - XClean(patterns); - XClean(supports); - XClean(bullishBars); - XClean(bearishBars); - XClean(resistances); - XClean(bullishFVGs); - XClean(bearishFVGs); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - IsXValid(time) && - IsXValid(symbol) && - IsXValid(period) && - HasDirection(dir) && - NotEmptyZero(upper) && - NotEmptyZero(lower) && - upper > lower; - - // - return result; - } - - /** - * Check is Bullish ... - * - * @return ( bool ) - */ - bool IsBullish() - { - return IsValid() && - IsXBullish(dir); - } - - /** - * Check is Bearish ... - * - * @return ( bool ) - */ - bool IsBearish() - { - return IsValid() && - IsXBearish(dir); - } - - /** - * Converts a Leg to XBoxZone ... - * - * @param zone: XBoxZone, reference to holds Converted ... - * - * @return ( bool ) - */ - bool ToBox(XBoxZone &zone) - { - // - bool result = false; - - // - // Prepare ... - zone.Clean(); - - // - // Validate ... - result = IsValid(); - if (!result) - { - return result; - } - - // - zone.at = time; - zone.dir = dir; - zone.from = time; - zone.upper = upper; - zone.lower = lower; - zone.symbol = symbol; - zone.period = period; - zone.to = TimeCurrent(); - zone.type = ToXString(X_BAR_PATTERN_LEG); - - // - result = zone.IsValid(); - - // - // Cleanup ... - if (!result) - { - zone.Clean(); - } - - // - return result; - } - - /** - * Update Times of Collections ... - * - * @param value: datetime, Specified Time ... - */ - void UpdateTimes(datetime value = NULL) - { - // - // Normalize ... - value = NormalizeTime(value); - - // - // Validate ... - if (!IsValid()) - { - return; - } - - // - UpdateToTime(supports, value); - UpdateToTime(resistances, value); - UpdateToTime(bullishFVGs, value); - UpdateToTime(bearishFVGs, value); - } - - // -};