diff --git a/Documents/BKP/tmp.base.signal.class.mq5 b/Documents/BKP/tmp.base.signal.class.mq5 deleted file mode 100644 index 7ddfc929..00000000 --- a/Documents/BKP/tmp.base.signal.class.mq5 +++ /dev/null @@ -1,214 +0,0 @@ - -// -// a Base Class by Support Alert ... -class XCBaseAlert : public XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - // Constructor(s) ... - void XCBaseAlert() - { - // - // Instance Alert ... - mAlert = new XCAlert(); - } - - // - // Deconstructors ... - void ~XCBaseAlert() - { - // - delete mAlert; - - // - ZeroMemory(mAlert); - } - - // - // Alert Handler Functions ... - - // - // Alert Functions Getter(s) / Setters(s) ... - - // - string GetAlertPrefix() - { - return mAlert.GetPrefix(); - } - - // - void SetAlertPrefix(string value) - { - mAlert.SetPrefix(value); - } - - // - bool GetAlertLogAlerts() - { - return mAlert.GetLogAlerts(); - } - - // - void SetAlertLogAlerts(bool value) - { - mAlert.SetLogAlerts(value); - } - - // - bool GetAlertEnableAlerts() - { - return mAlert.GetEnableAlerts(); - } - - // - void SetAlertEnableAlerts(bool value) - { - mAlert.SetEnableAlerts(value); - } - - // - bool GetAlertPushAlerts() - { - return mAlert.GetPushAlerts(); - } - - // - void SetAlertPushAlerts(bool value) - { - mAlert.SetPushAlerts(value); - } - - // - bool GetAlertMailAlerts() - { - return mAlert.GetMailAlerts(); - } - - // - void SetAlertMailAlerts(bool value) - { - mAlert.SetMailAlerts(value); - } - - // - bool GetAlertTerminalAlerts() - { - return mAlert.GetTerminalAlerts(); - } - - // - void SetAlertTerminalAlerts(bool value) - { - mAlert.SetTerminalAlerts(value); - } - - // - // Alert Actions ... - - // - // Logging an Alert ... - void LogAlert(string message) - { - mAlert.LogAlert(message); - } - - // - // Terminal Alert ... - void TerminalAlert(string message) - { - mAlert.TerminalAlert(message); - } - - // - // Mail Alert ... - void MailAlert(string message) - { - mAlert.MailAlert(message); - } - - // - // Send Push Notification ... - void PushAlert(string message) - { - mAlert.PushAlert(message); - } - - // - // Send an Alert by Handling all Different Specified - // type's of Alert's if they are Enabled ... - void SendAlert(string message) - { - mAlert.SendAlert(message); - } - - // - // Logs ... - - // - // Log a Message ... - void Log(string message) - { - mAlert.Log(message); - } - void Log(string tag, string message) - { - mAlert.Log(tag, message); - } - void LogEmpty() - { - mAlert.LogEmpty(); - } - - // - // Log Specific Array ... - template - void LogArray( - T &array[], // Array to Log - string label = NULL // Array Label - ) - { - mAlert.LogArray(array, label); - } - - // - // Error ... - - // - // Log an Error ... - void LogError( - int error = -1 // Specific Error, if it's equal to -1, use Last Error ... - ) - { - mAlert.LogError(error); - } - - // - // Retrieve Specified Error Code Description ... - string GetErrorDescription(int err_code) - { - return mAlert.GetErrorDescription(err_code); - } - - // - // Retrieve Specified Error Code Description ... - string GetTradeServerReturnCodeDescription(int return_code) - { - return mAlert.GetTradeServerReturnCodeDescription(return_code); - } - - // - // Protected ... - protected: - // - // Alert ... - XCAlert *mAlert; - - // - // Private ... - private: -}; diff --git a/Documents/BKP/tmp.conditionalling.signalling.mq5 b/Documents/BKP/tmp.conditionalling.signalling.mq5 deleted file mode 100644 index 41babe83..00000000 --- a/Documents/BKP/tmp.conditionalling.signalling.mq5 +++ /dev/null @@ -1,1433 +0,0 @@ - XBoxZone iPeak; - XBoxZone iVale; - XBoxZone iOBBull; - XBoxZone iOBBear; - XBoxZone iMTBull; - XBoxZone iMTBear; - - // - iPeak.Clean(); - iVale.Clean(); - iOBBull.Clean(); - iOBBear.Clean(); - iMTBull.Clean(); - iMTBear.Clean(); - - // - // Select MT Block ... - // if (result) - // { - // // - // // New MT Pivot Detected ... - // if (detector.newMTBullishPivotDetected) - // { - // // - // idx = GetYoungest(detector.mtBullishPivots); - // if (IsValidIndex(idx)) - // { - // iMTBull = detector.mtBullishPivots[idx]; - // } - // } - // else if (detector.newMTBearishPivotDetected) - // { - // // - // idx = GetYoungest(detector.mtBearishPivots); - // if (IsValidIndex(idx)) - // { - // iMTBear = detector.mtBearishPivots[idx]; - // } - // } - - // // - // // Draw MT ... - - // // - // // Bullish ... - // has = iMTBull.IsValid(); - // if (has) - // { - // // - // iMTBull.to = conditions.bars[zIDX].time; - - // // - // XCBoxObject *iObj; - // has = drawer - // .drawer - // .DrawBox( - // iMTBull, - // iObj // - // ); - // if (has) - // { - // drawer.ApplyMTBullishPivotStyle(iObj); - // } - // } - - // // - // // Bearish ... - // has = iMTBear.IsValid(); - // if (has) - // { - // // - // iMTBear.to = conditions.bars[zIDX].time; - - // // - // XCBoxObject *iObj; - // has = drawer - // .drawer - // .DrawBox( - // iMTBear, - // iObj // - // ); - // if (has) - // { - // drawer.ApplyMTBearishPivotStyle(iObj); - // } - // } - // } - - // - // Select Peak and Vale ... - // this used to Signalling Better ... - // if (result) - // { - // // - // // Select Peak ... - // idx = GetLowest( - // conditions.bars[cIDX], - // detector.peakPivots // - // ); - // if (IsValidIndex(idx)) - // { - // // - // iPeak = detector.peakPivots[idx]; - // iPeak.to = conditions.bars[zIDX].time; - // } - - // // - // // Select Vale ... - // idx = GetHighest( - // conditions.bars[cIDX], - // detector.valePivots // - // ); - // if (IsValidIndex(idx)) - // { - // // - // iVale = detector.valePivots[idx]; - // iVale.to = conditions.bars[zIDX].time; - // } - - // // - // // Checkig Result ... - // result = - // iPeak.IsValid() && - // iVale.IsValid(); - - // // - // // Draw Peak and Vales ... - // if (result) - // { - // // - // // Object Definitions ... - // XCBoxObject *iObj; - - // // - // // Draw Peak ... - // has = drawer - // .drawer - // .DrawBox( - // iPeak, - // iObj // - // ); - // if (has) - // { - // drawer.ApplyPeakPivotStyle(iObj); - // } - // ZeroMemory(iObj); - - // // - // // Draw Vale ... - // has = drawer - // .drawer - // .DrawBox( - // iVale, - // iObj // - // ); - // if (has) - // { - // drawer.ApplyValePivotStyle(iObj); - // } - // ZeroMemory(iObj); - // } - // } - - - // // - // // We Have to Detect Youngest Order Block ... - // // or Mitigation Block ... - // if (isCond1Bullish) - // { - // // // - // // // OB ... - // // idx = GetYoungest(detector.obBullishPivots); - // // has = IsValidIndex(idx); - // // if (has) - // // { - // // iOB = detector.obBullishPivots[idx]; - // // } - - // // - // // MT ... - // idx = GetYoungest(detector.mtBullishPivots); - // has = IsValidIndex(idx); - // if (has) - // { - // iOB = detector.mtBullishPivots[idx]; - // } - // } - // else if (isCond1Bearish) - // { - // // - // // OB - // // idx = GetYoungest(detector.obBearishPivots); - // // has = IsValidIndex(idx); - // // if (has) - // // { - // // iOB = detector.obBearishPivots[idx]; - // // } - - // // - // // MT - // idx = GetYoungest(detector.mtBearishPivots); - // has = IsValidIndex(idx); - // if (has) - // { - // iMT = detector.mtBearishPivots[idx]; - // } - // } - - // // - // // Now we can Do some Verifications Using these ... - // result = - // isCond1Bullish - // ? iMT.IsBullish() - // : iMT.IsBearish(); - // if (!result) - // { - // // - // isCond1Bullish = false; - // isCond1Bearish = false; - // } - - // - // All Requirements based on Cond 1 ... - -/////////////////////////////////////////////////////////////// - - // - XOHCL pBar; - has = bar.GetPreviousBar(pBar); - if (has) - { - // - ENUM_X_DIRECTION seqDir; - - // - bool isSeqBreaked = barAnalyser - .IsSeqBreak( - pBar, - seqDir // - ); - bool isBullishSeqBreaked = - isSeqBreaked && - IsBullish(seqDir); - bool isBearishSeqBreaked = - isSeqBreaked && - IsBearish(seqDir); - - // - if (isSeqBreaked) - { - Print("Detect Sequence Breaker Bar ..."); - } - } - pBar.Clean(); - -/////////////////////////////////////////////////////////////// - - - /** - * Detect Spike ... - * - * @param bar: XOHCL instance reference, Start Bar ... - * @param dir: ENUM_X_DIRECTION member, Event Direction ... - * @param type: ENUM_X_PRICE member, Price Type ... - * @param forcBodyInRange: bool, Use Body in Range Detection ... - * @param rangeExtendMultiplier: double, a Multiplier for Checking Price Range ... - * @param sameBars: int, Specified How Many Same Bars Required for an Spike ... - * - * @return ( bool ) - */ - bool IsSpike( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - int &rootIDX, - ENUM_X_PRICE type = X_PRICE_CLOSE, - bool forcBodyInRange = true, - double rangeExtendMultiplier = 2.0, - int sameBars = 3 // - ) - { - // - bool result = false; - - // - dir = X_DIRECTION_NONE; - sameBars = NormalizeInt(sameBars, 2); - - // - result = IsValid(type) && - bar.IsValid(); - if (!result) - { - return result; - } - - // - // First We Have to Has a Big Change ... - int sharpRootIDX = -1; - result = IsSharp( - bar, - dir, - sharpRootIDX, - type, - forcBodyInRange, - rangeExtendMultiplier // - ); - if (!result) - { - return result; - } - - // - // Check Has Same Bars ... - int sameBarsIndex = -1; - ENUM_X_DIRECTION sameBarsDir; - result = HasSameBars( - bar, - sameBarsDir, - sameBarsIndex, - sameBars // - ); - if (!result) - { - return result; - } - - // - // Check Same Bars Direction sames To Price Change ... - result = sameBarsDir == dir; - if (!result) - { - return result; - } - - // - rootIDX = sharpRootIDX; - - // - return result; - } - - /** - * Check a Bar is Support Bar or not ... - * - * @param bar: XOHCL instance ... - * @param supportBar: XOHCL instance, Provides Fouded Support Bar ... - * @param range: Integer, Specified Verifiation Range ... - * - * @return ( bool ) - */ - bool HasSupport( - XOHCL &bar, - XOHCL &supportBar, - int range = 21 // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int supportIDX = bar.Index() + range; - result = supportBar.Init( - bar.symbol, - bar.period, - supportIDX // - ); - if (!result) - { - // - supportBar.Clean(); - return result; - } - - // - result = bar.low > supportBar.low; - if (!result) - { - // - supportBar.Clean(); - return result; - } - - // - // Validate Point ... - for (int i = 1; i < range; i++) - { - // - XOHCL iPBar; - XOHCL iNBar; - bool iHas = false; - - // - iHas = iPBar.Init( - bar.symbol, - bar.period, - supportIDX + i // - ); - result = iHas; - if (!result) - { - break; - } - - // - iHas = iNBar.Init( - bar.symbol, - bar.period, - supportIDX - i // - ); - result = iHas; - if (!result) - { - break; - } - - // - result = supportBar.low < iPBar.low && - supportBar.low < iNBar.low; - if (!result) - { - break; - } - } - - // - return result; - } - - /** - * Check a Bar is Resistance Bar or not ... - * - * @param bar: XOHCL instance ... - * @param resistanceBar: XOHCL instance, Provides Fouded Support Bar ... - * @param range: Integer, Specified Verifiation Range ... - * - * @return ( bool ) - */ - bool HasResistance( - XOHCL &bar, - XOHCL &resistanceBar, - int range = 21 // - ) - { - // - bool result = false; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int resistanceIDX = bar.Index() + range; - result = resistanceBar.Init( - bar.symbol, - bar.period, - resistanceIDX // - ); - if (!result) - { - // - resistanceBar.Clean(); - return result; - } - - // - result = bar.high < resistanceBar.high; - if (!result) - { - // - resistanceBar.Clean(); - return result; - } - - // - // Validate Point ... - for (int i = 1; i < range; i++) - { - // - XOHCL iPBar; - XOHCL iNBar; - bool iHas = false; - - // - iHas = iPBar.Init( - bar.symbol, - bar.period, - resistanceIDX + i // - ); - result = iHas; - if (!result) - { - break; - } - - // - iHas = iNBar.Init( - bar.symbol, - bar.period, - resistanceIDX - i // - ); - result = iHas; - if (!result) - { - break; - } - - // - result = resistanceBar.high > iPBar.high && - resistanceBar.high > iNBar.high; - if (!result) - { - break; - } - } - - // - return result; - } - - /** - * Detect a Fair Value Gap Based on Given Bar ... - * - * @param bar: XOHCL instance, Specified Start Bar ... - * @param fromBar: XOHCL instance, Provides Start Bar of FVG ... - * @param toBar: XOHCL instance, Provides End Bar of FVG ... - * @param dir: ENUM_X_DIRECTION member, Specified Founded Order Block Direction ... - * @param sameBars: Integer, Specified Min Same Bars for Detecting Order Block ... - * @return ( bool ) - */ - bool HasFairValueGap( - XOHCL &bar, - XOHCL &fromBar, - XOHCL &toBar, - ENUM_X_DIRECTION &dir, - int sameBars = 3 // - ) - { - // - bool result = false; - - // - toBar.Clean(); - fromBar.Clean(); - dir = X_DIRECTION_NONE; - sameBars = NormalizeInt(sameBars, 1); - - // - result = bar.IsValid(); - if (!result) - { - // - toBar.Clean(); - fromBar.Clean(); - return result; - } - - // - int index = 0; - result = HasSameBars( - bar, - dir, - index, - sameBars // - ); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(dir); - - // - int to = bar.Index(); - int from = - index > (to + sameBars) - ? to + sameBars - : index; - for (int i = from; i > to; i--) - { - // - result = fromBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!result) - { - break; - } - - // - result = toBar.Init( - bar.symbol, - bar.period, - i - 2 // - ); - if (!result) - { - break; - } - - // - result = isBullish - ? fromBar.high < toBar.low - : fromBar.low > toBar.high; - if (result) - { - break; - } - } - - // - if (!result) - { - // - toBar.Clean(); - fromBar.Clean(); - dir = X_DIRECTION_NONE; - } - - // - return result; - } - - /** - * Detect an Order Block Based on Given Bar ... - * - * @param bar: XOHCL instance, Specified Start Bar ... - * @param ob: XOHCL instance, Fill it if Order Block Found ... - * @param dir: ENUM_X_DIRECTION member, Specified Founded Order Block Direction ... - * @param sameBars: Integer, Specified Min Same Bars for Detecting Order Block ... - * - * @return ( bool ) - */ - bool HasOrderBlock( - XOHCL &bar, - XOHCL &ob, - ENUM_X_DIRECTION &dir, - int sameBars = 3, - bool forceSpike = true, - bool forceFairValueGap = true, - bool forceSupportResistance = true // - ) - { - // - bool result = false; - - // - ob.Clean(); - dir = X_DIRECTION_NONE; - sameBars = NormalizeInt(sameBars, 1); - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = bar.GetPreviousBar(sBar); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - // First Step We Have to Check Same Bars ... - int spikeRootIDX = -1; - int sameBarsIndex = -1; - result = HasSameBars( - bar, - dir, - sameBarsIndex, - sameBars // - ); - if (!result) - { - // - ob.Clean(); - return result; - } - - // - // Must an Spike Happens ... - if (forceSpike) - { - // - ENUM_X_DIRECTION spikeDir; - result = IsSpike( - bar, - spikeDir, - spikeRootIDX, // Spike Root Index ... - X_PRICE_CLOSE, // Price Type ... - true, // Force Body ... - 1.5, // Range Extend Multiplier ... - sameBars // - ); - result = - result && - dir == spikeDir; - if (!result) - { - // - ob.Clean(); - return result; - } - } - - // - // Select OB Candidate Bars ... - - XOHCL sameBar; - XOHCL rootBar; - XOHCL rootPBar; - result = sameBar.Init( - bar.symbol, - bar.period, - sameBarsIndex + 1 // - ); - if (!result) - { - // - sBar.Clean(); - sameBar.Clean(); - return result; - } - result = rootBar.Init( - bar.symbol, - bar.period, - spikeRootIDX // - ); - if (!result) - { - // - sBar.Clean(); - rootBar.Clean(); - sameBar.Clean(); - return result; - } - result = rootBar.GetPreviousBar(rootPBar); - if (!result) - { - // - sBar.Clean(); - rootBar.Clean(); - sameBar.Clean(); - rootPBar.Clean(); - return result; - } - - // - // Select ob Bar ... - if (rootBar.GetDirection() == Opposit(dir)) - { - ob = rootBar; - } - else if (rootPBar.GetDirection() == Opposit(dir)) - { - ob = rootPBar; - } - else if (sameBar.GetDirection() == Opposit(dir)) - { - ob = sameBar; - } - else - { - ob.Clean(); - } - - // - // Select Order Block Bar ... - result = ob.IsValid(); - ENUM_X_DIRECTION obDir = ob.GetDirection(); - result = - result && - dir == Opposit(obDir); - if (!result) - { - // - sBar.Clean(); - rootBar.Clean(); - sameBar.Clean(); - rootPBar.Clean(); - - // - return result; - } - - // - // if Bullish OB => Supports ... - // if Bearish OB => Resistance ... - if (forceSupportResistance) - { - // - XOHCL supResBar; - - // - // Check Support ... - bool isSupport = HasSupport( - ob, - supResBar // - ); - - // - // Check Resistance ... - bool isResistance = HasResistance( - ob, - supResBar // - ); - - // - supResBar.Clean(); - - // - result = - result && - (IsBullish(dir) - ? isSupport - : isResistance); - - // - if (!result) - { - // - ob.Clean(); - sBar.Clean(); - rootBar.Clean(); - sameBar.Clean(); - rootPBar.Clean(); - - // - return result; - } - } - - // - // Force Check Fair ValueGaps ... - if (forceFairValueGap) - { - // - XOHCL toBar; - XOHCL fromBar; - ENUM_X_DIRECTION fvgDir; - bool isFVG = HasFairValueGap( - bar, - fromBar, - toBar, - fvgDir, - sameBars // - ); - - // - result = - isFVG && - result && - dir == fvgDir; - - // - toBar.Clean(); - fromBar.Clean(); - } - - // - // Cleanup Resource ... - - // - sBar.Clean(); - rootBar.Clean(); - sameBar.Clean(); - rootPBar.Clean(); - - // - return result; - } - - /** - * Check a Bar has Consolidation Zone or not ... - * - * @param bar: XOHCL instance, Specified Start Bar ... - * @param zone: XConsolidationZone instance, consolidation Zone Object ... - * @param minLoopback: int, min Allowed Lopback for Consolidating ... - * @param range: double, Consolidation Range ... - * @param upperAppliedTo: ENUM_X_PRICE member, Upper Selection Price ... - * @param lowerAppliedTo: ENUM_X_PRICE member, Lower Selection Price ... - * - * @return ( bool ) - */ - bool HasConsolidationZone( - XOHCL &bar, - XConsolidationZone &zone, - int minLoopback = 7, - double range = 50, - ENUM_X_PRICE upperAppliedTo = X_PRICE_HIGH, - ENUM_X_PRICE lowerAppliedTo = X_PRICE_LOW // - ) - { - // - bool result = false; - - // - zone.Clean(); - range = NormalizeDouble(range, 50); - minLoopback = NormalizeInt(minLoopback, 7); - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - double points = GetPoints(bar.symbol); - int index = bar.Index() + 1; - int length = minLoopback; - - // - double upperPrice[]; - int upperPriceCount = FillPrice( - upperPrice, - bar, - length, - upperAppliedTo // - ); - - // - double lowerPrice[]; - int lowerPriceCount = FillPrice( - lowerPrice, - bar, - length, - lowerAppliedTo // - ); - - // - result = upperPriceCount == lowerPriceCount && - lowerPriceCount == length; - if (!result) - { - // - Clean(upperPrice); - Clean(lowerPrice); - - // - return result; - } - - // - double upper = upperPrice[ArrayMaximum(upperPrice)]; - double lower = lowerPrice[ArrayMinimum(lowerPrice)]; - - // - bool isBullishBreake = - bar.low > lower && - bar.high > upper && - bar.GetUp() > upper; - bool isBearishBreake = - bar.high < upper && - bar.low < lower && - bar.GetDown() < lower; - result = isBullishBreake || - isBearishBreake; - if (!result) - { - // - Clean(upperPrice); - Clean(lowerPrice); - - // - return result; - } - - // - double delta = upper - lower; - result = delta <= range * points; - if (!result) - { - // - Clean(upperPrice); - Clean(lowerPrice); - - // - return result; - } - - // - while (delta <= range * points) - { - // - length++; - - // - upperPriceCount = FillPrice( - upperPrice, - bar, - length, - upperAppliedTo // - ); - - // - lowerPriceCount = FillPrice( - lowerPrice, - bar, - length, - lowerAppliedTo // - ); - - // - bool isValid = upperPriceCount == lowerPriceCount && - lowerPriceCount == length; - if (!isValid) - { - break; - } - - // - double iUpper = upperPrice[ArrayMaximum(upperPrice)]; - double iLower = lowerPrice[ArrayMinimum(lowerPrice)]; - - // - delta = iUpper - iLower; - if (delta <= range * points) - { - // - upper = iUpper; - lower = iLower; - } - } - - // - Clean(upperPrice); - Clean(lowerPrice); - - // - // Filling Zone ... - zone.upper = upper; - zone.lower = lower; - zone.symbol = bar.symbol; - zone.period = bar.period; - zone.to = iTime( - bar.symbol, - bar.period, - bar.Index() + 1 // - ); - zone.from = iTime( - bar.symbol, - bar.period, - bar.Index() + length // - ); - zone.dir = isBullishBreake - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - result = zone.IsValid(); - if (!result) - { - zone.Clean(); - } - - // - return result; - } - -/////////////////////////////////////////////////////////////////// - - // - // DOJI ... - bool isDoji = IsDoji( - bar, - iDir // - ); - bool isBullishDoji = - isDoji && - IsBullish(iDir); - bool isBearishDoji = - isDoji && - IsBearish(iDir); - - // - // SWING ... - bool isSwing = IsSwing( - bar, - iDir // - ); - bool isBullishSwing = - isSwing && - IsBullish(iDir); - bool isBearishSwing = - isSwing && - IsBearish(iDir); - - // - // HAMMER ... - bool isHammer = IsHammer( - bar, - iDir // - ); - bool isBullishHammer = - isHammer && - IsBullish(iDir); - bool isBearishHammer = - isHammer && - IsBearish(iDir); - - // - // ENGULF ... - bool isEngulfed = IsEngulfed( - bar, - iDir // - ); - bool isBullishEngulfed = - isEngulfed && - IsBullish(iDir); - bool isBearishEngulfed = - isEngulfed && - IsBearish(iDir); - - // - // REJECTED ... - bool isRejected = IsRejected( - bar, - iDir // - ); - bool isBullishRejected = - isRejected && - IsBullish(iDir); - bool isBearishRejected = - isRejected && - IsBearish(iDir); - - // - // MOMENTUM ... - bool isMomentum = IsMomentum( - bar, - iDir // - ); - bool isBullishMomentum = - isMomentum && - IsBullish(iDir); - bool isBearishMomentum = - isMomentum && - IsBearish(iDir); - - // - // Summarize Conditions ... - - // - bool isBullishOr = - isBullishDoji || - isBullishSwing || - isBullishHammer || - isBullishEngulfed || - isBullishRejected || - isBullishMomentum; - - // - bool isBearishOr = - isBearishDoji || - isBearishSwing || - isBearishHammer || - isBearishEngulfed || - isBearishRejected || - isBearishMomentum; - - // - bool isBullish = - isBullishOr && - !isBearishOr; - - // - bool isBearish = - !isBullishOr && - isBearishOr; - -/////////////////////////////////////////////////////////////////// - - bool IsVPattern( - XOHCL &bar, - ENUM_X_DIRECTION &dir, - ENUM_X_PRICE pType = X_PRICE_CLOSE, - int loopback = 3 // - ) - { - // - bool result = false; - - // - // Normalize Args ... - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 3); - - // - // Loopback Must an Odd Number ... - // here we Validate and Normalize it ... - double iLoopbackCheck = ((double)(loopback - 1)) / 2; - if (iLoopbackCheck != 0) - { - loopback++; - } - - // - // Validate Args ... - result = - bar.IsValid() && - IsValid(pType); - if (!result) - { - return result; - } - - // - XOHCL iBar; - int index = -1; - XOHCL iSwingBar; - double prices[]; - bool has = false; - double iPrice = 0; - int pricesCount = 0; - int swingBarIDX = -1; - int loopbackHalf = 0; - bool isBullish = false; - bool isBearish = false; - bool hasBullishSeq = false; - bool hasBearishSeq = false; - - // - if (result) - { - // - // Retrieve Price Type Collection ... - index = bar.Index(); - pricesCount = FillPrice( - prices, - bar, - loopback, - pType // - ); - result = pricesCount == loopback; - if (result) - { - // - loopbackHalf = (loopback - 1) / 2; - swingBarIDX = index + loopbackHalf + 1; - has = IsValidIndex(swingBarIDX); - - // - // Check for Bullish and Bearish ... - if (has) - { - // - hasBullishSeq = true; - hasBearishSeq = true; - iPrice = prices[swingBarIDX]; - for (int i = 0; i < loopbackHalf - 1; i++) - { - // - // Side Values ... - - // - // Prev ... - double iPPrice = prices[swingBarIDX + i]; - double iP2Price = prices[swingBarIDX + i + 1]; - - // - // Next ... - double iNPrice = prices[swingBarIDX - i]; - double iN2Price = prices[swingBarIDX - i - 1]; - - // - if (hasBullishSeq) - { - // - // For Bullish Seq ... - // Prevs Must: iPPrice < iP2Price - // Nexts Must: iNPrice < iN2Price - hasBullishSeq = - iPrice < iPPrice && - iPrice < iNPrice && - iPPrice <= iP2Price && - iNPrice <= iN2Price; - } - - // - if (hasBearishSeq) - { - // - // For Bearish Seq ... - // Prevs Must: iPPrice > iP2Price - // Nexts Must: iNPrice > iN2Price - hasBearishSeq = - iPrice > iPPrice && - iPrice > iNPrice && - iPPrice >= iP2Price && - iNPrice >= iN2Price; - } - - // - if (!hasBullishSeq && - !hasBearishSeq) - { - break; - } - } - } - - // - result = - has && - (hasBullishSeq || - hasBearishSeq); - } - } - - // - // Here we Make Sure the Propper Sequence is Exists ... - if (result) - { - // - // Try to Check onther Conditions ... - has = iSwingBar.Init( - bar.symbol, - bar.period, - swingBarIDX // - ); - - // - if (has) - { - // - // Draw Requirement to Now ... - string iName = "S_1"; - datetime iTime = iSwingBar.time; - - // - CChartObjectVLine *iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - iTime // - ); - - // - iName = "SP_1"; - iTime = GetBarTime( - bar.symbol, - bar.period, - swingBarIDX + loopbackHalf); - CChartObjectVLine *iObj1 = new CChartObjectVLine(); - has = iObj1.Create( - 0, - iName, - 0, - iTime // - ); - - // - Print("Salam ..."); - } - } - - // - // Summarize Result ... - result = isBullish || - isBearish; - if (result) - { - // - dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resource ... - iBar.Clean(); - iSwingBar.Clean(); - - // - return result; - } - -/////////////////////////////////////////////////////////////////// - -template -bool IsBoolean(T value) -{ - // - bool result = false; - - // - string normalizedValue = ToString(value); - StringToLower(normalizedValue); - normalizedValue = Trim(normalizedValue); - - // - result = - !IsValid(normalizedValue) - ? false - : (normalizedValue == "true" || - normalizedValue == "false"); - - // - return result; -} - -/////////////////////////////////////////////////////////////////// - diff --git a/Documents/BKP/x-saherelm.x-expert.class.mq5 b/Documents/BKP/x-saherelm.x-expert.class.mq5 deleted file mode 100644 index ac4719e8..00000000 --- a/Documents/BKP/x-saherelm.x-expert.class.mq5 +++ /dev/null @@ -1,967 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XCBaseExpert -// Description: provides all based classes for use ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" - -// -// Definitions ... -string XCBaseExpertToken = "XCBaseEA"; - -// -// Inputs ... - -// -// Implementations ... -class XCBaseExpert : public XCBaseAlert -{ - // - public: - // - - // - XCTrade *mTrader; // Trader of Expert Adviser ... - - // - // Constructur(s) ... - void XCBaseExpert() - { - } - - // - // Deconstructor ... - void ~XCBaseExpert() - { - // - delete mTrader; - - // - ZeroMemory(mTrader); - } - - // - // Getter(s) / Setter(s) ... - - // - // Common ... - - /** - * Get Magic Number ... - * - * @return ( long ) - */ - long MagicNumber() - { - return mMagicNumber; - } - - /** - * Set Magic Number ... - * - * @param value: Long ... - */ - void MagicNumber(long value) - { - // - mMagicNumber = value; - ReConfigure(); - } - - /** - * Get Slippage ... - * - * @return ( int ) - */ - int Slippage() - { - return mSlippage; - } - - /** - * Set Slippage ... - * - * @param value: Integer ... - */ - void Slippage(int value) - { - // - mSlippage = value; - ReConfigure(); - } - - /** - * Get Tag Prefix ... - * - * @return ( string ) - */ - string TagPrefix() - { - return mTagPrefix; - } - - /** - * Set Tag Prefix ... - * - * @param value: String ... - */ - void TagPrefix(string value) - { - // - mTagPrefix = value; - ReConfigure(); - } - - // - // Symbol ... - - /** - * Get Period ... - * - * @return ( ENUM_TIMEFRAMES ) - */ - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - /** - * Set Period ... - * - * @param value: ENUM_TIMEFRAMES member ... - */ - void SetPeriod(ENUM_TIMEFRAMES value) - { - // - mPeriod = value; - ReConfigure(); - } - - /** - * Get Symbol ... - * - * @return ( string ) - */ - string GetSymbol() - { - return mSymbol; - } - - /** - * Set Symbol ... - * - * @param value: String ... - */ - void SetSymbol(string value) - { - // - mSymbol = value; - ReConfigure(); - } - - /** - * Get Multi Symbol is Enable or Not ... - * - * @return ( bool ) - */ - bool MultiSymbol() - { - return mMultiSymbol; - } - - /** - * Set Multi Symbol is Enable or Not ... - * - * @param value: Boolean ... - */ - void MultiSymbol(bool value) - { - // - mMultiSymbol = value; - ReConfigure(); - } - - /** - * Get Multi Provided Symbols ... - * - * @return ( string ) - */ - string Symbols() - { - return mSymbols; - } - - /** - * Set Multi Provided Symbols ... - * - * @param value: String ... - */ - void Symbols(string value) - { - // - mSymbols = value; - ReConfigure(); - } - - // - // Signalling ... - - /** - * Get Force Disable Signalling ... - * - * @return ( bool ) - */ - bool Disabled() - { - return mDisabled; - } - - /** - * Set Force Disable Signalling ... - * - * @param value: Boolean ... - */ - void Disabled(bool value) - { - // - mDisabled = value; - ReConfigure(); - } - - /** - * Get Allow Long Signals ... - * - * @return ( bool ) - */ - bool AllowLong() - { - return mAllowLong; - } - - /** - * Set Allow Long Signals ... - * - * @param value: Boolean ... - */ - void AllowLong(bool value) - { - // - mAllowLong = value; - ReConfigure(); - } - - /** - * Get Allow Short Signalling ... - * - * @return ( bool ) - */ - bool AllowShort() - { - return mAllowShort; - } - - /** - * Set Allow Short Signalling ... - * - * @param value: Boolean ... - */ - void AllowShort(bool value) - { - // - mAllowShort = value; - ReConfigure(); - } - - // - // Reports ... - - /** - * Get Report New Month State ... - * - * @return ( bool ) - */ - bool ReportNewMonths() - { - return mReportNewMonths; - } - - /** - * Set Report New Month State ... - * - * @param value: Boolean ... - */ - void ReportNewMonths(bool value) - { - // - mReportNewMonths = value; - ReConfigure(); - } - - /** - * Get Report New Weeks State ... - * - * @return ( bool ) - */ - bool ReportNewWeeks() - { - return mReportNewWeeks; - } - - /** - * Set Report New Weeks State ... - * - * @param value: Boolean ... - */ - void ReportNewWeeks(bool value) - { - // - mReportNewWeeks = value; - ReConfigure(); - } - - /** - * Get Report New Days State ... - * - * @return ( bool ) - */ - bool ReportNewDays() - { - return mReportNewDays; - } - - /** - * Set Report New Days State ... - * - * @param value: Boolean ... - */ - void ReportNewDays(bool value) - { - // - mReportNewDays = value; - ReConfigure(); - } - - /** - * Get Report New Hours State ... - * - * @return ( bool ) - */ - bool ReportNewHours() - { - return mReportNewHours; - } - - /** - * Set Report New Hours State ... - * - * @param value: Boolean ... - */ - void ReportNewHours(bool value) - { - // - mReportNewHours = value; - ReConfigure(); - } - - // - // Actions ... - - /** - * Handle Expert OnInit Event ... - * - * @return ( bool ) - */ - bool HandleOnInit() - { - // - bool result = false; - - // - string message = ""; - - // - // Validate Input ... - result = ValidateInputs(); - if (!result) - { - // - message = "Invalid Inputs ...."; - - // - SendAlert(message); - } - - // - // Initial All Requirements ... - result = InitEA(); - if (!result) - { - return result; - } - - // - // Initial All GUI Requirements ... - result = InitGUI(); - if (!result) - { - return result; - } - - // - message = "Initialized Successfully ..."; - SendAlert(message); - - // - return result; - } - - /** - * Handle Expert OnDeInit Event ... - */ - void HandleOnDeInit() - { - // - // Destroy all GUI Requirements ... - DestroyGUI(); - - // - // Alert De Initialization Succeeded ... - string msg = "De Initialized Successfully ..."; - Alert(msg); - - // - // Destroy all EA Requirements ... - DestroyEA(); - } - - /** - * Handle Expert OnTick Event ... - */ - void HandleOnTick() - { - // - UpdateGUI(); - HandleReportTime(); - HandleStrategiesOnTick(); - HandleStrategiesGuard(); - } - - /** - * Handle Expert OnTrade Event ... - */ - void HandleOnTrade() - { - mTrader.HandleOnTrade(); - } - - /** - * Handle Expert OnTimer Event ... - */ - void HandleOnTimer() - { - } - - /** - * Handle Expert OnChart Event ... - */ - void HandleOnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // - ) - { - } - - // - // Virtual Actions ... - - /** - * Apply Default Configurations ... - */ - virtual void DefaultConfigure() - { - // - // Commons ... - Slippage(10); - TagPrefix(""); - MagicNumber(1694056); - - // - // Symbol ... - SetSymbol(_Symbol); - SetPeriod(_Period); - MultiSymbol(false); - Symbols("EURUSDb,GBPUSDb,USDJPYb,USDCHFb,DowJones30,XAUUSDb"); - - // - // Signalling ... - Disabled(false); - AllowLong(true); - AllowShort(true); - - // - string tag = GetTag(); - - // - // Alert ... - SetAlertPrefix(tag); - SetAlertLogAlerts(true); - SetAlertPushAlerts(true); - SetAlertMailAlerts(false); - SetAlertEnableAlerts(true); - SetAlertTerminalAlerts(false); - - // - // Reports ... - ReportNewDays(true); - ReportNewWeeks(false); - ReportNewHours(false); - ReportNewMonths(false); - } - - /** - * Vaslidate Inputs ... - * - * @return ( virtual bool ) - */ - virtual bool ValidateInputs() - { - // - bool result = false; - - // - string errMessage = ""; - - // - bool isCommonValid = ( - // - mSlippage > 0 && - mMagicNumber > 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 ... - errMessage = " Errors: \n" + errMessage; - SendAlert(errMessage); - } - - // - return result; - } - - // - // Initializers and DeInitializers ... - - /** - * Initial EA Requirements ... - * - * @return ( virtual bool ) - */ - virtual bool InitEA() - { - // - bool result = false; - - // - // Initialize Indicator Helpers ... - - // - // Create Trader Instance and Configure it ... - mTrader = new XCTrade( - mSlippage, - mMagicNumber // - ); - - // - return result; - } - - /** - * Destroy Initialized Requirements ... - */ - virtual void DestroyEA() - { - // - delete mTrader; - - // - ZeroMemory(mTrader); - } - - /** - * GUI Initialize if required ... - * - * @return ( virtual bool ) - */ - virtual bool InitGUI() - { - // - bool result = false; - - // - result = true; - - // - return result; - } - - /** - * Update All GUI Contents ... - */ - virtual void UpdateGUI() - { - } - - /** - * Destroy all Initialized GUi Elements ... - */ - virtual void DestroyGUI() - { - } - - // - // Event Handlers ... - - /** - * Calls When a Position's SL Triggered ... - * - * @param deal: XDeal instance ... - */ - virtual void HandleOnStopLossTriggered(const XDeal &deal) - { - HandleReportBalance(); - } - - /** - * Calls When a Position's TP Triggered ... - * - * @param deal: XDeal instance ... - */ - virtual void HandleOnTakeProfitTriggered(const XDeal &deal) - { - HandleReportBalance(); - } - - /** - * Handle Force Close a Position ... - * - * @param ticket: Position Ticket ... - * @param position: XPosition ... - * @param comment: Closing Comment ... - */ - virtual void HandleOnPositionForceClosed( - const ulong ticket, - const XPosition &position, - const string comment // - ) - { - HandleReportBalance(); - } - - /** - * Handle Position Modified ... - * - * @param ticket: ULONG ... - * @param profit: Double ... - * @param comment: String ... - */ - virtual void HandleOnPositionModified( - const ulong ticket, - const double profit, - const string comment // - ) - { - } - - /** - * Handle Position Partially Closed ... - * - * @param ticket: ULONG ... - * @param profit: Double ... - * @param comment: String ... - */ - virtual void HandleOnPositionPartialClosed( - const ulong ticket, - const double profit, - const string comment // - ) - { - } - - /** - * Handle Deals Changed ... - * - * @param count: Integer, Number of Changes ... - */ - virtual void HandleOnDealsChanged(int count) - { - } - - /** - * Handle Orders Changed ... - * - * @param count: Integer, Number of Changes ... - */ - virtual void HandleOnOrdersChanged(int count) - { - } - - /** - * Handle Positions Changed ... - * - * @param count: Integer, Number of Changes ... - */ - virtual void HandleOnPositionsChanged(int count) - { - } - - /** - * Do All Signalling Processing Here ... - */ - virtual void HandleStrategiesOnTick() - { - } - - /** - * Check Strategies for Guards and then Apply Them ... - */ - virtual void HandleStrategiesGuard() - { - } - - // - // Time Handlers ... - - virtual void HandleOnNewMonth() - { - } - - virtual void HandleOnNewWeek() - { - } - - virtual void HandleOnNewDay() - { - } - - virtual void HandleOnNewHour() - { - } - - virtual void ReConfigure() - { - } - - /** - * Generate Identifier Tag ... - * - * @return ( virtual string ) - */ - virtual string GetTag() - { - // - string result = NULL; - - // - string tagPrefix = TagPrefix(); - if (IsValid(tagPrefix)) - { - result = tagPrefix; - } - else - { - result = ""; - } - - // - result = - XCBaseExpertToken + result; - - // - return result; - } - - // - protected: - // - - // - // Props ... - - // - XTimeTracker mTimeTracker; // Time Tracker for Providing Reports ... - - // - // Actions ... - - /** - * Report Account Balance ... - */ - void HandleReportBalance() - { - // - if (!IsRunningOnTestMode()) - { - return; - } - - // - string msg = "Balance: " + ToString(mTrader.mAccount.GetBalance()); - Log(msg); - } - - /** - * Time Reporting based on Inputs ... - */ - void HandleReportTime() - { - // - // Monthly Report .... - if (mTimeTracker.IsNewMonth()) - { - // - HandleOnNewMonth(); - - // - if (mReportNewMonths) - { - // - string msg = "New Month ..."; - - // - SendAlert(msg); - } - } - - // - // Weekly Report .... - if (mTimeTracker.IsNewWeek()) - { - // - HandleOnNewWeek(); - - // - if (mReportNewWeeks) - { - // - string msg = "New Week ..."; - - // - SendAlert(msg); - } - } - - // - // Daily Report .... - if (mTimeTracker.IsNewDay()) - { - // - HandleOnNewDay(); - - // - if (mReportNewDays) - { - // - string msg = "New Day ..."; - - // - SendAlert(msg); - } - } - - // - // Hourly Report .... - if (mTimeTracker.IsNewHour()) - { - // - HandleOnNewHour(); - - // - if (mReportNewHours) - { - // - string msg = "New Hour ..."; - - // - SendAlert(msg); - } - } - } - - // - private: - // - - // - // Props ... - - // - // Common ... - long mMagicNumber; // Magic Number ... - int mSlippage; // Slippage ... - string mTagPrefix; // Tag Prefix ... - - // - // Symbol ... - ENUM_TIMEFRAMES mPeriod; // Period ... - string mSymbol; // Symbol ... - bool mMultiSymbol; // Multi Symbol is Enable or Not ... - string mSymbols; // Multi Provided Symbols ... - - // - // Signalling ... - bool mDisabled; // Force Disable Signalling ... - bool mAllowLong; // Allow Long Signals ... - bool mAllowShort; // Allow Short Signals ... - - // - // Reports ... - bool mReportNewMonths; // Report New Month ... - bool mReportNewWeeks; // Report New Weeks ... - bool mReportNewDays; // Report New Days ... - bool mReportNewHours; // Report New Hours ... - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x-poi.class.mq5 b/Documents/BKP/x-saherelm.x-poi.class.mq5 deleted file mode 100644 index d3338fa1..00000000 --- a/Documents/BKP/x-saherelm.x-poi.class.mq5 +++ /dev/null @@ -1,3513 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XPOI -// Description: Provides Point of Interests ... -// - Swing Highs; -// - Swing Lows; -// -// 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-alert.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Libraries/x-saherelm.x-poi.state.lib.mq5" - -// -// Implementation ... - -// -// POI Detector Class ... -class XCPOIDetector : public XCBaseAlert -{ - // - public: - // - - // - // Constructors ... - /** - * Create an Instance ... - * - * @param symbol: String ... - * @param period: ENUM_TIMEFRAMES member ... - */ - void XCPOIDetector( - string symbol, - ENUM_TIMEFRAMES period) - { - // - // Attach Required Properties ... - mSymbol = symbol; - mPeriod = period; - - // - // Initialize Bar Tracker ... - mBarTracker.Init( - mSymbol, - mPeriod // - ); - - // - mBarAnalyser = new XCBarAnalyser(); - - // - // Apply Default Configurations ... - Default(); - } - - // - // Deconstructor ... - void ~XCPOIDetector() - { - Destroy(); - } - - // - // Getter(s) / Setter(s) ... - - /** - * Retrieve Detector Symbol ... - * - * @return ( string ) - */ - string GetSymbol() - { - return mSymbol; - } - - /** - * Retrieve Detector Period ... - * - * @return ( ENUM_TIMEFRAMES ) - */ - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - /** - * Get Max Required POI(s) allowed to Holds ... - * - * @return ( int ) - */ - int MaxRequiredPOIs() - { - return mMaxRequiredPOIs; - } - - /** - * Set Max Required POI(s) allowed to Holds ... - * - * @param value: int ... - */ - void MaxRequiredPOIs(int value) - { - // - if (value < 0) - { - value = 5; - } - - // - mMaxRequiredPOIs = value; - } - - /** - * Get Max Allowed Loopback for POI(s) Detection on Initialization Process ... - * - * @return ( int ) - */ - int MaxAllowedLoopbackForInit() - { - return maxAllowedLoopbackForInit; - } - - /** - * Set Max Allowed Loopback for POI(s) Detection on Initialization Process ... - * - * @param value: int ... - */ - void MaxAllowedLoopbackForInit(int value) - { - // - if (value < 0) - { - value = 578; - } - - // - maxAllowedLoopbackForInit = value; - } - - // - // - // - - /** - * Get Swing Range Validation ... - * - * @return ( int ) - */ - int SwingRange() - { - return mSwingRange; - } - - /** - * Set Swing Range Validation ... - * - * @param value: int ... - */ - void SwingRange(int value) - { - // - value = NormalizeInt(value, 1); - - // - mSwingRange = value; - } - - /** - * Get Pullback Range Validation ... - * - * @return ( int ) - */ - int PullbackRange() - { - return mPullbackRange; - } - - /** - * Set Pullback Range Validation ... - * - * @param value: int ... - */ - void PullbackRange(int value) - { - // - value = NormalizeInt(value, 1); - - // - mPullbackRange = value; - } - - /** - * Get Momentum Detecting Loopback ... - * - * @return ( int ) - */ - int MomentumLoopback() - { - return mMomentumLoopback; - } - - /** - * Set Momentum Detecting Loopback ... - * - * @param value: int ... - */ - void MomentumLoopback(int value) - { - // - value = NormalizeInt(value, 1); - - // - mMomentumLoopback = value; - } - - /** - * Get Rejection Detecting Force Bar Type State ... - * - * @return ( bool ) - */ - bool RejectionForceBarType() - { - return mRejectionForceBarType; - } - - /** - * Set Rejection Detecting Force Bar Type State ... - * - * @param value: bool ... - */ - void RejectionForceBarType(bool value) - { - mRejectionForceBarType = value; - } - - /** - * Get Rejection Detecting Force Fibo Pressure State ... - * - * @return ( bool ) - */ - bool RejectionForceFiboPressure() - { - return mRejectionForceFiboPressure; - } - - /** - * Set Rejection Detecting Force Fibo Pressure State ... - * - * @param value: bool ... - */ - void RejectionForceFiboPressure(bool value) - { - mRejectionForceFiboPressure = value; - } - - /** - * Get Minimum Length of Cnsolidation Zone ... - * - * @return ( int ) - */ - int ConsolidationZoneMinLoopback() - { - return mConsolidationZoneMinLoopback; - } - - /** - * Set Minimum Length of Cnsolidation Zone ... - * - * @param value: int ... - */ - void ConsolidationZoneMinLoopback(int value) - { - // - value = NormalizeInt(value, 1); - - // - mConsolidationZoneMinLoopback = value; - } - - /** - * Get Consolidation Zone Range in Point ... - * - * @return ( double ) - */ - double ConsolidationZoneRangeInPoint() - { - return mConsolidationZoneRangeInPoint; - } - - /** - * Set Consolidation Zone Range in Point ... - * - * @param value: double ... - */ - void ConsolidationZoneRangeInPoint(double value) - { - // - value = NormalizeDouble(value, 0); - - // - mConsolidationZoneRangeInPoint = value; - } - - /** - * Get Consolidation Zone Lower Applied To ... - * - * @return ( ENUM_X_PRICE ) - */ - ENUM_X_PRICE ConsolidationZonesLowerAppliedTo() - { - return mConsolidationZonesLowerAppliedTo; - } - - /** - * Get Consolidation Zone Lower Applied To ... - * - * @param value: ENUM_X_PRICE member ... - */ - void ConsolidationZonesLowerAppliedTo(ENUM_X_PRICE value) - { - mConsolidationZonesLowerAppliedTo = value; - } - - /** - * Get Consolidation Zone Upper Applied To ... - * - * @return ( ENUM_X_PRICE ) - */ - ENUM_X_PRICE ConsolidationZonesUpperAppliedTo() - { - return mConsolidationZonesUpperAppliedTo; - } - - /** - * Get Consolidation Zone Upper Applied To ... - * - * @param value: ENUM_X_PRICE member ... - */ - void ConsolidationZonesUpperAppliedTo(ENUM_X_PRICE value) - { - mConsolidationZonesUpperAppliedTo = value; - } - - /** - * Get Spike Detection Price Type ... - * - * @return ( ENUM_X_PRICE ) - */ - ENUM_X_PRICE SpikePriceType() - { - return mSpikePriceType; - } - - /** - * Set Spike Detection Price Type ... - * - * @param value: ENUM_X_PRICE member ... - */ - void SpikePriceType(ENUM_X_PRICE value) - { - mSpikePriceType = value; - } - - /** - * Get Spike Detection Force Body In Range State ... - * - * @return ( bool ) - */ - bool SpikeForcBodyInRange() - { - return mSpikeForcBodyInRange; - } - - /** - * Set Spike Detection Force Body In Range State ... - * - * @param value: bool ... - */ - void SpikeForcBodyInRange(bool value) - { - mSpikeForcBodyInRange = value; - } - - /** - * Get Spike Detection Range Extends Multiplier ... - * - * @return ( double ) - */ - double SpikeRangeExtendMultiplier() - { - return mSpikeRangeExtendMultiplier; - } - - /** - * Set Spike Detection Range Extends Multiplier ... - * - * @param value: double ... - */ - void SpikeRangeExtendMultiplier(double value) - { - // - value = NormalizeDouble(value, 1); - - // - mSpikeRangeExtendMultiplier = value; - } - - /** - * Get Spike Detection Same Bars ... - * - * @return ( int ) - */ - int SpikeSameBars() - { - return mSpikeSameBars; - } - - /** - * Set Spike Detection Same Bars ... - * - * @param value: int ... - */ - void SpikeSameBars(int value) - { - // - value = NormalizeInt(value, 1); - - // - mSpikeSameBars = value; - } - - /** - * Get Support and Resistance Detection Range ... - * - * @return ( int ) - */ - int SupResRange() - { - return mSupResRange; - } - - /** - * Set Support and Resistance Detection Range ... - * - * @param value: int ... - */ - void SupResRange(int value) - { - // - value = NormalizeInt(value, 5); - - // - mSupResRange = value; - } - - /** - * Get use Support and Resistance Range as Start ... - * - * @return ( bool ) - */ - bool SupResRangeAsStart() - { - return mSupResRangeAsStart; - } - - /** - * Set use Support and Resistance Range as Start ... - * - * @param value: bool ... - */ - void SupResRangeAsStart(bool value) - { - mSupResRangeAsStart = value; - } - - /** - * Get Force Activations in Supply/Demand and Support/Resistance Detections State ... - * - * @return ( bool ) - */ - bool SupResForceActivation() - { - return mSupResForceActivation; - } - - /** - * Set Force Activations in Supply/Demand and Support/Resistance Detections State ... - * - * @param value: bool ... - */ - void SupResForceActivation(bool value) - { - mSupResForceActivation = value; - } - - /** - * Get FairValueGap Detection Same Bars ... - * - * @return ( int ) - */ - int FairValueGapSameBars() - { - return mFairValueGapSameBars; - } - - /** - * Set FairValueGap Detection Same Bars ... - * - * @param value: int ... - */ - void FairValueGapSameBars(int value) - { - // - value = NormalizeInt(value, 2); - - // - mFairValueGapSameBars = value; - } - - /** - * Get FairValueGap Detection Force Check Activation State ... - * - * @return ( bool ) - */ - bool FairValueGapForceActivation() - { - return mFairValueGapForceActivation; - } - - /** - * Set FairValueGap Detection Force Check Activation State ... - * - * @param value: bool ... - */ - void FairValueGapForceActivation(bool value) - { - mFairValueGapForceActivation = value; - } - - /** - * Get OrderBlock Detection Same Bars ... - * - * @return ( int ) - */ - int OrderBlockSameBars() - { - return mOrderBlockSameBars; - } - - /** - * Set OrderBlock Detection Same Bars ... - * - * @param value: int ... - */ - void OrderBlockSameBars(int value) - { - // - value = NormalizeInt(value, 1); - - // - mOrderBlockSameBars = value; - } - - /** - * Get Order Blocs Detection Force Spike State ... - * - * @return ( bool ) - */ - bool OrderBlockForceSpike() - { - return mOrderBlockForceSpike; - } - - /** - * Set Order Blocs Detection Force Spike State ... - * - * @param value: bool ... - */ - void OrderBlockForceSpike(bool value) - { - mOrderBlockForceSpike = value; - } - - /** - * Get Order Blocs Detection Force Fair Value Gaps State ... - * - * @return ( bool ) - */ - bool OrderBlockForceFairValueGap() - { - return mOrderBlockForceFairValueGap; - } - - /** - * Set Order Blocs Detection Force Fair Value Gaps State ... - * - * @param value: bool ... - */ - void OrderBlockForceFairValueGap(bool value) - { - mOrderBlockForceFairValueGap = value; - } - - /** - * Get Order Blocs Detection Force Support/Resisatnce ... - * - * @return ( bool ) - */ - bool OrderBlockForceSupportResistance() - { - return mOrderBlockForceSupportResistance; - } - - /** - * Set Order Blocs Detection Force Support/Resisatnce ... - * - * @param value: bool ... - */ - void OrderBlockForceSupportResistance(bool value) - { - mOrderBlockForceSupportResistance = value; - } - - /** - * Get OrderBlock Detection Force Check Activation State ... - * - * @return ( bool ) - */ - bool OrderBlockForceActivation() - { - return mOrderBlockForceActivation; - } - - /** - * Set OrderBlock Detection Force Check Activation State ... - * - * @param value: bool ... - */ - void OrderBlockForceActivation(bool value) - { - mOrderBlockForceActivation = value; - } - - // - // - // - // - // - // - - // - // Actions ... - - /** - * Apply Default Configurations ... - */ - virtual void Default() - { - // - // Default Props ... - MaxRequiredPOIs(100); - MaxAllowedLoopbackForInit(578); - - // - SwingRange(7); - MomentumLoopback(2); - - // - PullbackRange(3); - - // - MomentumLoopback(2); - - // - RejectionForceBarType(true); - RejectionForceFiboPressure(true); - - // - ConsolidationZoneMinLoopback(7); - ConsolidationZoneRangeInPoint(50); - ConsolidationZonesLowerAppliedTo(X_PRICE_LOW); - ConsolidationZonesUpperAppliedTo(X_PRICE_HIGH); - - // - SpikePriceType(X_PRICE_CLOSE); - SpikeForcBodyInRange(true); - SpikeRangeExtendMultiplier(2.0); - SpikeSameBars(3); - - // - SupResRange(21); - SupResRangeAsStart(true); - SupResForceActivation(true); - - // - FairValueGapSameBars(3); - - // - OrderBlockSameBars(3); - OrderBlockForceSpike(true); - OrderBlockForceFairValueGap(true); - OrderBlockForceSupportResistance(false); - } - - /** - * Add Event Listener ... - * - * @param listener: TOnPOIEvent instance ... - */ - void AddEventListener(TOnPOIEvent listener) - { - // - Add( - listener, - mEventListeners // - ); - } - - /** - * Initialize Instance ... - */ - void Init( - int barIndex = 0, - bool ignoreMaxAllowed = true // - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (maxAllowedLoopbackForInit <= 0) - { - return; - } - - // - mLock = true; - bool canContinue = true; - int index = barIndex + maxAllowedLoopbackForInit; - if (!IsValidIndex(index)) - { - // - mLock = false; - return; - } - - // - while (canContinue) - { - // - XOHCL iBar; - bool has = iBar.Init( - mSymbol, - mPeriod, - index // - ); - index--; - - // - int count = 0; - ENUM_XPOI_EVENTS iEvent = X_POI_EVENT_NONE; - - // - // Swings ... - DetectSwing( - iBar, - iEvent // - ); - - // - // Momentum ... - DetectMomentum( - iBar, - iEvent // - ); - - // - // Rejection ... - DetectRejection( - iBar, - iEvent // - ); - - // - // Pullback ... - DetetctPullback( - iBar, - iEvent // - ); - - // - // Consolidation Zone ... - DetectConsolidationZone( - iBar, - iEvent // - ); - - // - // Spike ... - DetectSharp( - iBar, - iEvent // - ); - - // - // Spike ... - DetectSpike( - iBar, - iEvent // - ); - - // - // Support ... - DetectSupportZone( - iBar, - iEvent // - ); - - // - // Resistance ... - DetectResistanceZone( - iBar, - iEvent // - ); - - // - // Supply ... - DetectSupplyZone( - iBar, - iEvent // - ); - - // - // Demand ... - DetectDemandZone( - iBar, - iEvent // - ); - - // - // FairValueGap ... - DetectFairValueGap( - iBar, - iEvent // - ); - - // - // OrderBlock ... - DetectOrderBlock( - iBar, - iEvent // - ); - - // - canContinue = - has && - index >= 0; - - // - iBar.Clean(); - } - - // - ReverseCollections(); - - // - mLock = false; - } - - /** - * Update POI(s) ... - * @param events: ENUM_XPOI_EVENTS member Collection ... - */ - void Update( - ENUM_XPOI_EVENTS &events[], - int barIndex = 0 // - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Clean(events); - - // - if (mLock) - { - return; - } - - // - // Check Bar Tracker if Waits ... - if (!mBarTracker.IsNewBar()) - { - return; - } - - // - mLock = true; - - // - XOHCL iBar; - bool has = iBar.Init( - mSymbol, - mPeriod, - barIndex // - ); - - // - if (!has) - { - // - iBar.Clean(); - - // - return; - } - - // - int count = 0; - ENUM_XPOI_EVENTS iEvent = X_POI_EVENT_NONE; - - // - // Swings ... - has = DetectSwing( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Momentum ... - has = DetectMomentum( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Rejection ... - has = DetectRejection( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Pullback ... - has = DetetctPullback( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Consolidation Zone ... - has = DetectConsolidationZone( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Sharp ... - has = DetectSharp( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Spike ... - has = DetectSpike( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Support ... - has = DetectSupportZone( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Resistance ... - has = DetectResistanceZone( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Supply ... - has = DetectSupplyZone( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // Demand ... - has = DetectDemandZone( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // FairValueGap ... - has = DetectFairValueGap( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - // OrderBlock ... - has = DetectOrderBlock( - iBar, - iEvent // - ); - if (has) - { - // - Add( - iEvent, - events // - ); - } - - // - iBar.Clean(); - mLock = false; - - // - if (HasChild(events)) - { - CleanupUnusedCollections(); - } - } - - /** - * Get Current State of POIs ... - * - * @param state: XPOIState instance ... - */ - void GetState( - XPOIState &state // - ) - { - // - state.Clean(); - - // - state.symbol = mSymbol; - state.period = mPeriod; - state.time = TimeCurrent(); - - // - // Swings ... - - // - Copy( - mSwings, - state.swings // - ); - - // - Copy( - mSwingLows, - state.swingLows // - ); - - // - Copy( - mSwingHighs, - state.swingHighs // - ); - - // - // Pullbacks ... - - // - Copy( - mPullbacks, - state.pullbacks // - ); - - // - Copy( - mBullishPullbacks, - state.bullishPullbacks // - ); - - // - Copy( - mBearishPullbacks, - state.bearishPullbacks // - ); - - // - // Momentums ... - - // - Copy( - mMomentums, - state.momentums // - ); - - // - Copy( - mBullishMomentums, - state.bullishMomentums // - ); - - // - Copy( - mBearishMomentums, - state.bearishMomentums // - ); - - // - // Rejections ... - - // - Copy( - mRejections, - state.rejections // - ); - - // - Copy( - mBullishRejections, - state.bullishRejections // - ); - - // - Copy( - mBearishRejections, - state.bearishRejections // - ); - - // - // Support and Resistances ... - - // - Copy( - mSupportZones, - state.supportZones // - ); - - // - Copy( - mResistanceZones, - state.resistanceZones // - ); - - // - // Supply and Demand ... - - // - Copy( - mSupplyZones, - state.supplyZones // - ); - - // - Copy( - mDemandZones, - state.demandZones // - ); - - // - // Spikes ... - - // - Copy( - mSpikes, - state.spikes // - ); - - // - Copy( - mBullishSpikes, - state.bullishSpikes // - ); - - // - Copy( - mBearishSpikes, - state.bearishSpikes // - ); - - // - // Sharps ... - - // - Copy( - mSharps, - state.sharps // - ); - - // - Copy( - mBullishSharps, - state.bullishSharps // - ); - - // - Copy( - mBearishSharps, - state.bearishSharps // - ); - - // - // Consolidation Zones ... - - // - Copy( - mConsolidationZones, - state.consolidationZones // - ); - - // - Copy( - mBullishConsolidationZones, - state.bullishConsolidationZones // - ); - - // - Copy( - mBearishConsolidationZones, - state.bearishConsolidationZones // - ); - - // - // Fair Value Gaps ... - - // - Copy( - mFairValueGaps, - state.fairValueGaps // - ); - - // - Copy( - mBullishFairValueGaps, - state.bullishFairValueGaps // - ); - - // - Copy( - mBearishFairValueGaps, - state.bearishFairValueGaps // - ); - - // - // Order Blocks ... - - // - Copy( - mOrderBlocks, - state.orderBlocks // - ); - - // - Copy( - mBullishOrderBlocks, - state.bullishOrderBlocks // - ); - - // - Copy( - mBearishOrderBlocks, - state.bearishOrderBlocks // - ); - } - - /** - * Destroy Instance ... - */ - void Destroy() - { - // - mBarTracker.Clean(); - ZeroMemory(mBarAnalyser); - - // - CleanCollections(); - } - - // - // - // - // - // - // - - /** - * Detect Swing ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectSwing( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = bar.GetPreviousBar(sBar); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsSwing( - sBar, - iDir, - mSwingRange // - ); - - // - result = result && - HasDirection(iDir); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - bool checkBar = bar.Index() != sBar.Index(); - - // - bool isBullish = - IsBullish(iDir) && - (!checkBar - ? true - : bar.low > sBar.low); - bool isBearish = - IsBearish(iDir) && - (!checkBar - ? true - : bar.high < sBar.high); - result = isBullish || - isBearish; - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - XOHCL swingBar; - result = sBar.GetPreviousBar(swingBar); - if (!result) - { - // - sBar.Clean(); - swingBar.Clean(); - return result; - } - - // - ENUM_XPOIS type = - isBullish - ? X_POI_SWING_LOW - : X_POI_SWING_HIGH; - - // - // Swing Object ... - XCSwing *swing; - swing = new XCSwing(); - result = swing.Init( - swingBar, - type // - ); - if (!result) - { - // - sBar.Clean(); - swingBar.Clean(); - return result; - } - - // - // Add ... - - // - int idx = FindIndex( - swing, - mSwings // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - sBar.Clean(); - swingBar.Clean(); - return result; - } - - // - // Add All Collection ... - Add( - swing, - mSwings // - ); - - // - // Bullish Swings (Swing Low) ... - if (isBullish) - { - // - Add( - swing, - mSwingLows // - ); - } - - // - // Bearish Swings (Swing High) ... - if (isBearish) - { - // - Add( - swing, - mSwingHighs // - ); - } - - // - // Prepare State ... - state = - isBullish - ? X_SWING_LOW_DETECTED - : X_SWING_HIGH_DETECTED; - - // - // Cleanup Resources ... - - // - sBar.Clean(); - swingBar.Clean(); - - // - return result; - } - - /** - * Detect Momentums ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectMomentum( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = sBar.Init( - bar.symbol, - bar.period, - bar.Index() + 1 // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsMomentum( - sBar, - iDir, - mMomentumLoopback // - ); - - // - result = result && - HasDirection(iDir); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - bool isBullish = IsBullish(iDir); - bool isBearish = IsBearish(iDir); - - // - ENUM_XPOIS type = - isBullish - ? X_POI_MOMENTUM_BAR - : X_POI_MOMENTUM_BAR; - - // - // Swing Object ... - XCMomentumBar *momentum; - momentum = new XCMomentumBar(); - result = momentum.Init( - sBar // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - int idx = FindIndex( - momentum, - mMomentums // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - // Momentums ... - Add( - momentum, - mMomentums // - ); - - // - if (isBullish) - { - // - Add( - momentum, - mBullishMomentums // - ); - } - - // - if (isBearish) - { - // - Add( - momentum, - mBearishMomentums // - ); - } - - // - state = - isBullish - ? X_BULLISH_MOMENTUM_BAR_DETECTED - : X_BEARISH_MOMENTUM_BAR_DETECTED; - - // - sBar.Clean(); - - // - return result; - } - - /** - * Detect Rejections ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectRejection( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = sBar.Init( - bar.symbol, - bar.period, - bar.Index() + 1 // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsRejected( - sBar, - iDir, - mRejectionForceBarType, - mRejectionForceFiboPressure // - ); - - // - result = result && - HasDirection(iDir); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - bool isBullish = IsBullish(iDir); - bool isBearish = IsBearish(iDir); - - // - ENUM_XPOIS type = - isBullish - ? X_POI_MOMENTUM_BAR - : X_POI_MOMENTUM_BAR; - - // - // Swing Object ... - XCRejectionBar *rejection; - rejection = new XCRejectionBar(); - result = rejection.Init( - sBar // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - int idx = FindIndex( - rejection, - mRejections // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - Add( - rejection, - mRejections // - ); - - // - if (isBullish) - { - // - Add( - rejection, - mBullishRejections // - ); - } - - // - if (isBearish) - { - // - Add( - rejection, - mBearishRejections // - ); - } - - // - state = - isBullish - ? X_BULLISH_REJECTION_BAR_DETECTED - : X_BEARISH_REJECTION_BAR_DETECTED; - - // - return result; - } - - /** - * Detect Pullback ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetetctPullback( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = sBar.Init( - bar.symbol, - bar.period, - bar.Index() + 1 // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsPullback( - sBar, - iDir, - mPullbackRange, - true // Force Body ... - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - bool isBullish = IsBullish(iDir); - bool isBearish = IsBearish(iDir); - result = isBullish || - isBearish; - if (!result) - { - // - sBar.Clean(); - return result; - } - - // - XOHCL fromBar; - result = fromBar.Init( - bar.symbol, - bar.period, - sBar.Index() + mPullbackRange // - ); - if (!result) - { - // - fromBar.Clean(); - return result; - } - - // - XBoxZone box; - - // - box.dir = iDir; - box.to = sBar.time; - box.from = fromBar.time; - box.symbol = fromBar.symbol; - box.period = fromBar.period; - box.lower = MathMin(sBar.low, fromBar.low); - box.upper = MathMax(sBar.high, fromBar.high); - box.type = ToString(iDir) + "_XPullBK" + box.symbol + "_" + ToString(box.period); - - // - result = box.IsValid(); - if (result) - { - // - AddRef( - box, - mPullbacks // - ); - - // - if (isBullish) - { - // - AddRef( - box, - mBullishPullbacks // - ); - } - - // - if (isBearish) - { - // - AddRef( - box, - mBearishPullbacks // - ); - } - - // - state = - isBullish - ? X_BULLISH_PULLBACK_DETECTED - : X_BEARISH_PULLBACK_DETECTED; - } - - // - // Cleanup Resources ... - - // - box.Clean(); - sBar.Clean(); - fromBar.Clean(); - - // - return result; - } - - /** - * Detect Consolidation Zones ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectConsolidationZone( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - XOHCL sBar; - if (bar.Index() == 0) - { - // - result = sBar.Init( - bar.symbol, - bar.period, - bar.Index() + 1 // - ); - if (!result) - { - // - sBar.Clean(); - return result; - } - } - else - { - sBar = bar; - } - - // - XConsolidationZone cZone; - result = mBarAnalyser.HasConsolidationZone( - sBar, - cZone, - mConsolidationZoneMinLoopback, - mConsolidationZoneRangeInPoint, - mConsolidationZonesUpperAppliedTo, - mConsolidationZonesLowerAppliedTo // - ); - if (!result) - { - // - sBar.Clean(); - cZone.Clean(); - - // - return result; - } - - // - // Add ... - - // - bool isBullish = IsBullish(cZone.dir); - bool isBearish = IsBearish(cZone.dir); - - // - int idx = FindIndex( - cZone, - mConsolidationZones // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - sBar.Clean(); - cZone.Clean(); - - // - return result; - } - - // - AddRef( - cZone, - mConsolidationZones // - ); - - // - if (isBullish) - { - // - AddRef( - cZone, - mBullishConsolidationZones // - ); - } - - // - if (isBearish) - { - // - AddRef( - cZone, - mBearishConsolidationZones // - ); - } - - // - state = - IsBullish(cZone.dir) - ? X_BULLISH_CONSOLIDATION_ZONE_DETECTED - : X_BEARISH_CONSOLIDATION_ZONE_DETECTED; - - // - cZone.Clean(); - - // - return result; - } - - /** - * Detect Sharp Change ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectSharp( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int sharpRootIDX = -1; - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsSharp( - bar, - iDir, - sharpRootIDX, - mSpikePriceType, - mSpikeForcBodyInRange, - mSpikeRangeExtendMultiplier // - ); - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(iDir); - bool isBearish = IsBearish(iDir); - - // - XOHCL fromBar; - result = fromBar.Init( - bar.symbol, - bar.period, - sharpRootIDX // - ); - if (!result) - { - // - fromBar.Clean(); - return result; - } - - // - XBoxZone box; - - // - box.dir = iDir; - box.to = bar.time; - box.from = fromBar.time; - box.symbol = fromBar.symbol; - box.period = fromBar.period; - box.type = ToString(iDir) + "_XSharp" + box.symbol + "_" + ToString(box.period); - - // - box.upper = - isBullish - ? bar.high - : fromBar.high; - - // - box.lower = - isBullish - ? fromBar.low - : bar.low; - - // - result = box.IsValid(); - if (result) - { - // - AddRef( - box, - mSharps // - ); - - // - if (isBullish) - { - // - AddRef( - box, - mBullishSharps // - ); - } - - // - if (isBearish) - { - // - AddRef( - box, - mBearishSharps // - ); - } - - // - state = - isBullish - ? X_BULLISH_SHARP_DETECTED - : X_BEARISH_SHARP_DETECTED; - } - - // - // Cleanup Resources ... - - // - box.Clean(); - fromBar.Clean(); - - // - return result; - } - - /** - * Detect Spike ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectSpike( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int rootIDX = -1; - ENUM_X_DIRECTION iDir; - result = mBarAnalyser.IsSpike( - bar, - iDir, - rootIDX, - mSpikePriceType, - mSpikeForcBodyInRange, - mSpikeRangeExtendMultiplier, - mSpikeSameBars // - ); - if (!result) - { - return result; - } - - // - // Chek Same Bars ... - int sameBarsIndex = -1; - ENUM_X_DIRECTION sameBarsDir; - result = mBarAnalyser.HasSameBars( - bar, - sameBarsDir, - sameBarsIndex, - mSpikeSameBars // - ); - if (!result) - { - return result; - } - - // - // Validate Same Bars Dir and Spike Dir ... - result = iDir == sameBarsDir; - if (!result) - { - return result; - } - - // - bool isBullish = IsBullish(iDir); - bool isBearish = IsBearish(iDir); - - // - XOHCL fromBar; - result = fromBar.Init( - bar.symbol, - bar.period, - rootIDX // - ); - if (!result) - { - // - fromBar.Clean(); - return result; - } - - // - XBoxZone box; - - // - box.dir = iDir; - box.to = bar.time; - box.from = fromBar.time; - box.symbol = fromBar.symbol; - box.period = fromBar.period; - box.type = ToString(iDir) + "_XSpike_" + box.symbol + "_" + ToString(box.period); - - // - box.upper = - isBullish - ? bar.high - : fromBar.high; - - // - box.lower = - isBullish - ? fromBar.low - : bar.low; - - // - result = box.IsValid(); - if (result) - { - // - AddRef( - box, - mSpikes // - ); - - // - if (isBullish) - { - // - AddRef( - box, - mBullishSpikes // - ); - } - - // - if (isBearish) - { - // - AddRef( - box, - mBearishSpikes // - ); - } - - // - state = - isBullish - ? X_BULLISH_SPIKE_DETECTED - : X_BEARISH_SPIKE_DETECTED; - } - - // - // Cleanup Resources ... - - // - box.Clean(); - fromBar.Clean(); - - // - return result; - } - - /** - * Detect Support Zone ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectSupportZone( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL supportBar; - result = mBarAnalyser - .HasSupport( - bar, - supportBar, - mSupResRange // - ); - if (!result) - { - // - supportBar.Clean(); - - // - return result; - } - - // - XCSupportZone *supportZone; - supportZone = new XCSupportZone(); - result = supportZone.Init( - supportBar, - mSupResRange, - mSupResRangeAsStart // Use Range As Start ... - ); - if (!result) - { - // - supportBar.Clean(); - ZeroMemory(supportZone); - - // - return result; - } - - // - // Check Zone Not Activated ... - if (mSupResForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = supportZone.IsActivated( - X_DIRECTION_BULLISH, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - supportBar.Clean(); - activationBar.Clean(); - ZeroMemory(supportZone); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - // Add ... - - // - int idx = FindIndex( - supportZone, - mSupportZones // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - supportBar.Clean(); - ZeroMemory(supportZone); - - // - return result; - } - - // - Add( - supportZone, - mSupportZones // - ); - - // - state = X_SUPPORT_ZONE_DETECTED; - - // - supportBar.Clean(); - - // - return result; - } - - /** - * Detect Resistance Zone ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectResistanceZone( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL resistanceBar; - result = mBarAnalyser - .HasResistance( - bar, - resistanceBar, - mSupResRange // - ); - if (!result) - { - // - resistanceBar.Clean(); - - // - return result; - } - - // - XCResistanceZone *resistanceZone; - resistanceZone = new XCResistanceZone(); - result = resistanceZone.Init( - resistanceBar, - mSupResRange, - mSupResRangeAsStart // Use Range As Start ... - ); - if (!result) - { - // - resistanceBar.Clean(); - ZeroMemory(resistanceZone); - - // - return result; - } - - // - // Check Zone Not Activated ... - if (mSupResForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = resistanceZone.IsActivated( - X_DIRECTION_BULLISH, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - resistanceBar.Clean(); - activationBar.Clean(); - ZeroMemory(resistanceZone); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - // Add ... - - // - int idx = FindIndex( - resistanceZone, - mResistanceZones // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - resistanceBar.Clean(); - ZeroMemory(resistanceZone); - - // - return result; - } - - // - Add( - resistanceZone, - mResistanceZones // - ); - - // - state = X_RESISTANCE_ZONE_DETECTED; - - // - resistanceBar.Clean(); - - // - return result; - } - - /** - * Detect Supply Zone ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectSupplyZone( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int mSupDemRange = mSupResRange * 2; - - // - XOHCL supplyBar; - result = mBarAnalyser - .HasResistance( - bar, - supplyBar, - mSupDemRange // - ); - if (!result) - { - // - supplyBar.Clean(); - - // - return result; - } - - // - XCSupplyZone *supplyZone; - supplyZone = new XCSupplyZone(); - result = supplyZone.Init( - supplyBar, - mSupDemRange, - mSupResRangeAsStart // Use Range As Start ... - ); - if (!result) - { - // - supplyBar.Clean(); - ZeroMemory(supplyZone); - - // - return result; - } - - // - // Check Zone Not Activated ... - if (mSupResForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = supplyZone.IsActivated( - X_DIRECTION_BULLISH, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - supplyBar.Clean(); - activationBar.Clean(); - ZeroMemory(supplyZone); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - // Add ... - - // - int idx = FindIndex( - supplyZone, - mSupplyZones // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - supplyBar.Clean(); - ZeroMemory(supplyZone); - - // - return result; - } - - // - Add( - supplyZone, - mSupplyZones // - ); - - // - state = X_SUPPLY_ZONE_DETECTED; - - // - supplyBar.Clean(); - - // - return result; - } - - /** - * Detect Demand Zone ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectDemandZone( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - int mSupDemRange = mSupResRange * 2; - - // - XOHCL demandBar; - result = mBarAnalyser - .HasSupport( - bar, - demandBar, - mSupDemRange // - ); - if (!result) - { - // - demandBar.Clean(); - - // - return result; - } - - // - XCDemandZone *demandZone; - demandZone = new XCDemandZone(); - result = demandZone.Init( - demandBar, - mSupDemRange, - mSupResRangeAsStart // Use Range As Start ... - ); - if (!result) - { - // - demandBar.Clean(); - ZeroMemory(demandZone); - - // - return result; - } - - // - // Check Zone Not Activated ... - if (mSupResForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = demandZone.IsActivated( - X_DIRECTION_BULLISH, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - demandBar.Clean(); - activationBar.Clean(); - ZeroMemory(demandZone); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - // Add ... - - // - int idx = FindIndex( - demandZone, - mDemandZones // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - demandBar.Clean(); - ZeroMemory(demandZone); - - // - return result; - } - - // - Add( - demandZone, - mDemandZones // - ); - - // - state = X_DEMAND_ZONE_DETECTED; - - // - demandBar.Clean(); - - // - return result; - } - - /** - * Detect Fair Value Gaps ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectFairValueGap( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL fvgStartBar; - XOHCL fvgEndBar; - ENUM_X_DIRECTION fvgDir; - result = mBarAnalyser.HasFairValueGap( - bar, - fvgStartBar, - fvgEndBar, - fvgDir, - mFairValueGapSameBars // - ); - if (!result) - { - // - fvgEndBar.Clean(); - fvgStartBar.Clean(); - - // - return result; - } - - // - XCFVG *fvg; - fvg = new XCFVG(); - result = fvg.Init( - fvgStartBar, - fvgEndBar, - fvgDir // - ); - if (!result) - { - // - ZeroMemory(fvg); - fvgEndBar.Clean(); - fvgStartBar.Clean(); - - // - return result; - } - - // - bool isBullish = IsBullish(fvgDir); - bool isBearish = IsBearish(fvgDir); - - // - // Check Zone Not Activated ... - if (mFairValueGapForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = fvg.IsActivated( - fvgDir, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - ZeroMemory(fvg); - fvgEndBar.Clean(); - fvgStartBar.Clean(); - activationBar.Clean(); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - int idx = FindIndex( - fvg, - mFairValueGaps // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - ZeroMemory(fvg); - fvgEndBar.Clean(); - fvgStartBar.Clean(); - - // - return result; - } - - // - Add( - fvg, - mFairValueGaps // - ); - - // - if (isBullish) - { - // - Add( - fvg, - mBullishFairValueGaps // - ); - } - - // - if (isBearish) - { - // - Add( - fvg, - mBearishFairValueGaps // - ); - } - - // - state = - isBullish - ? X_BULLISH_FVG_DETECTED - : X_BEARISH_FVG_DETECTED; - - // - fvgEndBar.Clean(); - fvgStartBar.Clean(); - - // - return result; - } - - /** - * Detect Order Blocks ... - * - * @param bar: XOHCL instance ... - * @param state: ENUM_XPOI_EVENTS member ... - * - * @return ( bool ) - */ - bool DetectOrderBlock( - XOHCL &bar, - ENUM_XPOI_EVENTS &state // - ) - { - // - bool result = false; - - // - state = X_POI_EVENT_NONE; - - // - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL obBar; - ENUM_X_DIRECTION obDir; - result = mBarAnalyser.HasOrderBlock( - bar, - obBar, - obDir, - mOrderBlockSameBars, - mOrderBlockForceSpike, - mOrderBlockForceFairValueGap, - mOrderBlockForceSupportResistance // - ); - if (!result) - { - // - obBar.Clean(); - - // - return result; - } - - // - XCOrderBlock *ob; - ob = new XCOrderBlock(); - result = ob.Init( - obBar, - obDir // - ); - if (!result) - { - // - obBar.Clean(); - ZeroMemory(ob); - - // - return result; - } - - // - bool isBullish = IsBullish(obDir); - bool isBearish = IsBearish(obDir); - - // - // Check Zone Not Activated ... - if (mOrderBlockForceActivation) - { - // - XOHCL activationBar; - bool isActivationBarBodyIn = false; - bool isActivated = ob.IsActivated( - obDir, - activationBar, - isActivationBarBodyIn, - false, - bar.period // - ); - result = !isActivated; - if (!result) - { - // - obBar.Clean(); - activationBar.Clean(); - ZeroMemory(ob); - - // - return result; - } - - // - activationBar.Clean(); - } - - // - int idx = FindIndex( - ob, - mOrderBlocks // - ); - result = !IsValidIndex(idx); - if (!result) - { - // - obBar.Clean(); - ZeroMemory(ob); - - // - return result; - } - - // - Add( - ob, - mOrderBlocks // - ); - - // - if (isBullish) - { - // - Add( - ob, - mBullishOrderBlocks // - ); - } - - // - if (isBearish) - { - // - Add( - ob, - mBearishOrderBlocks // - ); - } - - // - state = - isBullish - ? X_BULLISH_ORDERBLOCK_DETECTED - : X_BEARISH_ORDERBLOCK_DETECTED; - - // - obBar.Clean(); - - // - return result; - } - - // - protected: - // - - /** - * Notify Event Listeners ... - * - * @param event: ENUM_XPOI_EVENTS member, Specified Occured Event ... - * @param param: XCBasePOI implementation, Specified Event Object ... - */ - void NotifyEventListeners( - ENUM_XPOI_EVENTS event, - XCBasePOI *param // - ) - { - // - int count = ArraySize(mEventListeners); - if (!IsValidSize(count)) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - mEventListeners[i]( - event, - param // - ); - } - } - - // - private: - // - - // - // Props ... - string mSymbol; // Market Symbol ... - ENUM_TIMEFRAMES mPeriod; // Market Period ... - XBarTracker mBarTracker; // Market Bar Tracker ... - XCBarAnalyser *mBarAnalyser; // Bar Analyser ... - - // - bool mLock; - - // - int mMaxRequiredPOIs; // Max Allowed Holds POI(s) ... - int maxAllowedLoopbackForInit; // Max Allowed Loopback for POI(s) Detection on Initialization Process ... - - // - TOnPOIEvent mEventListeners[]; // Event Listeners ... - - // - // Swings ... - XCSwing *mSwings[]; // Holds Founded Swing ... - XCSwing *mSwingLows[]; // Holds Founded Swing Lows ... - XCSwing *mSwingHighs[]; // Holds Founded Swing Highs ... - int mSwingRange; // Swing Detection Range ... - - // - // Pullbacks ... - XBoxZone mPullbacks[]; // Holds Founded Pullbacks ... - XBoxZone mBullishPullbacks[]; // Holds Founded Bullish Pullbacks ... - XBoxZone mBearishPullbacks[]; // Holds Founded Bearish Pullbacks ... - int mPullbackRange; // Pullback Detection Range ... - - // - // Momentums ... - XCMomentumBar *mMomentums[]; // Holds Founded Momentum Bars ... - XCMomentumBar *mBullishMomentums[]; // Holds Founded Bullish Momentum Bars ... - XCMomentumBar *mBearishMomentums[]; // Holds Founded Bearish Momentum Bars ... - int mMomentumLoopback; // Momentum Detecting Loopback ... - - // - // Rejections ... - XCRejectionBar *mRejections[]; // Holds Founded Rejection Bars ... - XCRejectionBar *mBullishRejections[]; // Holds Founded Bullish Rejection Bars ... - XCRejectionBar *mBearishRejections[]; // Holds Founded Bearish Rejection Bars ... - bool mRejectionForceBarType; // Rejection Detecting Force Bar Type ... - bool mRejectionForceFiboPressure; // Rejection Detecting Force Fibo Pressure ... - - // - // Consolidation Zones ... - XConsolidationZone mConsolidationZones[]; // Holds Founded Consolidation Zones ... - XConsolidationZone mBullishConsolidationZones[]; // Holds Founded Bullish Consolidation Zones ... - XConsolidationZone mBearishConsolidationZones[]; // Holds Founded Bearish Consolidation Zones ... - int mConsolidationZoneMinLoopback; // Minimum Length of Cnsolidation Zone ... - double mConsolidationZoneRangeInPoint; // Consolidation Zone Range in Point ... - ENUM_X_PRICE mConsolidationZonesLowerAppliedTo; // Consolidation Zone Upper Applied To ... - ENUM_X_PRICE mConsolidationZonesUpperAppliedTo; // Consolidation Zone Lower Applied To ... - - // - // Spike/Sharp Zones ... - XBoxZone mSharps[]; // Holds Founded Sharps ... - XBoxZone mBullishSharps[]; // Holds Founded Bullish Sharps ... - XBoxZone mBearishSharps[]; // Holds Founded Bearish Sharps ... - XBoxZone mSpikes[]; // Holds Founded Spikes ... - XBoxZone mBullishSpikes[]; // Holds Founded Bullish Spikes ... - XBoxZone mBearishSpikes[]; // Holds Founded Bearish Spikes ... - ENUM_X_PRICE mSpikePriceType; // Spike Detection Price Type ... - bool mSpikeForcBodyInRange; // Spike Detection Force Body In Range ... - double mSpikeRangeExtendMultiplier; // Spike Detection Range Extends Multiplier ... - int mSpikeSameBars; // Spike Detection Same Bars ... - - // - // Support and Resistance ... - // Supply and Demand ... - - // - int mSupResRange; // Support and Resistance Detection Range ... - bool mSupResRangeAsStart; // use Support and Resistance Range as Start ... - bool mSupResForceActivation; // Force Activations in Supply/Demand and Support/Resistance Detections ... - - // - XCSupplyZone *mSupplyZones[]; // Holds Detected Supply Zones ... - XCDemandZone *mDemandZones[]; // Holds Detected Demand Zones ... - - // - XCSupportZone *mSupportZones[]; // Holds Detected Support Zones ... - XCResistanceZone *mResistanceZones[]; // Holds Detected Resistance Zones ... - - // - // Fair Value Gaps ... - XCFVG *mFairValueGaps[]; // Holds Founded FairValueGaps ... - XCFVG *mBullishFairValueGaps[]; // Holds Founded Bullish FairValueGaps ... - XCFVG *mBearishFairValueGaps[]; // Holds Founded Bearish FairValueGaps ... - int mFairValueGapSameBars; // FairValueGap Detection Same Bars ... - bool mFairValueGapForceActivation; // FairValueGap Detection Force Check Activation ... - - // - // Order Blocks ... - XCOrderBlock *mOrderBlocks[]; // Holds Founded OrderBlocks ... - XCOrderBlock *mBullishOrderBlocks[]; // Holds Founded Bullish OrderBlocks ... - XCOrderBlock *mBearishOrderBlocks[]; // Holds Founded Bearish OrderBlocks ... - int mOrderBlockSameBars; // OrderBlock Detection Same Bars ... - bool mOrderBlockForceSpike; // Order Blocs Detection Force Spike ... - bool mOrderBlockForceFairValueGap; // Order Blocs Detection Force Fair Value Gaps ... - bool mOrderBlockForceSupportResistance; // Order Blocs Detection Force Support/Resisatnce ... - bool mOrderBlockForceActivation; // Order Blocs Detection Force Check Activation ... - - /** - * Clean All Collections ... - */ - void CleanCollections() - { - // - Clean(mSwings); - Clean(mSwingLows); - Clean(mSwingHighs); - Clean(mMomentums); - Clean(mBullishMomentums); - Clean(mBearishMomentums); - Clean(mRejections); - Clean(mBullishRejections); - Clean(mBearishRejections); - Clean(mConsolidationZones); - Clean(mBullishConsolidationZones); - Clean(mBearishConsolidationZones); - Clean(mSpikes); - Clean(mBullishSpikes); - Clean(mBearishSpikes); - Clean(mSupplyZones); - Clean(mDemandZones); - Clean(mSupportZones); - Clean(mResistanceZones); - Clean(mFairValueGaps); - Clean(mBullishFairValueGaps); - Clean(mBearishFairValueGaps); - Clean(mOrderBlocks); - Clean(mBullishOrderBlocks); - Clean(mBearishOrderBlocks); - } - - /** - * Reverse Collections ... - */ - void ReverseCollections() - { - // - ArrayReverse(mSwings); - ArrayReverse(mSwingLows); - ArrayReverse(mSwingHighs); - ArrayReverse(mMomentums); - ArrayReverse(mBullishMomentums); - ArrayReverse(mBearishMomentums); - ArrayReverse(mRejections); - ArrayReverse(mBullishRejections); - ArrayReverse(mBearishRejections); - ArrayReverse(mConsolidationZones); - ArrayReverse(mBullishConsolidationZones); - ArrayReverse(mBearishConsolidationZones); - ArrayReverse(mSpikes); - ArrayReverse(mBullishSpikes); - ArrayReverse(mBearishSpikes); - ArrayReverse(mSupplyZones); - ArrayReverse(mDemandZones); - ArrayReverse(mSupportZones); - ArrayReverse(mResistanceZones); - ArrayReverse(mFairValueGaps); - ArrayReverse(mBullishFairValueGaps); - ArrayReverse(mBearishFairValueGaps); - ArrayReverse(mOrderBlocks); - ArrayReverse(mBullishOrderBlocks); - ArrayReverse(mBearishOrderBlocks); - } - - /** - * Cleanup Unused Collection Items ... - * - * @param maxAllowed: int, Max Allowed ... - */ - void CleanupUnusedCollections( - int maxAllowed = 0 // - ) - { - // - maxAllowed = MaxRequiredPOIs(); - - // - if (maxAllowed <= 0) - { - return; - } - - // - CleanupArray(mSwings, maxAllowed); - CleanupArray(mSwingLows, maxAllowed); - CleanupArray(mSwingHighs, maxAllowed); - CleanupArray(mMomentums, maxAllowed); - CleanupArray(mBullishMomentums, maxAllowed); - CleanupArray(mBearishMomentums, maxAllowed); - CleanupArray(mRejections, maxAllowed); - CleanupArray(mBullishRejections, maxAllowed); - CleanupArray(mBearishRejections, maxAllowed); - CleanupArray(mConsolidationZones, maxAllowed); - CleanupArray(mBullishConsolidationZones, maxAllowed); - CleanupArray(mBearishConsolidationZones, maxAllowed); - CleanupArray(mSpikes, maxAllowed); - CleanupArray(mBullishSpikes, maxAllowed); - CleanupArray(mBearishSpikes, maxAllowed); - CleanupArray(mSupplyZones, maxAllowed); - CleanupArray(mDemandZones, maxAllowed); - CleanupArray(mSupportZones, maxAllowed); - CleanupArray(mResistanceZones, maxAllowed); - CleanupArray(mFairValueGaps, maxAllowed); - CleanupArray(mBullishFairValueGaps, maxAllowed); - CleanupArray(mBearishFairValueGaps, maxAllowed); - CleanupArray(mOrderBlocks, maxAllowed); - CleanupArray(mBullishOrderBlocks, maxAllowed); - CleanupArray(mBearishOrderBlocks, maxAllowed); - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/x-saherelm.x.expert.class.mq5 b/Documents/BKP/x-saherelm.x.expert.class.mq5 deleted file mode 100644 index ef09eb3e..00000000 --- a/Documents/BKP/x-saherelm.x.expert.class.mq5 +++ /dev/null @@ -1,1070 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Base Expert Class -// ------------------------------------------------- -// Name: XCExpert ... -// Description: Base Expert 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 Base Expert Class" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.x-guard.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" - -// -// Definitions ... - -// -// Implementation ... -class XCExpert : public XCBase -{ - // - // public ... - public: - // - // Props ... - - // - // Common ... - long eaMagicNumber; // Magic Number - int eaSlippage; // Slippgae - string eaLogSuffix; // Log Suffix - - // - // Volume ... - ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect; // Volume Applying Type - double eaStaticVoluem; // Static Volume - double eaDynamicVolumeStepBalance; // Step of Balance for Increase Volume - double eaDynamicVolumeStepVolume; // Step of Volume Increasing - double eaConstantRiskBalance; // Constant Risk Balance per Trade - double eaConstantPercent; // Constant Percent of Balance Per Trade - double eaConstantBalance; // Constant Balance for Calculations - - // - // Management ... - string eaSymbols; // Allowed Trading Symbols - bool eaAllowGuards; // Allow Guards - bool eaAllowTrade; // Allow Trade on Signals - bool eaAllowLongs; // Allow Long Trades - bool eaAllowShorts; // Allow Short Trades - ENUM_XCATBEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod; // Restrictions Period - int eaMaxAllowedTPs; // Max Allowed TP(s) in Restrictions Period - int eaMaxAllowedSLs; // Max Allowed SL(s) in Restrictions Period - int eaMaxAllowedTrades; // Max Allowed Trades in Restrictions Period - int eaMaxAllowedPositions; // Max Allowed Same Time Trades - double eaMaxAllowedSpread; // Max Allowed Spread For Trade - double eaMaxAllowedDrawdownFactor; // Max Allowed DrawDown for Trade - string eaCloseAllOpenTradesAt; // Close All Open Trades per Day At Specified Time - - // - // Alert ... - bool eaEnableAlerts; // Enable Alerts - bool eaSaveAlerts; // Save Alerts - bool eaLogAlerts; // Log Alerts - bool eaMailAlerts; // Mail Alerts - bool eaPushAlerts; // Push Alerts - bool eaTerminalAlerts; // Terminal Alerts - - // - // Time Report ... - bool eaReportNewMonths; // Report New Month - bool eaReportNewWeeks; // Report New Weeks - bool eaReportNewDays; // Report New Days - bool eaReportNewHours; // Report New Hours - bool eaReportTrades; // Report Trades - bool eaReportSignals; // Report Signals - bool eaReportProtector; // Report Protector Actions - bool eaReportRestrictions; // Report Restrictions - bool eaReportAfterTradesBalance; // Report Balance after a Trade Finished - - // - // Collector ... - bool eaSaveTrades; // Save Trades - bool eaSaveSignals; // Save Signals - bool eaSaveWins; // Save Winning Conditions - bool eaSaveLosts; // Save Lost Conditions - bool eaSaveRestrictions; // Save Restriction Reports - - // - // Trade Event Handlers ... - TOnModify OnModifyEventHandler; - TOnStopLoss OnStopLossEventHandler; - TOnForceClose OnForceCloseEventHandler; - TOnTakeProfit OnTakeProfitEventHandler; - TOnPartialClose OnPartialCloseEventHandler; - TOnDealsChanged OnDealsChangedEventHandler; - TOnOrdersChanged OnOrdersChangedEventHandler; - TOnPositionsChanged OnPositionsChangedEventHandler; - TOnTradeStateChanged OnTradeStateChangedEventHandler; - - // - // Requirements ... - - // - XCAlert *eaAlert; // EA Scope Alert Handler ... - XCTrade *eaTrade; // EA Scope Trade Handler ... - XCGuard *eaGuard; // EA Scope Guard Handler ... - XCVolume *eaVolume; // EA Scope Voluem Handler ... - XTimeTracker eaTimeTracker; // EA Scope Time Tracker ... - - // - // Tools / Actions / Handlers ... - - // - // Validators ... - - /** - * Validate Inputs ... - * - * @return ( bool ) - */ - bool ValidateInputs() - { - // - bool result = false; - - // - // Implement all Inputs Validation ... - result = eaMagicNumber > 0 && - eaSignalR2R > 0; - - // - return result; - } - - // - // Expert Advisor Event Handlers ... - - /** - * Handle Initialization of Expert ... - * - * @return ( bool ) - */ - bool HandleOnInit() - { - // - bool result = false; - - // - // Validate Inputs ... - result = ValidateInputs(); - if (!result) - { - return result; - } - - // - // Initialize Alert Handler ... - eaAlert = new XCAlert(); - eaAlert.SetPrefix(eaLogSuffix); - eaAlert.SetLogAlerts(eaLogAlerts); - eaAlert.SetMailAlerts(eaMailAlerts); - eaAlert.SetPushAlerts(eaPushAlerts); - eaAlert.SetEnableAlerts(eaEnableAlerts); - eaAlert.SetTerminalAlerts(eaTerminalAlerts); - - // - // Initialize Volume Manager ... - eaVolume = new XCVolume(); - result = eaVolume.Init( - eaVolumeSelect, - eaStaticVoluem, - eaDynamicVolumeStepBalance, - eaDynamicVolumeStepVolume, - eaConstantRiskBalance, - eaConstantPercent, - eaConstantBalance // - ); - if (!result) - { - return result; - } - - // - // Initialize Trader ... - eaTrade = new XCTrade( - eaSlippage, - eaMagicNumber, - eaMaxAllowedSpread, - eaMaxAllowedPositions, - eaMaxAllowedDrawdownFactor // - ); - eaTrade.AddOnStopLossEventHandler(OnStopLossEventHandler); - eaTrade.AddOnTakeProfitEventHandler(OnTakeProfitEventHandler); - eaTrade.AddOnModifyPositionEventHandler(OnModifyEventHandler); - eaTrade.AddOnDealsChangedEventHandler(OnDealsChangedEventHandler); - eaTrade.AddOnOrdersChangedEventHandler(OnOrdersChangedEventHandler); - eaTrade.AddOnForceClosePositionEventHandler(OnForceCloseEventHandler); - eaTrade.AddOnPartialClosePositionEventHandler(OnPartialCloseEventHandler); - eaTrade.AddOnPositionsChangedEventHandler(OnPositionsChangedEventHandler); - eaTrade.AddOnTradeStateChangedEventHandler(OnTradeStateChangedEventHandler); - - // - // Initialize Guard Handler ... - eaGuard = new XCGuard( - eaAlert, - eaTrade // - ); - - // - // Initialize Trae Manager ... - eaTradeManager = new XCXCATBEATradeManager( - eaAlert, - eaTrade // - ); - - // - eaTradeManager.SaveWins(eaSaveWins); - eaTradeManager.SaveLosts(eaSaveLosts); - eaTradeManager.SaveTrades(eaSaveTrades); - eaTradeManager.SaveSignals(eaSaveSignals); - eaTradeManager.SaveRestrictions(eaSaveRestrictions); - - // - // Enable Force Close At ... - eaTradeManager.SetForceCloseTradesAt(eaCloseAllOpenTradesAt); - - // - // Setting Trade Reports ... - eaTradeManager - .SetTradeReports( - eaReportTrades, - eaReportSignals, - eaReportProtector, - eaReportRestrictions, - eaReportAfterTradesBalance // - ); - - // - // Setting Trade Permissions ... - eaTradeManager - .SetTradePermissions( - eaAllowTrade, - eaAllowLongs, - eaAllowShorts // - ); - - // - // Setting Trade Restrictions ... - eaTradeManager - .SetTradeRestrictions( - eaRestrictionsPeriod, - eaMaxAllowedTPs, - eaMaxAllowedSLs, - eaMaxAllowedTrades // - ); - - // - // Parsing Symbols ... - - // - string symbols[]; - int symbolsCount = 0; - if (IsValid(eaSymbols)) - { - // - symbolsCount = SplitContent( - symbols, - eaSymbols, - "," // - ); - } - - // - // Adding Default Symbol, if eaSymbols not Filled ... - if (!HasChild(symbols)) - { - // - Add( - _Symbol, - symbols // - ); - - // - symbolsCount = ArraySize(symbols); - } - bool hasSymbols = HasChild(symbols); - - // - // Initializing Sessions ... - string sessions[]; - int sessionsCount = 0; - bool hasSession = IsValid(eaSessions); - if (hasSession) - { - // - // Extract Per Symbol Sessions ... - sessionsCount = SplitContent( - sessions, - eaSessions, - "," // - ); - - // - // Try to Extract Start and End Times Series ... - hasSession = IsValidSize(sessionsCount); - if (hasSession) - { - // - // Iterate Sessions ... - for (int i = 0; i < sessionsCount; i++) - { - // - // Ignore unused Cases and Extracts only Content ... - string iSessionDescriptorStr = ExtractString(sessions[i]); - bool isInited = IsValid(iSessionDescriptorStr); - if (isInited) - { - // - // Extract Session Descriptor Data ... - string parts[]; - int partsCount = SplitContent( - parts, - iSessionDescriptorStr, - "_" // - ); - isInited = IsValidSize(partsCount) && partsCount == 3; - if (isInited) - { - // - string iName = parts[0]; - string iStart = parts[1]; - string iEnd = parts[2]; - isInited = IsValid(iName) && - IsValid(iStart) && - IsValid(iEnd); - if (isInited) - { - // - // Set Active Session Per Symbols ... - if (hasSymbols) - { - // - for (int j = 0; j < symbolsCount; j++) - { - // - eaTradeManager - .SetTradeSession( - symbols[j], - iStart, - iEnd, - iName // - ); - } - } - } - } - } - } - } - } - - // - // Initialize Signallers ... - if (hasSymbols) - { - // - // Prepare Signaller Inputs ... - XCATBEASignallerInputs iSignallerInputs; - - // - // Common Configs ... - - // - // Provider Name ... - iSignallerInputs.period = _Period; - iSignallerInputs.allowDraws = true; - iSignallerInputs.provider = "XTRGB"; - iSignallerInputs.allowGuards = eaAllowGuards; - iSignallerInputs.riskToRewardRatio = eaSignalR2R; - iSignallerInputs.slATRMultiplier = eaSLATRMultiplier; - - // - // CATB Indicator ... - iSignallerInputs.catbInputs.Default(); - iSignallerInputs.catbInputs.Hide(); - - // - // Make Available all Requirement Buffers of XCATB indicator ... - iSignallerInputs.catbInputs.showPV = false; - iSignallerInputs.catbInputs.showKI = false; - iSignallerInputs.catbInputs.showSar = false; - iSignallerInputs.catbInputs.showTrend = false; - iSignallerInputs.catbInputs.showATRBand = false; - iSignallerInputs.catbInputs.showPVGolden = false; - - // - // Signalling Configurations ... - iSignallerInputs.signallerConfigs.allowSignallingBasedOnConditions = eaAllowSignallingBasedOnConditions; - iSignallerInputs.signallerConfigs.allowSignallingBasedOnTriggerBlocks = eaAllowSignallingBasedOnTriggerBlocks; - iSignallerInputs.signallerConfigs.secondsTriggersSLUsingFirstTriggerBlock = eaSecondsTriggersSLUsingFirstTriggerBlock; - iSignallerInputs.signallerConfigs.applyValidateAndFilterOnSelectInsideOthers = eaApplyValidateAndFilterOnSelectInsideOthers; - iSignallerInputs.signallerConfigs.allowSignallingBasedOnTriggerBlocksInsideOther = eaAllowSignallingBasedOnTriggerBlocksInsideOther; - iSignallerInputs.signallerConfigs.allowSignallingConditions1 = eaAllowSignallingConditions1; - iSignallerInputs.signallerConfigs.allowSignallingConditions2 = eaAllowSignallingConditions2; - iSignallerInputs.signallerConfigs.allowSignallingConditions3 = eaAllowSignallingConditions3; - iSignallerInputs.signallerConfigs.allowSignallingConditions4 = eaAllowSignallingConditions4; - iSignallerInputs.signallerConfigs.allowSignallingConditions5 = eaAllowSignallingConditions5; - iSignallerInputs.signallerConfigs.allowSignallingConditions6 = eaAllowSignallingConditions6; - // - // Prepare Trigger Block Validations ... - - // - iSignallerInputs.validations.forceHasSwing = eaForceHasSwing; - iSignallerInputs.validations.forceOBBarType = eaForceOBBarType; - iSignallerInputs.validations.minRequiredOBBar = eaMinRequiredOBBar; - iSignallerInputs.validations.forceFVGBarType = eaForceFVGBarType; - iSignallerInputs.validations.liquidityLoopback = eaLiquidityLoopback; - iSignallerInputs.validations.maxAllowedRange = eaMaxAllowedRange; - iSignallerInputs.validations.minAllowedRange = eaMinAllowedRange; - iSignallerInputs.validations.forceHasFLiquidity = eaForceHasFLiquidity; - iSignallerInputs.validations.forceHasRLiquidity = eaForceHasRLiquidity; - iSignallerInputs.validations.validateGapSequence = eaValidateGapSequence; - iSignallerInputs.validations.minAllowedBlockLength = eaMinAllowedBlockLength; - iSignallerInputs.validations.validateBlockEdgeBreakout = eaValidateBlockEdgeBreakout; - - // - // Prepare Trigger Block Filters ... - - // - iSignallerInputs.filters.filterBasedOnPV = eaFilterBasedOnPV; - iSignallerInputs.filters.bosLoopback = eaBosLoopback; - - // - iSignallerInputs.filters.filterBasedOnSar = eaFilterBasedOnSar; - iSignallerInputs.filters.forceSarSwitched = eaForceSarSwitched; - iSignallerInputs.filters.forceSarOnBothSide = eaForceSarOnBothSide; - iSignallerInputs.filters.forceSarHasBreakout = eaForceSarHasBreakout; - iSignallerInputs.filters.forceSarHasReversalSide = eaForceSarHasReversalSide; - - // - iSignallerInputs.filters.filterBasedOnRSI = eaFilterBasedOnRSI; - iSignallerInputs.filters.forceHasRSITrending = eaForceHasRSITrending; - iSignallerInputs.filters.forceHasRSIVPattern = eaForceHasRSIVPattern; - iSignallerInputs.filters.forceHasRSICrossing = eaForceHasRSICrossing; - - // - iSignallerInputs.filters.filterBasedOnADX = eaFilterBasedOnADX; - iSignallerInputs.filters.forceHasADXTrending = eaForceHasADXTrending; - iSignallerInputs.filters.forceHasADXCrossing = eaForceHasADXCrossing; - - // - iSignallerInputs.filters.filterBasedOnATR = eaFilterBasedOnATR; - iSignallerInputs.filters.forceHasATRTrending = eaForceHasATRTrending; - iSignallerInputs.filters.forceHasATRBreakout = eaForceHasATRBreakout; - - // - iSignallerInputs.filters.filterBasedOnTrend = eaFilterBasedOnTrend; - iSignallerInputs.filters.forceHasTrendDir = eaForceHasTrendDir; - iSignallerInputs.filters.forceHasTrendPlace = eaForceHasTrendPlace; - iSignallerInputs.filters.forceHasTrendChange = eaForceHasTrendChange; - iSignallerInputs.filters.forceHasTrendTrending = eaForceHasTrendTrending; - iSignallerInputs.filters.forceHasTrendRejection = eaForceHasTrendRejection; - iSignallerInputs.filters.forceHasTrendLineInside = eaForceHasTrendLineInside; - iSignallerInputs.filters.forceHasTrendDirOnBothSide = eaForceHasTrendDirOnBothSide; - - // - iSignallerInputs.filters.filterBasedOnKI = eaFilterBasedOnKI; - iSignallerInputs.filters.filterBasedOnDelta = eaFilterBasedOnDelta; - iSignallerInputs.filters.filterBasedOnVolume = eaFilterBasedOnVolume; - iSignallerInputs.filters.filterBasedOnSignalBar = eaFilterBasedOnSignalBar; - iSignallerInputs.filters.filterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar; - - // - // Loop through Symbols and Initialize Signaller - // for it, then Attached it to eaSignallers ... - for (int i = 0; i < symbolsCount; i++) - { - // - iSignallerInputs.symbol = symbols[i]; - if (iSignallerInputs.IsValid()) - { - // - // Initialize Signaller ... - XCXCATBEASignaller *iSignaller = new XCXCATBEASignaller(iSignallerInputs); - - // - // Add it to the Signallers List ... - Add( - iSignaller, - eaSignallers // - ); - - // - ZeroMemory(iSignaller); - } - } - - // - // Cleanup Resources ... - iSignallerInputs.Clean(); - } - - // - // since atleast one Signaller must - // exists to Expert works ... - // we check it as Last Step ... - result = hasSymbols && - HasChild(eaSignallers); - if (result) - { - // - string message = "Initialized Successfully ..."; - eaAlert.SendAlert(message); - } - else - { - // - string message = "Initialization Failed ..."; - eaAlert.SendAlert(message); - } - - // - return result; - } - - /** - * Handle De Initialization of Expert ... - */ - void HandleOnDeInit() - { - // - delete eaTrade; - ZeroMemory(eaTrade); - - // - delete eaGuard; - ZeroMemory(eaGuard); - - // - delete eaVolume; - ZeroMemory(eaVolume); - - // - eaTimeTracker.Clean(); - - // - Clean(eaSignallers); - - // - delete eaTradeManager; - ZeroMemory(eaTradeManager); - - // - string message = "DeInitialized Successfully ..."; - eaAlert.SendAlert(message); - - // - delete eaAlert; - ZeroMemory(eaAlert); - } - - /** - * Handle Tick ... - */ - void HandleOnTick() - { - // - // Time Report Handling ... - HandleTimeReport(); - - // - // Position Management / Protections Handling ... - eaTradeManager.Manage(); - - // - // Check Signallers Registered ... - bool has = HasChild(eaSignallers); - if (!has) - { - return; - } - - // - // Define Collection of Requirements ... - XGuard guards[]; - XCATBEAStrategyConditions conditions[]; - - // - // Loop through Registered Signallers to Proccess Ticks and - // Collect: - // - Guards; - // - Triggered Conditions; - // - ... - int count = ArraySize(eaSignallers); - for (int i = 0; i < count; i++) - { - // - // Retrieve indexed Signaller ... - XCXCATBEASignaller *iSignaller = eaSignallers[i]; - - // - string iSymbol = iSignaller.GetSymbol(); - string iProvider = iSignaller.GetProvider(); - ENUM_TIMEFRAMES iPeriod = iSignaller.GetPeriod(); - - // - // Now we Have to Check Handle Tick Resoult ... - - // - // Requirements ... - XGuard iGuards[]; // Hold Provided Guards ... - XPosition iPositions[]; // Retrieve Signaller Positions ... - XCATBEAStrategyConditions iConditions; // Recieve Triggered Conditions ... - - // - // Check Active Session ... - bool isActiveSession = eaTradeManager.IsActiveSession(iSymbol); - - // - // Reading Signaller Positions ... - eaTradeManager.GetPositions( - iPositions, - iSymbol, - iProvider, - iPeriod // - ); - - // - // Processing Tick for Signaller ... - iSignaller.ProcessTick( - iPositions, - iGuards, - iConditions, - isActiveSession // - ); - - // - // Check Results ... - has = HasChild(iGuards); - if (has) - { - // - Copy( - iGuards, - guards, - false // Force Clean ... - ); - } - - // - // Check Triggered Conditions ... - has = iConditions.IsValid() && - iConditions.IsSetuped() && - iConditions.CanTrigger(); - if (has) - { - // - AddRef( - iConditions, - conditions // - ); - } - - // - // Cleanup Resources ... - Clean(iGuards); - Clean(iPositions); - iConditions.Clean(); - } - - // - // Do Actions Based on Provided Info ... - - // - // Guards ... - has = HasChild(guards); - if (has) - { - // - // Handle Guards Firing ... - eaGuard.DoGuards(guards); - } - - // - // Triggers ... - has = HasChild(conditions); - if (has) - { - // - // Handle Conditions Triggering ... - TriggerConditions(conditions); - } - - // - // Cleanup Resources ... - - // - Clean(guards); - Clean(conditions); - } - - /** - * Handle Trade ... - */ - void HandleOnTrade() - { - } - - /** - * Handle Timer ... - */ - void HandleOnTimer() - { - } - - /** - * Handle Chart Event ... - * - * @param id: int, Event id ... - * @param lparam: long, Event Long Parameter ... - * @param dparam: double, Event Double Parameter ... - * @param sparam: string, Event String Parameter ... - */ - void HandleOnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // - ) - { - } - - // - // Trade Event Handlers ... - - /** - * Handle Stop Loss Event Triggered ... - * - * @param deal: XDeal instance refrence, provides Triggered Deal info ... - */ - void HandleOnStopLossTriggered(const XDeal &deal) - { - } - - /** - * Handle Take Profit Event Triggered ... - * - * @param deal: XDeal instance refrence, provides Triggered Deal info ... - */ - void HandleOnTakeProfitTriggered(const XDeal &deal) - { - } - - /** - * Handle Position Force Closed Event ... - * - * @param ticket: ulong, triggered Positions ticket ... - * @param position: XPosition instance refrence, Triggered Position ... - * @param comment: string, Comment ... - */ - void HandleOnPositionForceClosed( - const ulong ticket, - const XPosition &position, - const string comment // - ) - { - } - - /** - * Handle Position Modified Event ... - * - * @param ticket: ulong, triggered Positions ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ - void HandleOnPositionModified( - const ulong ticket, - const double profit, - const string comment // - ) - { - } - - /** - * Handle Position Partially Closed Event ... - * - * @param ticket: ulong, triggered Positions ticket ... - * @param profit: double, Position Profit ... - * @param comment: string, Comment ... - */ - void HandleOnPositionPartialClosed( - const ulong ticket, - const double profit, - const string comment // - ) - { - } - - /** - * Handle Deals Changed ... - * - * @param count: int, number of changes ... - * if the count is positive, means new added ... - * if the count is negative, means removed ... - */ - void HandleOnDealsChanged(int count) - { - } - - /** - * Handle Orders Changed ... - * - * @param count: int, number of changes ... - * if the count is positive, means new added ... - * if the count is negative, means removed ... - */ - void HandleOnOrdersChanged(int count) - { - } - - /** - * Handle Positions Changed ... - * - * @param count: int, number of changes ... - * if the count is positive, means new added ... - * if the count is negative, means removed ... - */ - void HandleOnPositionsChanged(int count) - { - } - - /** - * Handle all Trades States Changed Event ... - * - * @param state: XOnTradeHandlerState instance refrence, Changed Trade State data ... - */ - void HandleOnTradeStateChanged(const XOnTradeHandlerState &state) - { - } - - // - // protected ... - protected: - // - - /** - * Report Time Changes based on Given Configurations ... - */ - void HandleTimeReport() - { - // - if (eaAlert == NULL) - { - return; - } - - // - // Monthly Report .... - if (eaReportNewMonths && - eaTimeTracker.IsNewMonth()) - { - // - string msg = "New Month ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Weekly Report .... - if (eaReportNewWeeks && - eaTimeTracker.IsNewWeek()) - { - // - string msg = "New Week ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Daily Report .... - if (eaReportNewDays && - eaTimeTracker.IsNewDay()) - { - // - string msg = "New Day ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Hourly Report .... - if (eaReportNewHours && - eaTimeTracker.IsNewHour()) - { - // - string msg = "New Hour ..."; - - // - eaAlert.SendAlert(msg); - } - } - - /** - * Update Signal Targets ... - */ - void UpdateSignalTargets(XSignal &signal) - { - // - bool has = signal.IsValid(); - if (!has) - { - return; - } - - // - // Clean Signal Targets ... - Clean(signal.targets); - - // - // Calculate Requirements ... - double r2r = eaSignalR2R > 0 - ? eaSignalR2R - : 1; - double risk = signal.GetRisk(); - double reward = risk * r2r; - - // - double isLong = IsLong(signal.type); - - // - // Handling Signal TP ... - signal.tp = - isLong - ? signal.entry + reward - : signal.entry - reward; - - // - // Try to Apply Money Management ... - - // - // Sort Targets ... - ENUM_X_DIRECTION sortingDir = - isLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - ApplySortOnTargets( - sortingDir, - signal.targets // - ); - } - - /** - * Convert a Triggered Conditions to Signal and - * Execute it ... - */ - void TriggerConditions(XCATBEAStrategyConditions &conditions[]) - { - // - int count = 0; - bool has = false; - - // - has = HasChild(conditions); - if (!has) - { - return; - } - - // - count = ArraySize(conditions); - for (int i = 0; i < count; i++) - { - // - // Retrieve Indexed Conditions ... - XCATBEAStrategyConditions iConditions = conditions[i]; - - // - // Define Signal Structure ... - XSignal iSignal; - - // - // Check Conditions is Valid Triggered Conditions ... - has = - iConditions.IsValid() && - iConditions.IsSetuped() && - iConditions.CanTrigger(); - if (has) - { - // - // Preparing Signal ... - has = ToSignal( - iSignal, - iConditions // - ); - } - - // - // Validate Signal ... - has = iSignal.IsValid(); - if (has) - { - // - // Retrieve Signal Type ... - bool isLong = IsLong(iSignal.type); - - // - // Update Signal Entry ... - iSignal.entry = GetEntry( - iSignal.symbol, - iSignal.type // - ); - - // - // Update Signal Targets ... - UpdateSignalTargets(iSignal); - - // - // Handle Volume Management ... - double iVolume = eaVolume.CalculateVolume(iSignal); - has = iVolume > X_MIN_VOLUME && - iVolume != iSignal.volume; - if (has) - { - iSignal.volume = iVolume; - } - - // - // Execute Signal ... - has = eaTradeManager.Execute( - iSignal, - iConditions // - ); - } - - // - // Cleanup Resources ... - - // - iSignal.Clean(); - iConditions.Clean(); - } - } - - // - // private ... - private: - // - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/xcatb.test.ea.mq5 b/Documents/BKP/xcatb.test.ea.mq5 deleted file mode 100644 index 6bdc6fad..00000000 --- a/Documents/BKP/xcatb.test.ea.mq5 +++ /dev/null @@ -1,1181 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XCATB MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XCAEA -// Description: an Exper Advisor which used XCATB -// -// 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 "EA based on X121 XCATB indicator" -#property strict - -// -// Include Common Library ... -#include "../Classes/x-saherelm.x-guard.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" -#include "../XCATBEA/Classes/xcatbea.signaller.class.mq5" -#include "../XCATBEA/Classes/xcatbea.x-trade.manager.class.mq5" - -// -#define ShortName "XCATBEA" - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 1694056; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Detector ... -input group "Detector"; - -// -// Validating ... -input group "Validations"; -input bool eaForceHasSwing = false; // Force Block to Has Propper Swing -input bool eaForceOBBarType = false; // Force Order Block to Has InDirectional Bars -input int eaMinRequiredOBBar = 0; // Min Required OB Bar -input bool eaForceFVGBarType = false; // Force Fair Value Gaps Bars Type -input int eaLiquidityLoopback = 0; // Liquidity Detection Loopback -input double eaMaxAllowedRange = 0.0; // Max Allowed Order Block Range -input double eaMinAllowedRange = 0.0; // Min Allowed Order Block Range -input bool eaForceHasFLiquidity = false; // Force Order Block To Has Reversal Liquidity -input bool eaForceHasRLiquidity = false; // Force Order Block to Has Following Liquidity -input bool eaValidateGapSequence = false; // Validate Fair Value Gaps Bar Sequences -input int eaMinAllowedBlockLength = 0; // Min Allowed Block Length -input bool eaValidateBlockEdgeBreakout = false; // Validate Order Block Edge Breakeout - -// -// Filtering ... -input group "Filters"; -input bool eaFilterBasedOnKI = false; // Filter Based On KI Flats -input bool eaFilterBasedOnPV = false; // Filter Based On PV -input int eaBosLoopback = 0; // PV Based Filtering BOS Lookup -input bool eaFilterBasedOnSar = false; // Filter Based On SAR -input bool eaForceSarSwitched = false; // SAR Switched on Sides for Filtering -input bool eaForceSarOnBothSide = false; // SAR Check on Both Sides for Filtering -input bool eaForceSarHasBreakout = false; // SAR Must Breakout -input bool eaForceSarHasReversalSide = false; // SAR Must Has Reversal Direction -input bool eaFilterBasedOnRSI = false; // Filter Based On RSI -input bool eaForceHasRSITrending = false; // RSI Must Has V Trending -input bool eaForceHasRSIVPattern = false; // RSI Must Has Pattern -input bool eaForceHasRSICrossing = false; // RSI Must Has Crossing Levels -input bool eaFilterBasedOnADX = false; // Filter Based On ADX -input bool eaForceHasADXTrending = false; // ADX Must Has Trending -input bool eaForceHasADXCrossing = false; // ADX Must Has Crossing +DI/-DI -input bool eaFilterBasedOnATR = false; // Filter Based On ATR -input bool eaForceHasATRTrending = false; // ATR Must Has Trending -input bool eaForceHasATRBreakout = false; // ATR Must Has Breakout -input bool eaFilterBasedOnTrend = false; // Filter Based On Trend -input bool eaForceHasTrendDir = false; // TREND Must Has Following Direction -input bool eaForceHasTrendPlace = false; // TREND Place Based Filtering -input bool eaForceHasTrendChange = false; // TREND Change Filtering -input bool eaForceHasTrendTrending = false; // TREND Must Has Trending -input bool eaForceHasTrendRejection = false; // TREND Line Must Rejected -input bool eaForceHasTrendLineInside = false; // TREND Line has Inside -input bool eaForceHasTrendDirOnBothSide = false; // TREND Must Has Following Direction in Both Side -input bool eaFilterBasedOnDelta = false; // Filter Based On Delta -input bool eaFilterBasedOnVolume = false; // Filter Based On Volume -input bool eaFilterBasedOnSignalBar = false; // Filter Based on Signal Bar -input bool eaFilterBasedOnHKSignalBar = false; // Filter Based On HK Signal Bar - -// -// Signal ... -input group "Signal"; -input int eaSignalR2R = 2; // Risk Reward Ratio -input double eaSLATRMultiplier = 0; // ATR Multiplier for SL -input bool eaAllowSignallingBasedOnConditions; // Signalling Based on Market Conditions -input bool eaAllowSignallingBasedOnTriggerBlocks; // Signalling Based on Trigger Blocks -input bool eaAllowSignallingBasedOnTriggerBlocksInsideOther; // Signalling Based on Trigger Blocks Seccond inputs -input bool eaSecondsTriggersSLUsingFirstTriggerBlock; // Use First Trigger Block for SL of Seconds Trigger Block Signalss -input bool eaApplyValidateAndFilterOnSelectInsideOthers; // Select Trigger Blocks by Applying Validations and Filterss -input bool eaAllowSignallingConditions1; // Allow Market Conditions Signaller to Using Sar Signals -input bool eaAllowSignallingConditions2; // Allow Market Conditions Signaller to Using Trend Signals -input bool eaAllowSignallingConditions3; // Allow Market Conditions Signaller to Using Delta Signals -input bool eaAllowSignallingConditions4; // Allow Market Conditions Signaller to Using Volume Signals -input bool eaAllowSignallingConditions5; // Allow Market Conditions Signaller to Using Signal Bar Signals -input bool eaAllowSignallingConditions6; // Allow Market Conditions Signaller to Using HK Signal Bar Signals - -// -// Volume ... -input group "Volume"; -input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_EQUITY; // Volume Applying Type -input double eaStaticVoluem = 0.0; // Static Volume -input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume -input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing -input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade -input double eaConstantPercent = 0.5; // Constant Percent of Balance Per Trade -input double eaConstantBalance = 0.0; // Constant Balance for Calculations - -// -// Management ... -// eaSessions => (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00) -input group "Management"; -input bool eaAllowGuards = false; // Allow Guards -input bool eaAllowTrade = true; // Allow Trade on Signals -input bool eaAllowLongs = true; // Allow Long Trades -input bool eaAllowShorts = true; // Allow Short Trades -input string eaSessions = ""; // Active Sessions -input ENUM_XCATBEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCATBEA_TRADE_RESTRICATION_NONE; // Restrictions Period -input int eaMaxAllowedTPs = 0; // Max Allowed TP(s) in Restrictions Period -input int eaMaxAllowedSLs = 0; // Max Allowed SL(s) in Restrictions Period -input int eaMaxAllowedTrades = 0; // Max Allowed Trades in Restrictions Period -input int eaMaxAllowedPositions = 5; // Max Allowed Same Time Trades -input double eaMaxAllowedSpread = 25; // Max Allowed Spread For Trade -input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade -input string eaCloseAllOpenTradesAt = ""; // Close All Open Trades per Day At Specified Time - -// -// 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 = true; // Push Alerts -input bool eaTerminalAlerts = false; // Terminal Alerts - -// -// Time Report ... -input group "Reports"; -input bool eaReportNewMonths = false; // Report New Month -input bool eaReportNewWeeks = false; // Report New Weeks -input bool eaReportNewDays = true; // Report New Days -input bool eaReportNewHours = false; // Report New Hours -input bool eaReportTrades = true; // Report Trades -input bool eaReportSignals = true; // Report Signals -input bool eaReportRestrictions = true; // Report Restrictions -input bool eaReportProtector = true; // Report Protector Actions -input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished - -// -// Collector ... -input group "Collector"; -input bool eaSaveTrades = false; // Save Trades -input bool eaSaveSignals = false; // Save Signals -input bool eaSaveWins = false; // Save Winning Conditions -input bool eaSaveLosts = false; // Save Lost Conditions -input bool eaSaveRestrictions = false; // Save Restriction Reports - -// -// Variables ... - -// -XCAlert *eaAlert; // EA Scope Alert Handler ... -XCTrade *eaTrade; // EA Scope Trade Handler ... -XCGuard *eaGuard; // EA Scope Guard Handler ... -string eaTag = ""; // Specified Alert Tag for EA ... -XCVolume *eaVolume; // EA Scope Voluem Handler ... -XTimeTracker eaTimeTracker; // EA Scope Time Tracker ... -XCXCATBEASignaller *eaSignallers[]; // EA Signallers Collection ... -XCXCATBEATradeManager *eaTradeManager; // EA Scope Trade Manager ... - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initial Requirements ... - InitRequirements(); - - // - // Initialize Volume Manger ... - if (!InitVolume()) - { - return INIT_FAILED; - } - - // - return (INIT_SUCCEEDED); -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - delete eaAlert; - ZeroMemory(eaAlert); - - // - delete eaTrade; - ZeroMemory(eaTrade); - - // - delete eaGuard; - ZeroMemory(eaGuard); - - // - delete eaVolume; - ZeroMemory(eaVolume); - - // - eaTimeTracker.Clean(); - - // - Clean(eaSignallers); - - // - delete eaTradeManager; - ZeroMemory(eaTradeManager); - - // - DestroyTimer(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - // Time Report Handling ... - HandleTimeReport(); - - // - // Position Management / Protections Handling ... - eaTradeManager.Manage(); - - // - // Count Signallers ... - bool has = HasChild(eaSignallers); - if (!has) - { - return; - } - - // - XGuard guards[]; - XCATBEAStrategyConditions conditions[]; - - // - int count = ArraySize(eaSignallers); - for (int i = 0; i < count; i++) - { - // - // Retrieve indexed Signaller ... - XCXCATBEASignaller *iSignaller = eaSignallers[i]; - - // - string iSymbol = iSignaller.GetSymbol(); - string iProvider = iSignaller.GetProvider(); - ENUM_TIMEFRAMES iPeriod = iSignaller.GetPeriod(); - - // - // Now we Have to Check Handle Tick Resoult ... - - // - // Requirements ... - XGuard iGuards[]; // Hold Provided Guards ... - XPosition iPositions[]; // Retrieve Signaller Positions ... - XCATBEAStrategyConditions iConditions; // Recieve Triggered Conditions ... - - // - // Reading Signaller Positions ... - eaTradeManager.GetPositions( - iPositions, - iSymbol, - iProvider, - iPeriod // - ); - - // - // Processing Tick for Signaller ... - iSignaller.ProcessTick( - iPositions, - iGuards, - iConditions // - ); - - // - // Check Results ... - has = HasChild(iGuards); - if (has) - { - // - Copy( - iGuards, - guards, - false // Force Clean ... - ); - } - - // - // Check Triggered Conditions ... - has = iConditions.IsValid() && - iConditions.IsSetuped() && - iConditions.CanTrigger(); - if (has) - { - // - AddRef( - iConditions, - conditions // - ); - } - - // - // Cleanup Resources ... - Clean(iGuards); - Clean(iPositions); - iConditions.Clean(); - } - - // - // Do Actions Based on Provided Info ... - - // - // Guards ... - has = HasChild(guards); - if (has) - { - // - // Handle Guards Firing ... - eaGuard.DoGuards(guards); - } - - // - // Triggers ... - has = HasChild(conditions); - if (has) - { - // - // Handle Conditions Triggering ... - TriggerConditions(conditions); - } - - // - // Cleanup Resources ... - - // - Clean(guards); - Clean(conditions); -} - -// -// Handle On Trade Event ... -void OnTrade() -{ - eaTrade.HandleOnTrade(); -} - -// -// On Timer ... -void OnTimer() -{ -} - -// -// Chart Event Handler ... -void OnChartEvent( - const int id, - const long &lparam, - const double &dparam, - const string &sparam // -) -{ -} - -// -// Event Listeners ... - -/** - * Handle StopLoss Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnStopLossTriggered(const XDeal &deal) -{ - eaTradeManager.HandleSL(deal); -} - -/** - * Handle Take Profit Triggered Positions ... - * - * @param deal: XDeal instance ... - */ -void OnTakeProfitTriggered(const XDeal &deal) -{ - eaTradeManager.HandleTP(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 // -) -{ - eaTradeManager.HandleForceClose(position); -} - -/** - * Handle Position Partially Closed Event ... - * - * @param ticket: ULONG ... - * @param profit: double ... - * @param comment: string ... - */ -void OnPositionPartiallyClosed( - const ulong ticket, - const double profit, - const string comment // -) -{ - eaTradeManager.HandlePartiallyClosed( - ticket, - profit, - comment // - ); -} - -/** - * 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) -{ -} - -// -// 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(); -} - -/** - * Initial Volume Manager Class Based on Given Configuration ... - * - * @return ( bool ) - */ -bool InitVolume() -{ - // - bool result = false; - - // - eaVolume = new XCVolume(); - - // - result = eaVolume.Init( - eaVolumeSelect, - eaStaticVoluem, - eaDynamicVolumeStepBalance, - eaDynamicVolumeStepVolume, - eaConstantRiskBalance, - eaConstantPercent, - eaConstantBalance // - ); - - // - return result; -} - -/** - * Initial Requirements of EA ... - */ -void InitRequirements() -{ - // - // Preparing Tags ... - eaTag = - (IsValid(eaLogSuffix) - ? eaLogSuffix + "_" - : "") + - ShortName; - - // - eaAlert = new XCAlert(); - eaAlert.SetPrefix(eaLogSuffix); - eaAlert.SetLogAlerts(eaLogAlerts); - eaAlert.SetMailAlerts(eaMailAlerts); - eaAlert.SetPushAlerts(eaPushAlerts); - eaAlert.SetEnableAlerts(eaEnableAlerts); - eaAlert.SetTerminalAlerts(eaTerminalAlerts); - - // - // EA Trade ... - eaTrade = new XCTrade( - eaSlippage, - eaMagicNumber, - eaMaxAllowedSpread, - eaMaxAllowedPositions, - eaMaxAllowedDrawdownFactor // - ); - - // - eaTrade.AddOnStopLossEventHandler(OnStopLossTriggered); - eaTrade.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); - eaTrade.AddOnForceClosePositionEventHandler(OnPositionForceClosed); - eaTrade.AddOnPartialClosePositionEventHandler(OnPositionPartiallyClosed); - - // - // EA Trae Manager ... - eaTradeManager = new XCXCATBEATradeManager( - eaTrade // - ); - - // - eaTradeManager.SetAlertPrefix(eaTag); - eaTradeManager.SetAlertLogAlerts(eaLogAlerts); - eaTradeManager.SetAlertMailAlerts(eaMailAlerts); - eaTradeManager.SetAlertPushAlerts(eaPushAlerts); - eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts); - eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts); - - // - eaTradeManager.SaveWins(eaSaveWins); - eaTradeManager.SaveLosts(eaSaveLosts); - eaTradeManager.SaveTrades(eaSaveTrades); - eaTradeManager.SaveSignals(eaSaveSignals); - eaTradeManager.SaveRestrictions(eaSaveRestrictions); - - // - // Setting Trade Reports ... - eaTradeManager - .SetTradeReports( - eaReportTrades, - eaReportSignals, - eaReportProtector, - eaReportRestrictions, - eaReportAfterTradesBalance // - ); - - // - // Setting Trade Permissions ... - eaTradeManager - .SetTradePermissions( - eaAllowTrade, - eaAllowLongs, - eaAllowShorts // - ); - - // - // Setting Trade Restrictions ... - eaTradeManager - .SetTradeRestrictions( - eaRestrictionsPeriod, - eaMaxAllowedTPs, - eaMaxAllowedSLs, - eaMaxAllowedTrades // - ); - - // - // EA Guard Initialization ... - eaGuard = new XCGuard( - eaTrade // - ); - - // - eaGuard.SetAlertPrefix(eaTag); - eaGuard.SetAlertLogAlerts(eaLogAlerts); - eaGuard.SetAlertMailAlerts(eaMailAlerts); - eaGuard.SetAlertPushAlerts(eaPushAlerts); - eaGuard.SetAlertEnableAlerts(eaEnableAlerts); - eaGuard.SetAlertTerminalAlerts(eaTerminalAlerts); - - // - // Initializing Sessions ... - string sessions[]; - int sessionsCount = 0; - bool hasSession = IsValid(eaSessions); - if (hasSession) - { - // - // Extract Per Symbol Sessions ... - sessionsCount = SplitContent( - sessions, - eaSessions, - "," // - ); - - // - // Try to Extract Start and End Times Series ... - hasSession = IsValidSize(sessionsCount); - if (hasSession) - { - // - // Iterate Sessions ... - for (int i = 0; i < sessionsCount; i++) - { - // - // Ignore unused Cases and Extracts only Content ... - string iSessionDescriptorStr = ExtractString(sessions[i]); - bool isInited = IsValid(iSessionDescriptorStr); - if (isInited) - { - // - // Extract Session Descriptor Data ... - string parts[]; - int partsCount = SplitContent( - parts, - iSessionDescriptorStr, - "_" // - ); - isInited = IsValidSize(partsCount) && partsCount == 3; - if (isInited) - { - // - string iName = parts[0]; - string iStart = parts[1]; - string iEnd = parts[2]; - isInited = IsValid(iName) && - IsValid(iStart) && - IsValid(iEnd); - if (isInited) - { - // - // Set Active Session ... - eaTradeManager - .SetTradeSession( - _Symbol, - iStart, - iEnd, - iName // - ); - } - } - } - } - } - } - - // - // Initializing Signaller(s) ... - string symbols[]; - Add( - _Symbol, - symbols // - ); - bool hasSymbols = HasChild(symbols); - if (hasSymbols) - { - // - // Prepare Signaller Inputs ... - XCATBEASignallerInputs iSignallerInputs; - - // - // Common Configs ... - - // - // Provider Name ... - iSignallerInputs.period = _Period; - iSignallerInputs.provider = "XTRGB"; - iSignallerInputs.allowGuards = eaAllowGuards; - iSignallerInputs.riskToRewardRatio = eaSignalR2R; - iSignallerInputs.allowDraws = IsRunningOnTestMode(); - iSignallerInputs.slATRMultiplier = eaSLATRMultiplier; - - // - // CATB Indicator ... - iSignallerInputs.catbInputs.Default(); - iSignallerInputs.catbInputs.Hide(); - - // - // Make Available all Requirement Buffers of XCATB indicator ... - iSignallerInputs.catbInputs.showPV = true; - iSignallerInputs.catbInputs.showKI = true; - iSignallerInputs.catbInputs.showATRBand = true; - iSignallerInputs.catbInputs.showPVGolden = true; - - // - // Trigger Block Validations ... - iSignallerInputs.validations.forceHasSwing = eaForceHasSwing; - iSignallerInputs.validations.forceOBBarType = eaForceOBBarType; - iSignallerInputs.validations.minRequiredOBBar = eaMinRequiredOBBar; - iSignallerInputs.validations.forceFVGBarType = eaForceFVGBarType; - iSignallerInputs.validations.liquidityLoopback = eaLiquidityLoopback; - iSignallerInputs.validations.maxAllowedRange = eaMaxAllowedRange; - iSignallerInputs.validations.minAllowedRange = eaMinAllowedRange; - iSignallerInputs.validations.forceHasFLiquidity = eaForceHasFLiquidity; - iSignallerInputs.validations.forceHasRLiquidity = eaForceHasRLiquidity; - iSignallerInputs.validations.validateGapSequence = eaValidateGapSequence; - iSignallerInputs.validations.minAllowedBlockLength = eaMinAllowedBlockLength; - iSignallerInputs.validations.validateBlockEdgeBreakout = eaValidateBlockEdgeBreakout; - - // - // Signalling Configurations ... - iSignallerInputs.signallerConfigs.allowSignallingBasedOnConditions = eaAllowSignallingBasedOnConditions; - iSignallerInputs.signallerConfigs.allowSignallingBasedOnTriggerBlocks = eaAllowSignallingBasedOnTriggerBlocks; - iSignallerInputs.signallerConfigs.secondsTriggersSLUsingFirstTriggerBlock = eaSecondsTriggersSLUsingFirstTriggerBlock; - iSignallerInputs.signallerConfigs.applyValidateAndFilterOnSelectInsideOthers = eaApplyValidateAndFilterOnSelectInsideOthers; - iSignallerInputs.signallerConfigs.allowSignallingBasedOnTriggerBlocksInsideOther = eaAllowSignallingBasedOnTriggerBlocksInsideOther; - iSignallerInputs.signallerConfigs.allowSignallingConditions1 = eaAllowSignallingConditions1; - iSignallerInputs.signallerConfigs.allowSignallingConditions2 = eaAllowSignallingConditions2; - iSignallerInputs.signallerConfigs.allowSignallingConditions3 = eaAllowSignallingConditions3; - iSignallerInputs.signallerConfigs.allowSignallingConditions4 = eaAllowSignallingConditions4; - iSignallerInputs.signallerConfigs.allowSignallingConditions5 = eaAllowSignallingConditions5; - iSignallerInputs.signallerConfigs.allowSignallingConditions6 = eaAllowSignallingConditions6; - - // - // Trigger Block Filters ... - - // - iSignallerInputs.filters.filterBasedOnPV = eaFilterBasedOnPV; - iSignallerInputs.filters.bosLoopback = eaBosLoopback; - - // - iSignallerInputs.filters.filterBasedOnSar = eaFilterBasedOnSar; - iSignallerInputs.filters.forceSarSwitched = eaForceSarSwitched; - iSignallerInputs.filters.forceSarOnBothSide = eaForceSarOnBothSide; - iSignallerInputs.filters.forceSarHasBreakout = eaForceSarHasBreakout; - iSignallerInputs.filters.forceSarHasReversalSide = eaForceSarHasReversalSide; - - // - iSignallerInputs.filters.filterBasedOnRSI = eaFilterBasedOnRSI; - iSignallerInputs.filters.forceHasRSITrending = eaForceHasRSITrending; - iSignallerInputs.filters.forceHasRSIVPattern = eaForceHasRSIVPattern; - iSignallerInputs.filters.forceHasRSICrossing = eaForceHasRSICrossing; - - // - iSignallerInputs.filters.filterBasedOnADX = eaFilterBasedOnADX; - iSignallerInputs.filters.forceHasADXTrending = eaForceHasADXTrending; - iSignallerInputs.filters.forceHasADXCrossing = eaForceHasADXCrossing; - - // - iSignallerInputs.filters.filterBasedOnATR = eaFilterBasedOnATR; - iSignallerInputs.filters.forceHasATRTrending = eaForceHasATRTrending; - iSignallerInputs.filters.forceHasATRBreakout = eaForceHasATRBreakout; - - // - iSignallerInputs.filters.filterBasedOnTrend = eaFilterBasedOnTrend; - iSignallerInputs.filters.forceHasTrendDir = eaForceHasTrendDir; - iSignallerInputs.filters.forceHasTrendPlace = eaForceHasTrendPlace; - iSignallerInputs.filters.forceHasTrendChange = eaForceHasTrendChange; - iSignallerInputs.filters.forceHasTrendTrending = eaForceHasTrendTrending; - iSignallerInputs.filters.forceHasTrendRejection = eaForceHasTrendRejection; - iSignallerInputs.filters.forceHasTrendLineInside = eaForceHasTrendLineInside; - iSignallerInputs.filters.forceHasTrendDirOnBothSide = eaForceHasTrendDirOnBothSide; - - // - iSignallerInputs.filters.filterBasedOnKI = eaFilterBasedOnKI; - iSignallerInputs.filters.filterBasedOnDelta = eaFilterBasedOnDelta; - iSignallerInputs.filters.filterBasedOnVolume = eaFilterBasedOnVolume; - iSignallerInputs.filters.filterBasedOnSignalBar = eaFilterBasedOnSignalBar; - iSignallerInputs.filters.filterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar; - - // - - // - // Loop Through Symbols for Signalling Initializing ... - int symbolsCount = ArraySize(symbols); - for (int i = 0; i < symbolsCount; i++) - { - // - string iSymbol = symbols[i]; - - // - iSignallerInputs.symbol = iSymbol; - if (iSignallerInputs.IsValid()) - { - // - // Initialize Signaller ... - XCXCATBEASignaller *iSignaller = new XCXCATBEASignaller(iSignallerInputs); - - // - // Add it to the Signallers List ... - Add( - iSignaller, - eaSignallers // - ); - - // - ZeroMemory(iSignaller); - } - } - - // - // Cleanup Resources ... - iSignallerInputs.Clean(); - } - - // -} - -/** - * Handling Time Reporting ... - */ -void HandleTimeReport() -{ - // - if (eaAlert == NULL) - { - return; - } - - // - // Monthly Report .... - if (eaReportNewMonths && - eaTimeTracker.IsNewMonth()) - { - // - string msg = "New Month ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Weekly Report .... - if (eaReportNewWeeks && - eaTimeTracker.IsNewWeek()) - { - // - string msg = "New Week ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Daily Report .... - if (eaReportNewDays && - eaTimeTracker.IsNewDay()) - { - // - string msg = "New Day ..."; - - // - eaAlert.SendAlert(msg); - } - - // - // Hourly Report .... - if (eaReportNewHours && - eaTimeTracker.IsNewHour()) - { - // - string msg = "New Hour ..."; - - // - eaAlert.SendAlert(msg); - } -} - -/** - * Update Signal Targets ... - */ -void UpdateSignalTargets(XSignal &signal) -{ - // - bool has = signal.IsValid(); - if (!has) - { - return; - } - - // - // Clean Signal Targets ... - Clean(signal.targets); - - // - // Calculate Requirements ... - double r2r = eaSignalR2R > 0 - ? eaSignalR2R - : 1; - double risk = signal.GetRisk(); - double reward = risk * r2r; - - // - double isLong = IsLong(signal.type); - - // - // Handling Signal TP ... - signal.tp = - isLong - ? signal.entry + reward - : signal.entry - reward; - - // - // Try to Apply Money Management ... - - // - // if (r2r <= 1) - // { - // return; - // } - - // - // XTarget iTarget; - - // // - // // Partial Close 0.5 of Position on Reward 1 ... - // reward = risk * 1; - // iTarget.target = - // isLong - // ? signal.entry + reward - // : signal.entry - reward; - // iTarget.volumeMultiplier = 0.5; - - // // - // AddRef(iTarget, signal.targets); - // iTarget.Clean(); - - // // - // if (r2r <= 2) - // { - // return; - // } - - // - // Making Loop ... - // for (int i = 2; i < ((int)r2r - 1); i++) - // { - // // - // iTarget.Clean(); - - // // - // reward = i * risk; - // iTarget.target = - // isLong - // ? signal.entry + reward - // : signal.entry - reward; - // iTarget.volumeMultiplier = 1 / (r2r - 2); - - // // - // AddRef(iTarget, signal.targets); - // } - - // - // Sort Targets ... - ENUM_X_DIRECTION sortingDir = - isLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - ApplySortOnTargets( - sortingDir, - signal.targets // - ); -} - -/** - * Convert a Triggered Conditions to Signal and - * Execute it ... - */ -void TriggerConditions(XCATBEAStrategyConditions &conditions[]) -{ - // - int count = 0; - bool has = false; - - // - has = HasChild(conditions); - if (!has) - { - return; - } - - // - count = ArraySize(conditions); - for (int i = 0; i < count; i++) - { - // - // Retrieve Indexed Conditions ... - XCATBEAStrategyConditions iConditions = conditions[i]; - - // - // Prepare Signal Based on Conditions ... - XSignal iSignal; - - // - // Check if a Trigger Block Attached and Has Signal ... - // use it ... - has = - iConditions.IsValid() && - iConditions.IsSetuped() && - iConditions.CanTrigger() && - iConditions.triggerBlock.IsValid() && - iConditions.triggerBlock.signal.IsValid(); - if (has) - { - iSignal = iConditions.triggerBlock.signal; - } - - // - // if we Have any other Signalling senarios we can Handle them here ... - - // - // Validate Signal ... - has = iSignal.IsValid(); - if (has) - { - // - // Retrieve Signal Type ... - bool isLong = IsLong(iSignal.type); - - // - // Update Signal Entry ... - iSignal.entry = GetEntry( - iSignal.symbol, - iSignal.type // - ); - - // - // Update Signal Targets ... - UpdateSignalTargets(iSignal); - - // - // Handle Volume Management ... - double iVolume = eaVolume.CalculateVolume(iSignal); - has = iVolume > X_MIN_VOLUME && - iVolume != iSignal.volume; - if (has) - { - iSignal.volume = iVolume; - } - - // - // Execute Signal ... - has = eaTradeManager.Execute( - iSignal, - iConditions // - ); - } - - // - // Cleanup Resources ... - - // - iSignal.Clean(); - iConditions.Clean(); - } -} - -// \ No newline at end of file diff --git a/Documents/BKP/xcatbea.x-data.collector.class.mq5 b/Documents/BKP/xcatbea.x-data.collector.class.mq5 deleted file mode 100644 index d16da67b..00000000 --- a/Documents/BKP/xcatbea.x-data.collector.class.mq5 +++ /dev/null @@ -1,209 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCATBEADataCollector ... -// Description: Class for XCATBEA Data Collector ... -// -// -// 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 Class for XCATBEA Data Collector" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.base.class.mq5" - -// -// Definitions ... - -// -// Implementation ... -class XCXCATBEADataCollector : public XCBase -{ - // - // Public ... - public: - // - // Constructors ... - XCXCATBEADataCollector() - { - } - - // - // Deconstructor ... - ~XCXCATBEADataCollector() - { - } - - // - // Properties ... - - // - string Path() - { - return mPath; - } - - // - void Path(string value) - { - // - // Normalizing Collector Path ... - if (IsValid(value)) - { - mPath = value; - } - else - { - mPath = "XCXCATBEADataCollector"; - } - } - - // - // Tools ... - - // - string GetFilePath(string fileName) - { - // - string result = ""; - - // - result = - // - mPath + "\\" + fileName + ".x121.log" - // - ; - - // - return result; - } - - // - int GetFileHandlerForWrite(string filePath) - { - // - int result = INVALID_HANDLE; - - // - if (!IsValid(filePath)) - { - return result; - } - - // - result = FileOpen( - filePath, - FILE_READ | FILE_WRITE | FILE_TXT // - ); - - // - return result; - } - - /** - * Save Specified Content into Specified File Name ... - * - * @param fileName: string, file name ... - * @param content: string, content ... - * - * @return ( bool ) - */ - bool Save( - string fileName, - string content // - ) - { - // - bool result = false; - - // - result = IsValid(content); - if (!result) - { - return result; - } - - // - // - int mHandler = GetFileHandlerForWrite(fileName); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - FileWrite(mHandler, content); - FileFlush(mHandler); - FileClose(mHandler); - - // - return result; - } - - /** - * Append Specified Content into Specified File Name ... - * - * @param fileName: string, file name ... - * @param content: string, content ... - * - * @return ( bool ) - */ - bool Append( - string fileName, - string content // - ) - { - // - bool result = false; - - // - result = IsValid(content); - if (!result) - { - return result; - } - - // - // - int mHandler = GetFileHandlerForWrite(fileName); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - FileSeek(mHandler, 0, SEEK_END); - FileWrite(mHandler, content); - FileFlush(mHandler); - FileClose(mHandler); - - // - return result; - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - - // - string mPath; // Base Collector Path ... -}; diff --git a/Documents/MQL5 VSCode.7z b/Documents/MQL5 VSCode.7z deleted file mode 100644 index a0e81380..00000000 Binary files a/Documents/MQL5 VSCode.7z and /dev/null differ