From a03a739e16d47b2e08ac984a85db08e5f06538ac Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sun, 1 Jun 2025 14:01:55 +0330 Subject: [PATCH] last ... --- Documents/BKP/1.mq5 | 243 - Documents/BKP/Consolidation_Detector_EA.mq5 | 233 - .../Indicators/x-saherelm.x121.xczone.2.mq5 | 2288 ------- .../BKP/Indicators/x-saherelm.x121.xczone.mq5 | 2288 ------- Documents/BKP/Tests/xcaea.cond2.script.mq5 | 647 -- .../Classes/xcaea.x-data.collector.class.mq5 | 167 - .../Classes/xcaea.x-poi.detector.class.mq5 | 4476 -------------- .../Classes/xcaea.x-poi.drawer.class.mq5 | 1490 ----- .../Classes/xcaea.x-trade.manager.class.mq5 | 2296 ------- .../XCAEA_BKP/XCAEA/Helpers/xcaea.helper.mq5 | 4822 --------------- .../XCAEA/Libraries/xcaea.signaller.lib.mq5 | 2927 --------- .../XCAEA/Signals/xcaea.signaller.class.mq5 | 1533 ----- Documents/BKP/XCAEA_BKP/tmp.detect.tb.mq5 | 1214 ---- .../XCAEA_BKP/x-saherelm.x121.xcatb.lib.mq5 | 3053 ---------- .../BKP/XCAEA_BKP/x-saherelm.x121.xcatb.mq5 | 2777 --------- .../BKP/XCAEA_BKP/x-saherelm.xcaea.ea.mq5 | 961 --- Documents/BKP/catb.test.ea.tmp.mq5 | 942 --- Documents/BKP/detect.block.base.trigger.mq5 | 218 - Documents/BKP/rsi.divergence.2.mq5 | 317 - Documents/BKP/rsi.divergence.mq5 | 198 - Documents/BKP/sample.mq5 | 2524 -------- Documents/BKP/test.1.mq5 | 181 - Documents/BKP/test.mq5 | 137 - Documents/BKP/tmp-1.mql4 | 770 --- Documents/BKP/tmp.guards.mq5 | 1167 ---- Documents/BKP/x-signal.tmp.mq5 | 2011 ------- .../BKP/xcaea.signaller.non-analyser.lib.mq5 | 2496 -------- Documents/BKP/xcaea.trigger.block.lib.mq5 | 1487 ----- Documents/BKP/xcaea.trigger.block.lib.old.mq5 | 4122 ------------- Documents/BKP/xcaea.x-poi.detector.class.mq5 | 5287 ----------------- Documents/BKP/xcatb.test.ea.mq5 | 1143 ---- Documents/BKP/xcatb.tm.inputs.mq5 | 316 - Documents/BKP/xczone.test.ea.mq5 | 1082 ---- 33 files changed, 55813 deletions(-) delete mode 100644 Documents/BKP/1.mq5 delete mode 100644 Documents/BKP/Consolidation_Detector_EA.mq5 delete mode 100644 Documents/BKP/Indicators/x-saherelm.x121.xczone.2.mq5 delete mode 100644 Documents/BKP/Indicators/x-saherelm.x121.xczone.mq5 delete mode 100644 Documents/BKP/Tests/xcaea.cond2.script.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-data.collector.class.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Helpers/xcaea.helper.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Libraries/xcaea.signaller.lib.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/XCAEA/Signals/xcaea.signaller.class.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/tmp.detect.tb.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.lib.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.mq5 delete mode 100644 Documents/BKP/XCAEA_BKP/x-saherelm.xcaea.ea.mq5 delete mode 100644 Documents/BKP/catb.test.ea.tmp.mq5 delete mode 100644 Documents/BKP/detect.block.base.trigger.mq5 delete mode 100644 Documents/BKP/rsi.divergence.2.mq5 delete mode 100644 Documents/BKP/rsi.divergence.mq5 delete mode 100644 Documents/BKP/sample.mq5 delete mode 100644 Documents/BKP/test.1.mq5 delete mode 100644 Documents/BKP/test.mq5 delete mode 100644 Documents/BKP/tmp-1.mql4 delete mode 100644 Documents/BKP/tmp.guards.mq5 delete mode 100644 Documents/BKP/x-signal.tmp.mq5 delete mode 100644 Documents/BKP/xcaea.signaller.non-analyser.lib.mq5 delete mode 100644 Documents/BKP/xcaea.trigger.block.lib.mq5 delete mode 100644 Documents/BKP/xcaea.trigger.block.lib.old.mq5 delete mode 100644 Documents/BKP/xcaea.x-poi.detector.class.mq5 delete mode 100644 Documents/BKP/xcatb.test.ea.mq5 delete mode 100644 Documents/BKP/xcatb.tm.inputs.mq5 delete mode 100644 Documents/BKP/xczone.test.ea.mq5 diff --git a/Documents/BKP/1.mq5 b/Documents/BKP/1.mq5 deleted file mode 100644 index 4bd1dda1..00000000 --- a/Documents/BKP/1.mq5 +++ /dev/null @@ -1,243 +0,0 @@ -//+------------------------------------------------------------------+ -//| SpikeDetectorEA.mq5 | -//| Copyright 2025, Your Name/Company | -//| https://www.example.com | -//+------------------------------------------------------------------+ -#property copyright "Copyright 2025, Your Name/Company" -#property link "https://www.example.com" -#property version "1.01" // Incremented version -#property description "Expert Advisor to detect and draw price spikes (pin bars)." - -//--- Input Parameters -input group "Spike Definition" input double InpMinWickToBodyRatio = 2.0; // Minimum ratio of the main wick to the body (e.g., 2.0 means wick is 2x body) -input double InpMaxOppositeWickToBodyRatio = 1.0; // Maximum ratio of the opposite wick to the body (e.g., 1.0 means opposite wick <= body) -input double InpMaxBodyToTotalRangeRatio = 0.33; // Maximum ratio of body to total candle range (H-L) (e.g., 0.33 means body is < 1/3 of range) - -input group "Drawing Settings" input int InpArrowOffsetPoints = 10; // Arrow offset from High/Low in points -input color InpBullishSpikeColor = clrLimeGreen; // Color for bullish spike arrows -input color InpBearishSpikeColor = clrRed; // Color for bearish spike arrows -input int InpLookbackForDrawing = 200; // How many past bars to check on EA load/recompile - -// Wingdings Arrow Codes (commonly used for OBJ_ARROW) -#define WINGDINGS_ARROW_UP 241 -#define WINGDINGS_ARROW_DOWN 242 - -//+------------------------------------------------------------------+ -//| Expert initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - //--- - // You can add any one-time initialization logic here if needed - Print("SpikeDetectorEA initialized. Symbol: ", _Symbol, ", Timeframe: ", EnumToString((ENUM_TIMEFRAMES)Period())); - //--- - return (INIT_SUCCEEDED); -} -//+------------------------------------------------------------------+ -//| Expert deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - //--- - // Optional: Clean up objects when EA is removed or chart is closed - // For more targeted deletion, you might loop through objects and check names - // ObjectsDeleteAll(0, "SpikeArrow_Bearish_" + _Symbol); - // ObjectsDeleteAll(0, "SpikeArrow_Bullish_" + _Symbol); - // A more robust way if you have many EAs or indicators: - long chart_id = ChartID(); - for (int i = ObjectsTotal(chart_id, -1, OBJ_ARROW) - 1; i >= 0; i--) - { - string obj_name = ObjectName(chart_id, i, -1, OBJ_ARROW); - if (StringFind(obj_name, "SpikeArrow_Bearish_" + _Symbol + "_" + EnumToString((ENUM_TIMEFRAMES)Period())) == 0 || - StringFind(obj_name, "SpikeArrow_Bullish_" + _Symbol + "_" + EnumToString((ENUM_TIMEFRAMES)Period())) == 0) - { - ObjectDelete(chart_id, obj_name); - } - } - Print("SpikeDetectorEA deinitialized. Reason: ", reason); -} -//+------------------------------------------------------------------+ -//| Expert tick function (not used for bar analysis in this EA) | -//+------------------------------------------------------------------+ -void OnTick() -{ - //--- - // We will use OnCalculate for bar-based analysis -} -//+------------------------------------------------------------------+ -//| Chart event function (not strictly needed for this EA) | -//+------------------------------------------------------------------+ -void OnChartEvent(const int id, - const long &lparam, - const double &dparam, - const string &sparam) -{ - //--- - // Can be used to handle chart events if necessary -} - -//+------------------------------------------------------------------+ -//| Expert new bar function / Indicator calculation event | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, // Size of the price[] arrays - const int prev_calculated, // Bars calculated at the previous call - const datetime &time[], // Time array - const double &open[], // Open price array - const double &high[], // High price array - const double &low[], // Low price array - const double &close[], // Close price array - const long &tick_volume[], // Tick Volume array - const long &volume[], // Real Volume array - const int &spread[]) // Spread array -{ - //--- Check for minimal rates_total - if (rates_total < 2) // Need at least one closed bar to compare - return (0); - - //--- Determine how many bars to calculate - int first_bar_to_calculate; - // On the very first call of OnCalculate (prev_calculated == 0) or if history was changed drastically - if (prev_calculated == 0 || prev_calculated > rates_total || rates_total - prev_calculated > InpLookbackForDrawing + 10) // Added a buffer for safety - { - first_bar_to_calculate = MathMax(0, rates_total - InpLookbackForDrawing); - Print("SpikeDetectorEA: First run or history refresh. Processing up to ", InpLookbackForDrawing, " bars from bar index ", first_bar_to_calculate); - // Clean up old arrows if doing a full refresh to avoid orphaned objects if bar times change - long chart_id = ChartID(); - for (int k = ObjectsTotal(chart_id, -1, OBJ_ARROW) - 1; k >= 0; k--) - { - string obj_name_check = ObjectName(chart_id, k, -1, OBJ_ARROW); - if (StringFind(obj_name_check, "SpikeArrow_Bearish_" + _Symbol + "_" + EnumToString((ENUM_TIMEFRAMES)Period())) == 0 || - StringFind(obj_name_check, "SpikeArrow_Bullish_" + _Symbol + "_" + EnumToString((ENUM_TIMEFRAMES)Period())) == 0) - { - ObjectDelete(chart_id, obj_name_check); - } - } - } - else - { - // prev_calculated is the number of bars calculated by the previous call. - // We want to start from one bar before the last one calculated by the previous call, - // to catch updates to the forming bar that has now closed, plus any new bars. - // rates_total - prev_calculated gives the number of new bars. - // We process (rates_total - prev_calculated) + 1 bars (the forming bar that closed + new bars) - // So, start from rates_total - (rates_total - prev_calculated + 1) = prev_calculated - 1 - first_bar_to_calculate = prev_calculated - 1; - } - // Ensure we don't go out of bounds (e.g. if prev_calculated was 0 due to error or very few bars) - first_bar_to_calculate = MathMax(0, first_bar_to_calculate); - // We don't want to process the current, still-forming bar (index rates_total - 1 usually) - // So loop up to rates_total - 1 (or < rates_total) - // If we are processing historical bars, i can go up to rates_total - 1 - // If we are processing only new bars, the last bar is rates_total - 1. - - //--- Main loop for processing bars - // We iterate up to rates_total-1 because the last bar (rates_total-1) is the current forming bar - // We are interested in closed bars. So, the last closed bar is at index rates_total-2 if rates_total > 1. - // However, if we start from prev_calculated-1, this logic handles it correctly. - // The loop should go up to `rates_total - 1` to process all available historical bars. - // The current bar (index rates_total - 1) will be processed on the next tick once it closes and a new bar forms. - for (int i = first_bar_to_calculate; i < rates_total; i++) - { - // Skip the current forming bar (bar 0 in terminal, index rates_total-1 in array if processing live) - // This logic is implicitly handled by how OnCalculate is typically called. - // The loop goes from an older bar up to the most recent *available* bar data. - // The last bar in the `time`, `open`, etc. arrays is `rates_total - 1`. - // If `i == rates_total - 1`, it's the current, potentially unclosed bar. - // We generally want to analyze closed bars. Let's adjust the loop to `i < rates_total -1` if we only want confirmed closed bars. - // However, for drawing on historical data, `i < rates_total` is fine. - // The key is that `prev_calculated` helps us only recalculate what's necessary. - // Let's assume we process up to the last available bar, and if it's the current forming bar, - // its spike status might change. The object deletion logic handles this. - - // If it's the very first bar available (index 0) and it has no history to form wicks properly, skip. - // This check might be too simplistic, but helps avoid issues with incomplete data at the start of history. - // if (i == 0 && rates_total < 3) continue; // This might be too restrictive. - - // Define object names for this bar to manage them - // Using time ensures uniqueness per bar. Adding symbol and timeframe for robustness. - string obj_time_str = TimeToString(time[i], TIME_DATE | TIME_MINUTES | TIME_SECONDS); // Added seconds for more uniqueness - string bearish_obj_name = StringFormat("SpikeArrow_Bearish_%s_%s_%s", _Symbol, EnumToString((ENUM_TIMEFRAMES)Period()), obj_time_str); - string bullish_obj_name = StringFormat("SpikeArrow_Bullish_%s_%s_%s", _Symbol, EnumToString((ENUM_TIMEFRAMES)Period()), obj_time_str); - - // Delete existing arrows for this bar before re-evaluating - // This allows settings changes to reflect immediately and removes arrows if a spike no longer qualifies - ObjectDelete(0, bearish_obj_name); - ObjectDelete(0, bullish_obj_name); - - // Get OHLC for the current bar i - double O = open[i]; - double H = high[i]; - double L = low[i]; - double C = close[i]; - - // Calculate candle components - double body_size = MathAbs(O - C); - double total_range = H - L; - double upper_wick = H - MathMax(O, C); - double lower_wick = MathMin(O, C) - L; - - // Avoid division by zero or issues with flat candles (doji, etc.) - if (total_range < _Point * 0.1) // If candle range is very small, skip (e.g. less than 0.1 points) - continue; - - bool is_bearish_spike = false; - bool is_bullish_spike = false; - double body_plus_epsilon = body_size + (_Point * 0.01); // Add a very small value related to point size - - // --- Bearish Spike Detection (Spike High) --- - // 1. Body is a small part of the total range - // 2. Upper wick is significantly larger than the body - // 3. Lower wick is small compared to the body (or upper wick) - if (body_size / total_range <= InpMaxBodyToTotalRangeRatio && - upper_wick / body_plus_epsilon >= InpMinWickToBodyRatio && - lower_wick / body_plus_epsilon <= InpMaxOppositeWickToBodyRatio && - upper_wick > lower_wick) // Ensure upper wick is dominant - { - is_bearish_spike = true; - } - - // --- Bullish Spike Detection (Spike Low) --- - // 1. Body is a small part of the total range - // 2. Lower wick is significantly larger than the body - // 3. Upper wick is small compared to the body (or lower wick) - if (body_size / total_range <= InpMaxBodyToTotalRangeRatio && - lower_wick / body_plus_epsilon >= InpMinWickToBodyRatio && - upper_wick / body_plus_epsilon <= InpMaxOppositeWickToBodyRatio && - lower_wick > upper_wick) // Ensure lower wick is dominant - { - is_bullish_spike = true; - } - - // --- Drawing --- - double arrow_offset_actual = InpArrowOffsetPoints * _Point; - - if (is_bearish_spike) - { - if (ObjectCreate(0, bearish_obj_name, OBJ_ARROW, 0, time[i], H + arrow_offset_actual)) - { - ObjectSetInteger(0, bearish_obj_name, OBJPROP_ARROWCODE, WINGDINGS_ARROW_DOWN); // Corrected - ObjectSetInteger(0, bearish_obj_name, OBJPROP_COLOR, InpBearishSpikeColor); - ObjectSetInteger(0, bearish_obj_name, OBJPROP_WIDTH, 1); - ObjectSetInteger(0, bearish_obj_name, OBJPROP_STYLE, STYLE_SOLID); - ObjectSetString(0, bearish_obj_name, OBJPROP_TOOLTIP, "Bearish Spike"); - } - // else { PrintFormat("Failed to create bearish spike arrow for bar at %s. Error: %d", TimeToString(time[i]), GetLastError()); } - } - - if (is_bullish_spike) - { - if (ObjectCreate(0, bullish_obj_name, OBJ_ARROW, 0, time[i], L - arrow_offset_actual)) - { - ObjectSetInteger(0, bullish_obj_name, OBJPROP_ARROWCODE, WINGDINGS_ARROW_UP); // Corrected - ObjectSetInteger(0, bullish_obj_name, OBJPROP_COLOR, InpBullishSpikeColor); - ObjectSetInteger(0, bullish_obj_name, OBJPROP_WIDTH, 1); - ObjectSetInteger(0, bullish_obj_name, OBJPROP_STYLE, STYLE_SOLID); - ObjectSetString(0, bullish_obj_name, OBJPROP_TOOLTIP, "Bullish Spike"); - } - // else { PrintFormat("Failed to create bullish spike arrow for bar at %s. Error: %d", TimeToString(time[i]), GetLastError()); } - } - } - //--- Return value of prev_calculated for next call - return (rates_total); -} -//+------------------------------------------------------------------+ diff --git a/Documents/BKP/Consolidation_Detector_EA.mq5 b/Documents/BKP/Consolidation_Detector_EA.mq5 deleted file mode 100644 index 6e3d74bd..00000000 --- a/Documents/BKP/Consolidation_Detector_EA.mq5 +++ /dev/null @@ -1,233 +0,0 @@ -//+------------------------------------------------------------------+ -//| Consolidation Detector EA | -//| Detects consolidations using multiple methods | -//+------------------------------------------------------------------+ -#property copyright "Your Name" -#property link "https://www.example.com" -#property version "1.01" - -// Input Parameters -input group "Consolidation Detection Settings" -input bool UsePriceRange = true; // Enable Price Range Analysis -input int PriceRangeBars = 20; // Bars for Price Range -input double PriceRangeThreshold = 0.5; // Price Range Threshold (% of ATR) - -input bool UseBollingerSqueeze = true; // Enable Bollinger Bands Squeeze -input int BollingerPeriod = 20; // Bollinger Bands Period -input double BollingerThreshold = 0.02; // Bollinger Bandwidth Threshold - -input bool UseATRCrossover = true; // Enable ATR Crossover -input int FastATRPeriod = 5; // Fast ATR Period -input int SlowATRPeriod = 20; // Slow ATR Period - -input bool UseVolumeAnalysis = true; // Enable Volume Analysis -input int VolumeBars = 20; // Bars for Volume Analysis -input double VolumeThreshold = 0.7; // Volume Threshold (% of Avg Volume) - -input group "Visualization and Alerts" -input bool DrawZones = true; // Draw Consolidation Zones -input bool EnableAlerts = true; // Enable Alerts for Consolidation -input color ZoneColor = clrPurple; // Color for Consolidation Zones - -// Global Variables -datetime lastBarTime; // Track last processed bar time -int bollingerHandle; // Handle for Bollinger Bands -int fastATRHandle; // Handle for Fast ATR -int slowATRHandle; // Handle for Slow ATR -int priceATRHandle; // Handle for Price Range ATR - -//+------------------------------------------------------------------+ -//| Expert initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - // Initialize Bollinger Bands handle - bollingerHandle = iBands(_Symbol, PERIOD_CURRENT, BollingerPeriod, 0, 2.0, PRICE_CLOSE); - if (bollingerHandle == INVALID_HANDLE) - { - Print("Failed to initialize Bollinger Bands"); - return(INIT_FAILED); - } - - // Initialize ATR handles - priceATRHandle = iATR(_Symbol, PERIOD_CURRENT, PriceRangeBars); - fastATRHandle = iATR(_Symbol, PERIOD_CURRENT, FastATRPeriod); - slowATRHandle = iATR(_Symbol, PERIOD_CURRENT, SlowATRPeriod); - - if (priceATRHandle == INVALID_HANDLE || fastATRHandle == INVALID_HANDLE || slowATRHandle == INVALID_HANDLE) - { - Print("Failed to initialize ATR indicators"); - return(INIT_FAILED); - } - - // Set last bar time to avoid processing same bar multiple times - lastBarTime = TimeCurrent(); - - return(INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| Expert deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - // Release indicator handles - IndicatorRelease(bollingerHandle); - IndicatorRelease(priceATRHandle); - IndicatorRelease(fastATRHandle); - IndicatorRelease(slowATRHandle); - - // Clean up chart objects - ObjectsDeleteAll(0, "Consolidation_"); -} - -//+------------------------------------------------------------------+ -//| Expert tick function | -//+------------------------------------------------------------------+ -void OnTick() -{ - // Process only on new bar - datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0); - if (currentBarTime == lastBarTime) - return; - lastBarTime = currentBarTime; - - bool isConsolidation = false; - string consolidationMethods = ""; - - // Get high and low for visualization - double high = iHigh(_Symbol, PERIOD_CURRENT, 1); - double low = iLow(_Symbol, PERIOD_CURRENT, 1); - datetime startTime = iTime(_Symbol, PERIOD_CURRENT, PriceRangeBars); - datetime endTime = currentBarTime; - - // Check Price Range Consolidation - // if (UsePriceRange && IsPriceRangeConsolidation(PriceRangeBars, PriceRangeThreshold)) - // { - // isConsolidation = true; - // consolidationMethods += "Price Range, "; - // } - - // // Check Bollinger Bands Squeeze - // if (UseBollingerSqueeze && IsBollingerSqueeze(BollingerPeriod, BollingerThreshold)) - // { - // isConsolidation = true; - // consolidationMethods += "Bollinger Squeeze, "; - // } - - // // Check ATR Crossover - // if (UseATRCrossover && IsATRConsolidation(FastATRPeriod, SlowATRPeriod)) - // { - // isConsolidation = true; - // consolidationMethods += "ATR Crossover, "; - // } - - // // Check Volume Analysis - // if (UseVolumeAnalysis && IsVolumeConsolidation(VolumeBars, VolumeThreshold)) - // { - // isConsolidation = true; - // consolidationMethods += "Volume Analysis, "; - // } - - // Output and Visualization - if (isConsolidation) - { - string message = "Consolidation detected by: " + consolidationMethods; - Print(message); - if (EnableAlerts) - Alert(message); - if (DrawZones) - DrawConsolidationZone(high, low, startTime, endTime); - } - else - { - Print("No consolidation detected"); - } -} - -//+------------------------------------------------------------------+ -//| Price Range Consolidation Detection | -//+------------------------------------------------------------------+ -bool IsPriceRangeConsolidation(int bars, double threshold) -{ - double rangeSum = 0.0; - double high[], low[], atr[]; - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(atr, true); - - CopyHigh(_Symbol, PERIOD_CURRENT, 1, bars, high); - CopyLow(_Symbol, PERIOD_CURRENT, 1, bars, low); - CopyBuffer(priceATRHandle, 0, 1, 1, atr); // Get ATR for shift 1 - - for (int i = 0; i < bars; i++) - rangeSum += high[i] - low[i]; - - double avgRange = rangeSum / bars; - - return (avgRange < threshold * atr[0]); -} - -//+------------------------------------------------------------------+ -//| Bollinger Bands Squeeze Detection | -//+------------------------------------------------------------------+ -bool IsBollingerSqueeze(int period, double threshold) -{ - double upper[], lower[], middle[]; - ArraySetAsSeries(upper, true); - ArraySetAsSeries(lower, true); - ArraySetAsSeries(middle, true); - - CopyBuffer(bollingerHandle, 0, 0, 3, middle); // Middle band - CopyBuffer(bollingerHandle, 1, 0, 3, upper); // Upper band - CopyBuffer(bollingerHandle, 2, 0, 3, lower); // Lower band - - double bandwidth = (upper[1] - lower[1]) / middle[1]; - return (bandwidth < threshold); -} - -//+------------------------------------------------------------------+ -//| ATR Crossover Consolidation Detection | -//+------------------------------------------------------------------+ -bool IsATRConsolidation(int fastPeriod, int slowPeriod) -{ - double fastATR[], slowATR[]; - ArraySetAsSeries(fastATR, true); - ArraySetAsSeries(slowATR, true); - - CopyBuffer(fastATRHandle, 0, 1, 1, fastATR); // Fast ATR for shift 1 - CopyBuffer(slowATRHandle, 0, 1, 1, slowATR); // Slow ATR for shift 1 - - return (fastATR[0] < slowATR[0]); -} - -//+------------------------------------------------------------------+ -//| Volume Analysis Consolidation Detection | -//+------------------------------------------------------------------+ -bool IsVolumeConsolidation(int bars, double threshold) -{ - double volume[]; - ArraySetAsSeries(volume, true); - CopyBuffer(iVolume(_Symbol, PERIOD_CURRENT, 0), 0, 0, bars, volume); - - double avgVolume = 0.0; - for (int i = 0; i < bars; i++) - avgVolume += volume[i]; - avgVolume /= bars; - - double currentVolume = volume[1]; - return (currentVolume < threshold * avgVolume); -} - -//+------------------------------------------------------------------+ -//| Draw Consolidation Zone on Chart | -//+------------------------------------------------------------------+ -void DrawConsolidationZone(double high, double low, datetime start, datetime end) -{ - string objName = "Consolidation_" + TimeToString(start); - ObjectCreate(0, objName, OBJ_RECTANGLE, 0, start, high, end, low); - ObjectSetInteger(0, objName, OBJPROP_COLOR, ZoneColor); - ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_SOLID); - ObjectSetInteger(0, objName, OBJPROP_FILL, true); - ObjectSetInteger(0, objName, OBJPROP_BACK, true); -} diff --git a/Documents/BKP/Indicators/x-saherelm.x121.xczone.2.mq5 b/Documents/BKP/Indicators/x-saherelm.x121.xczone.2.mq5 deleted file mode 100644 index 6489beb2..00000000 --- a/Documents/BKP/Indicators/x-saherelm.x121.xczone.2.mq5 +++ /dev/null @@ -1,2288 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: X121 XCZone V2 -// Description: XCZone V2 ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121 XCZone V2 Indicator" -#property strict - -// -// Definitions ... -// -#define ShortName "X121 XCZone" - -// -// Includes Common Library ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Inputs ... -input group "Market"; -input ENUM_X_PERIOD_METHOD trendPeriodMethod = X_PERIOD_AUTO; // How to Find Trend Period -input ENUM_TIMEFRAMES trendPeriod = NULL; // Trend Time Period -input ENUM_MA_METHOD trendMode = MODE_SMA; // Trend Mode -input ENUM_APPLIED_PRICE trendAppliedTo = PRICE_CLOSE; // Trend Applied To -input double sarStep = 0.02; // Sar Step -input double sarMax = 0.2; // Sar Maximum -input int adxLength = 14; // ADX Length -input double adxThreshold = 25.0; // ADX Threshold -input int rsiLength = 14; // RSI Length -input double rsiOBLevel = 70.0; // RSI OB Level -input double rsiOSLevel = 30.0; // RSI OS Level -input ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // RSI Applied To - -// -// Validating ... -input group "Validating"; -input int minZoneLength = 7; // Minimum Length of Consolidation Zone -input double maxZoneRangeInPoints = 70; // Max Zone Range in Point -input double maxAllowedEntryDistance = 30; // Max Allowed Entry Distance -input bool forceGapBarsBreakout = true; // Force Zone's Gap Bar's Breakes Out -input bool forceHasSwing = true; // Force Zone's Has Propper Swing -input bool forceHasPinBarEntry = true; // Force Zone's Ends with a Pin Bar - -// -// Filtering ... -input group "Filtering"; -input bool filterBasedOnSar = false; // Filter Pivots Based on Sar -input bool filterBasedOnRSI = false; // Filter Pivots Based on RSI -input bool filterBasedOnADX = false; // Filter Pivots Based on ADX -input bool filterBasedOnTrend = false; // Filter Pivots Based on Trend - -// -// Presentation ... -input group "Presentation"; -input bool showSar = false; // Show Sar -input bool showTrend = false; // Show Trend -input bool rayLeft = false; // Ray to Left -input bool drawZones = true; // Draw Detected Zones -input bool drawRRofZones = true; // Draw Zone's Risk Reward Ratios -input int boxWidth = 2; // Box Width -input color bullishColor = clrLime; // Bullish Color -input color bearishColor = clrRed; // Bearish Color -input ENUM_LINE_STYLE boxStyle = STYLE_SOLID; // Box Style - -// -input int startCalculationForLastBars = 5000; // Calculate Last n Bars -int sarArrowCode = 159; // Sar Arrow Code -int rrZoneLength = 7; // Draw Risk Reward Ratio till n Bars - -// -// Alert ... -input group "Alerts"; -input string alertPrefix = ""; // Alert Prefix -input bool _logAlerts = true; // Log Alerts -input bool _pushAlerts = true; // Push Alerts -input bool _mailAlerts = false; // Mail Alerts -input bool _terminalAlerts = true; // Terminal Alerts - -// -// Buffers ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -#property indicator_chart_window - -// -#property indicator_buffers 10 -#property indicator_plots 2 - -// -// Plot Buffers ... - -// -// TREND ... - -// -#define trendBufferIndex 0 -#define trendBufferPlotIndex 0 -double trendBuffer[]; - -// -#define trendColorBufferIndex 1 -double trendColorBuffer[]; - -// -#property indicator_label1 "X121 Trend" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_style1 STYLE_DASH -#property indicator_width1 2 - -// -// SAR ... - -// -#define sarBufferIndex 2 -#define sarBufferPlotIndex 2 -double sarBuffer[]; - -// -#define sarColorBufferIndex 3 -double sarColorBuffer[]; - -// -#property indicator_label2 "X121 SAR" -#property indicator_type2 DRAW_COLOR_ARROW -#property indicator_color2 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_width2 2 - -// -// Data Buffers ... - -#define mLastBufferIndex 3 - -// -#define trendStateBufferIndex mLastBufferIndex + 1 -double trendStateBuffer[]; - -// -#define sarStateBufferIndex mLastBufferIndex + 2 -double sarStateBuffer[]; - -// -#define rsiBufferIndex mLastBufferIndex + 3 -double rsiBuffer[]; - -// -#define adxBufferIndex mLastBufferIndex + 4 -double adxBuffer[]; - -// -#define adxpBufferIndex mLastBufferIndex + 5 -double adxpBuffer[]; - -// -#define adxnBufferIndex mLastBufferIndex + 6 -double adxnBuffer[]; - -// -// Variables, Properties and etc ... - -// -int limit; - -// -int maxLength; - -// -XCAlert *alert; -double mPoints = 0; -CArrayObj mObjects; -XCPOIDrawer *drawer; -bool mEnableAlerts = false; -XCBarAnalyser *barAnalyser; -int mTrendPeriodLength = 0; -int sarHandler = INVALID_HANDLE; -int rsiHandler = INVALID_HANDLE; -int adxHandler = INVALID_HANDLE; -int trendHandler = INVALID_HANDLE; -ENUM_TIMEFRAMES mTrendPeriod = NULL; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Indicator Handlers ... - - // - // Configure Alert ... - alert = new XCAlert(); - mEnableAlerts = - _logAlerts || - _pushAlerts || - _mailAlerts || - _terminalAlerts; - string mPrefix = ShortName + - (!IsValid(alertPrefix) - ? "" - : "[" + alertPrefix + "]"); - alert.SetPrefix(mPrefix); - alert.SetLogAlerts(_logAlerts); - alert.SetMailAlerts(_mailAlerts); - alert.SetPushAlerts(_pushAlerts); - alert.SetEnableAlerts(mEnableAlerts); - alert.SetTerminalAlerts(_terminalAlerts); - - // - drawer = new XCPOIDrawer(); - barAnalyser = new XCBarAnalyser(); - - // - // Initializing TrendPeriod ... - int cPeriodSeconds = PeriodSeconds(_Period); - if (trendPeriodMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mTrendPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mTrendPeriod = trendPeriod; - } - if (IsValid(mTrendPeriod)) - { - mTrendPeriodLength = PeriodSeconds(mTrendPeriod) / cPeriodSeconds; - } - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - bool isInited = sarHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // RSI ... - rsiHandler = iRSI( - _Symbol, - _Period, - rsiLength, - rsiAppliedTo // - ); - isInited = rsiHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // ADX ... - adxHandler = iADX( - _Symbol, - _Period, - adxLength // - ); - isInited = adxHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // TREND ... - trendHandler = iMA( - _Symbol, - _Period, - mTrendPeriodLength, - 0, - trendMode, - trendAppliedTo // - ); - isInited = trendHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - mPoints = GetPoints(_Symbol); - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - mObjects.Clear(); - - // - delete alert; - delete drawer; - - // - ZeroMemory(alert); - ZeroMemory(drawer); - ZeroMemory(barAnalyser); - - // - IndicatorRelease(sarHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(trendHandler); -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // Validate Calculated Bars ... - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - // RSI ... - int rsiCalculatedBars = BarsCalculated(rsiHandler); - - // - // ADX ... - int adxCalculatedBars = BarsCalculated(adxHandler); - - // - // TREND ... - int trendCalculatedBars = BarsCalculated(trendHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // SAR ... - sarCalculatedBars >= maxLength && - // - // RSI ... - rsiCalculatedBars >= maxLength && - // - // ADX ... - adxCalculatedBars >= maxLength && - // - // TREND ... - trendCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // SAR ... - int copiedSars = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // RSI ... - int copiedRSIs = CopyBuffer(rsiHandler, MAIN_LINE, 0, limit, rsiBuffer); - - // - // ADX ... - int copiedADXs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); - - // - // ADX Plus ... - int copiedADXPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxpBuffer); - - // - // ADX Negative ... - int copiedADXNs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxnBuffer); - - // - // TREND ... - int copiedTrends = CopyBuffer(trendHandler, MAIN_LINE, 0, limit, trendBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // SAR ... - copiedSars >= limit && - // - // RSI ... - copiedRSIs >= limit && - // - // TREND ... - copiedTrends >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Functions ... - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - sarMax > 0 && - sarStep > 0 && - adxLength > 0 && - rsiLength > 0 && - rsiOBLevel > 0 && - rsiOSLevel > 0 && - sarMax > sarStep && - minZoneLength > 2 && - IsValid(trendPeriodMethod, trendPeriod) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(minZoneLength, rsiLength); - result = MathMax(result, adxLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // TREND ... - - // - ArraySetAsSeries(trendBuffer, true); - SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrend); - - // - PlotIndexSetDouble(trendBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(trendColorBuffer, true); - SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSar); - - // - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Data Buffers ... - - // - ArraySetAsSeries(trendStateBuffer, true); - SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(rsiBuffer, true); - SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxBuffer, true); - SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxpBuffer, true); - SetIndexBuffer(adxpBufferIndex, adxpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxnBuffer, true); - SetIndexBuffer(adxnBufferIndex, adxnBuffer, INDICATOR_CALCULATIONS); -} - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Calculate Custom Buffers ... - * - * @param bar_index: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - // - // bool canCalculate = true; - bool canCalculate = - barsLimit == 0 || - bar_index <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - bar_index, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(bar_index); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - // SAR ... - // sarBuffer[barIndex] = emptyValue; - // sarColorBuffer[barIndex] = hideColorIDX; - // sarStateBuffer[barIndex] = neuturalState; - - // - // TREND ... - // trendBuffer[barIndex] = emptyValue; - // trendColorBuffer[barIndex] = hideColorIDX; - // trendStateBuffer[barIndex] = neuturalState; -} - -/** - * Calculate Values ... - * - * @param bar_index: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Prev Bar ... - - // - int lastBarIndex = bar_index + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - bar_index == maxBarIndex; - - // - double iLow = high[bar_index]; - double iHigh = high[bar_index]; - double iClose = close[bar_index]; - - // - double points = GetPoints(_Symbol); - - // - // Calculate Sar Color Buffer ... - double iSar = sarBuffer[bar_index]; - - // - double iSarState = neuturalState; - double iSarColor = neuturalColorIDX; - if (iLow > iSar) - { - // - iSarState = bullishState; - iSarColor = !showSar - ? hideColorIDX - : bullishColorIDX; - } - else if (iHigh < iSar) - { - // - iSarState = bearishState; - iSarColor = !showSar - ? hideColorIDX - : bearishColorIDX; - } - sarStateBuffer[bar_index] = iSarState; - sarColorBuffer[bar_index] = iSarColor; - - // - // Calculate Trend Color Buffer ... - double iTrend = trendBuffer[bar_index]; - - // - double iTrendState = neuturalState; - double iTrendColor = neuturalColorIDX; - if (iClose > iTrend) - { - // - iTrendState = bullishState; - iTrendColor = !showTrend - ? hideColorIDX - : bullishColorIDX; - } - else if (iClose < iTrend) - { - // - iTrendState = bearishState; - iTrendColor = !showTrend - ? hideColorIDX - : bearishColorIDX; - } - trendStateBuffer[bar_index] = iTrendState; - trendColorBuffer[bar_index] = iTrendColor; - - // - DetectTriggerZone( - bar_index, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); -} - -// -void DetectTriggerZone( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Prev Bar ... - - // - int lastBarIndex = bar_index + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - bar_index == maxBarIndex; - - // - // Prevent Calculation ... - if (maxBarIndex - bar_index < minZoneLength) - { - return; - } - - // - int zIDX = 0; - int cIDX = 0; - int pIDX = 0; - int p2IDX = 0; - int p3IDX = 0; - int p4IDX = 0; - double ll = 0; - double hh = 0; - bool has = false; - ENUM_X_DIRECTION iDir; - - // - // Retrieve Required Bars ... - - // - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - XOHCL cBar; // Current Finished Bar which Start Detecting Structures based on it ( End of Block and FVG Bar ) ... - XOHCL pBar; // Determines Block Gap Bar (all Filtering must applied and Check using this Bar and it's Next Bar) ... - XOHCL p2Bar; // Determines FVG's Start Bar in a Block ... - XOHCL p3Bar; // First Verification of Block ... - XOHCL p4Bar; // Seccond Verification of Block ... - - // - has = zBar.Init( - _Symbol, - _Period, - bar_index // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - has = - has && - p2Bar.GetPreviousBar(p3Bar); - has = - has && - p3Bar.GetPreviousBar(p4Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Define Zone Structure ... - XBoxZone zone; - - // - // Detect Based Order Block using CBar ... - has = barAnalyser.IsOB( - cBar, - zone, - true, // Force FVG Bar Type ... - true // Force Block Two Bar Checking ... - ); - - // - // Ensure a Block is Detected ... - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - zIDX = zBar.Index(); - cIDX = cBar.Index(); - pIDX = pBar.Index(); - p2IDX = p2Bar.Index(); - p3IDX = p3Bar.Index(); - p4IDX = p4Bar.Index(); - - // - bool isBullish = - has && - zone.IsBullish(); - - // - bool isBearish = - has && - zone.IsBearish(); - - // - int toIDX = zone.ToIndex(); - int fromIDX = zone.FromIndex(); - - // - // Validating p2Bar and p3Bar Direction ... - if (has) - { - // - iDir = Opposit(zone.dir); - - // - has = - iDir == p3Bar.GetDirection() || - iDir == p4Bar.GetDirection(); - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Start Validating Block based on - // Detected One ... - - // - // Validating Using Max Range ... - has = maxZoneRangeInPoints > 0; - if (has) - { - // - double range = zone.GetRange(); - has = range <= maxZoneRangeInPoints * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Gap Endup with PinBar ... - has = forceHasPinBarEntry; - if (has) - { - // - bool isBullishRejected = - isBullish && - cBar.IsBullish() && - cBar.GetLowShadow() > cBar.GetHighShadow(); - - // - bool isBearishRejected = - isBearish && - cBar.IsBearish() && - cBar.GetLowShadow() < cBar.GetHighShadow(); - - // - has = isBullishRejected || - isBearishRejected; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Gap Bar must a Momentum Bar and - // Breakes out Zone's Directional Edge ... - // for Bullish: Upper - // for Bearish: Lower - has = forceGapBarsBreakout; - if (has) - { - // - // Gap Bar is PBar ... - - // - // Check Gap Bar is Momentum Bar ... - has = barAnalyser.IsMomentum( - pBar, - iDir // - ); - bool isBullishMomentum = - has && - IsBullish(iDir); - bool isBearishMomentum = - has && - IsBearish(iDir); - - // - // Check Gap Bar's Breakout ... - - // - bool isBullishBreakedout = - isBullish && - pBar.IsBullish() && - isBullishMomentum && - pBar.GetUp() > zone.upper && - pBar.GetDown() < zone.upper; - - // - bool isBearishBreakedout = - isBearish && - pBar.IsBearish() && - isBearishMomentum && - pBar.GetUp() > zone.lower && - pBar.GetDown() < zone.lower; - - // - has = isBullishBreakedout || - isBearishBreakedout; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Zone Has Propper Swing ... - // for Bullish: p2Bar or p3Bar must be a Swing Low ... - // for Bearish: p2Bar or p3Bar must be a Swing High ... - has = forceHasSwing; - if (has) - { - // - // p2Bar ... - bool isP2BarSwing = - barAnalyser - .IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarSwingLow = - isP2BarSwing && - IsBullish(iDir); - bool isP2BarSwingHigh = - isP2BarSwing && - IsBearish(iDir); - - // - // p3Bar ... - bool isP3BarSwing = - barAnalyser - .IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarSwingLow = - isP3BarSwing && - IsBullish(iDir); - bool isP3BarSwingHigh = - isP3BarSwing && - IsBearish(iDir); - - // - bool hasSwingLow = - isBullish && - (isP2BarSwingLow || - isP3BarSwingLow); - - // - bool hasSwingHigh = - isBearish && - (isP2BarSwingHigh || - isP3BarSwingHigh); - - // - has = - hasSwingLow || - hasSwingHigh; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Using Swing Length ... - has = minZoneLength > 0; - if (has) - { - // - XOHCL fromBar; - has = zone.FromBar(fromBar); - if (has) - { - // - // Retrieve HH and LL ... - ll = fromBar.FindLowest(minZoneLength, MODE_LOW); - hh = fromBar.FindHighest(minZoneLength, MODE_HIGH); - - // - // Validate Using HH and LL ... - - // - bool isBullishValid = - isBullish && - ll >= zone.lower; - - // - bool isBearishValid = - isBearish && - hh <= zone.upper; - - // - has = isBullishValid || - isBearishValid; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Update Zone's From Time ... - zone.from = GetBarTime( - zone.symbol, - zone.period, - fromBar.Index() + minZoneLength // - ); - } - - // - fromBar.Clean(); - } - - // - // Validate Max Allowed Entry Distance ... - has = maxAllowedEntryDistance > 0; - if (has) - { - // - double base = - isBullish - ? zone.upper - : zone.lower; - double entryDistance = MathAbs(zBar.open - base); - has = entryDistance <= maxAllowedEntryDistance * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Here we Ensure which have a Valid Zone using Different Applied Validations ... - // from now we are Going to Filtered Validate Zones ... - - // - // Check Exists Filters or not ... - has = filterBasedOnSar || - filterBasedOnRSI || - filterBasedOnADX || - filterBasedOnTrend; - if (has) - { - // - // Do Apply Several Exists Filters ... - - // - // SAR Filter ... - if (filterBasedOnSar) - { - // - // Reading Conditions Values ... - - // - double zSar = sarBuffer[zIDX]; - double cSar = sarBuffer[cIDX]; - double pSar = sarBuffer[pIDX]; - double p2Sar = sarBuffer[p2IDX]; - double p3Sar = sarBuffer[p3IDX]; - double p4Sar = sarBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFiltered = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // RSI Filter ... - if (filterBasedOnRSI) - { - // - // Reading Conditions Values ... - - // - double rsiTrend = (rsiOBLevel + rsiOSLevel) / 2; - - // - double zRSI = rsiBuffer[zIDX]; - double cRSI = rsiBuffer[cIDX]; - double pRSI = rsiBuffer[pIDX]; - double p2RSI = rsiBuffer[p2IDX]; - double p3RSI = rsiBuffer[p3IDX]; - double p4RSI = rsiBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI <= rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI >= rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI > rsiOSLevel && - p2RSI <= rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI < rsiOBLevel && - p2RSI >= rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // ADX Filter ... - if (filterBasedOnADX) - { - // - // Reading Conditions Values ... - - // - // ADX ... - double zADX = adxBuffer[zIDX]; - double cADX = adxBuffer[cIDX]; - double pADX = adxBuffer[pIDX]; - double p2ADX = adxBuffer[p2IDX]; - double p3ADX = adxBuffer[p3IDX]; - double p4ADX = adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = adxpBuffer[zIDX]; - double cADXP = adxpBuffer[cIDX]; - double pADXP = adxpBuffer[pIDX]; - double p2ADXP = adxpBuffer[p2IDX]; - double p3ADXP = adxpBuffer[p3IDX]; - double p4ADXP = adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = adxnBuffer[zIDX]; - double cADXN = adxnBuffer[cIDX]; - double pADXN = adxnBuffer[pIDX]; - double p2ADXN = adxnBuffer[p2IDX]; - double p3ADXN = adxnBuffer[p3IDX]; - double p4ADXN = adxnBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > adxThreshold; - bool isZADXBearish = zADX < adxThreshold; - - // - bool isCADXBullish = cADX > adxThreshold; - bool isCADXBearish = cADX < adxThreshold; - - // - bool isPADXBullish = pADX > adxThreshold; - bool isPADXBearish = pADX < adxThreshold; - - // - bool isP2ADXBullish = p2ADX > adxThreshold; - bool isP2ADXBearish = p2ADX < adxThreshold; - - // - bool isP3ADXBullish = p3ADX > adxThreshold; - bool isP3ADXBearish = p3ADX < adxThreshold; - - // - bool isP4ADXBullish = p4ADX > adxThreshold; - bool isP4ADXBearish = p4ADX < adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // TREND Filter ... - if (filterBasedOnTrend) - { - // - // Reading Conditions Values ... - - // - double zTrend = trendBuffer[zIDX]; - double cTrend = trendBuffer[cIDX]; - double pTrend = trendBuffer[pIDX]; - double p2Trend = trendBuffer[p2IDX]; - double p3Trend = trendBuffer[p3IDX]; - double p4Trend = trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = trendStateBuffer[zIDX]; - double cTrendState = trendStateBuffer[cIDX]; - double pTrendState = trendStateBuffer[pIDX]; - double p2TrendState = trendStateBuffer[p2IDX]; - double p3TrendState = trendStateBuffer[p3IDX]; - double p4TrendState = trendStateBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // SCORE Filter ... - - // - // VOLUME Filter ... - } - - // - // Detect Left Side of Box ... - XOHCL zoneLeftBar; - int idx = fromIDX + 1; - bool isBaseValid = true; - while (isBaseValid) - { - // - // Retrieve iteration Bar ... - has = zoneLeftBar.Init( - _Symbol, - _Period, - idx // - ); - if (!has) - { - // - zoneLeftBar.Clean(); - break; - } - - // - // Check Bar's Validation ... - - // - bool isBullishPassed = - isBullish && - zoneLeftBar.low >= zone.lower; - - // - bool isBearishPassed = - isBearish && - zoneLeftBar.high <= zone.upper; - - // - // Summarize Conditions ... - has = - isBullishPassed || - isBearishPassed; - if (!has) - { - break; - } - - // - idx++; - } - - // - // Ray to Left Side Zone, if Provided ... - if (rayLeft) - { - // - // Update Value ... - fromIDX = zone.FromIndex(); - - // - // Check Last Iteration Bar is Valid Bar ... - // then Update Zone from Time ... - has = zoneLeftBar.IsValid(); - if (has) - { - // - zone.from = zoneLeftBar.time; - fromIDX = zone.FromIndex(); - } - } - - // - // Draw Detected Zone ... - if (drawZones) - { - // - XCBoxObject *iZoneObj; - has = drawer.DrawBox( - zone, - iZoneObj // - ); - if (has) - { - // - ApplyStyle(iZoneObj, zone.dir); - - // - mObjects.Add(iZoneObj); - - // - // TODO: Enable This for Debugging ... - // string message = ToString(zone.dir) + " Zone Detected (" + cBar.time + ") ..."; - // Print(message); - } - ZeroMemory(iZoneObj); - } - - // - // Draw RR Tool ... - if (drawRRofZones) - { - // - double rr[]{ - 1, - 1.5, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10 // - }; - XCRRObject *iRRObj; - iRRObj = new XCRRObject(); - has = iRRObj.CreateBoxRR( - drawer.ChartIdentification(), - drawer.SubWindowIdentification(), - zone, - rr, - rrZoneLength // - ); - if (has) - { - // - int iWidth = 2; - ENUM_LINE_STYLE iStyle = STYLE_SOLID; - - // - iRRObj.TPWidth(iWidth); - iRRObj.SLWidth(iWidth); - iRRObj.EntryWidth(iWidth); - iRRObj.TargetWidth(iWidth); - - // - iRRObj.TPStyle(iStyle); - iRRObj.SLStyle(iStyle); - iRRObj.EntryStyle(iStyle); - iRRObj.TargetStyle(iStyle); - - // - iRRObj.TPColor(clrLime); - iRRObj.SLColor(clrRed); - iRRObj.EntryColor(clrYellow); - iRRObj.TargetColor(clrLightBlue); - - // - mObjects.Add(iRRObj); - } - ZeroMemory(iRRObj); - } - - // - // Handle Alerst ... - bool canAlert = - mEnableAlerts && - prevCalculated > 0; - bool canLogOnly = - mEnableAlerts && - prevCalculated == 0; - if (canAlert || canLogOnly) - { - // - string message = - zone.symbol + "," + - ToString(zone.period) + "> " + - ToString(zone.dir) + - " Zone Detected at: " + ToString(zone.to); - - // - if (canLogOnly) - { - alert.LogAlert(message); - } - else if (canAlert) - { - alert.SendAlert(message); - } - } - - // - // Cleanup Resources ... - - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - zoneLeftBar.Clean(); -} - -// -void ApplyStyle( - XCBoxObject *iObj, - ENUM_X_DIRECTION dir // -) -{ - // - if (!HasDirection(dir) || iObj == NULL) - { - return; - } - - // - int width = boxWidth > 0 - ? boxWidth - : 1; - int clr = IsBullish(dir) - ? bullishColor - : bearishColor; - - // - iObj.BoxColor(clr); - iObj.BoxWidth(width); - iObj.BoxStyle(boxStyle); - - // -} - -// \ No newline at end of file diff --git a/Documents/BKP/Indicators/x-saherelm.x121.xczone.mq5 b/Documents/BKP/Indicators/x-saherelm.x121.xczone.mq5 deleted file mode 100644 index 5c21c5a5..00000000 --- a/Documents/BKP/Indicators/x-saherelm.x121.xczone.mq5 +++ /dev/null @@ -1,2288 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: X121 X3MA -// Description: X3MA ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121 XCZone Indicator" -#property strict - -// -// Definitions ... -// -#define ShortName "X121 XCZone" - -// -// Includes Common Library ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Inputs ... -input group "Market"; -input ENUM_X_PERIOD_METHOD trendPeriodMethod = X_PERIOD_AUTO; // How to Find Trend Period -input ENUM_TIMEFRAMES trendPeriod = NULL; // Trend Time Period -input ENUM_MA_METHOD trendMode = MODE_SMA; // Trend Mode -input ENUM_APPLIED_PRICE trendAppliedTo = PRICE_CLOSE; // Trend Applied To -input double sarStep = 0.02; // Sar Step -input double sarMax = 0.2; // Sar Maximum -input int adxLength = 14; // ADX Length -input double adxThreshold = 25.0; // ADX Threshold -input int rsiLength = 14; // RSI Length -input double rsiOBLevel = 70.0; // RSI OB Level -input double rsiOSLevel = 30.0; // RSI OS Level -input ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // RSI Applied To - -// -// Validating ... -input group "Validating"; -input int minZoneLength = 7; // Minimum Length of Consolidation Zone -input double maxZoneRangeInPoints = 70; // Max Zone Range in Point -input double maxAllowedEntryDistance = 30; // Max Allowed Entry Distance -input bool forceGapBarsBreakout = true; // Force Zone's Gap Bar's Breakes Out -input bool forceHasSwing = true; // Force Zone's Has Propper Swing -input bool forceHasPinBarEntry = true; // Force Zone's Ends with a Pin Bar - -// -// Filtering ... -input group "Filtering"; -input bool filterBasedOnSar = false; // Filter Pivots Based on Sar -input bool filterBasedOnRSI = false; // Filter Pivots Based on RSI -input bool filterBasedOnADX = false; // Filter Pivots Based on ADX -input bool filterBasedOnTrend = false; // Filter Pivots Based on Trend - -// -// Presentation ... -input group "Presentation"; -input bool showSar = false; // Show Sar -input bool showTrend = false; // Show Trend -input bool rayLeft = false; // Ray to Left -input bool drawZones = true; // Draw Detected Zones -input bool drawRRofZones = true; // Draw Zone's Risk Reward Ratios -input int boxWidth = 2; // Box Width -input color bullishColor = clrLime; // Bullish Color -input color bearishColor = clrRed; // Bearish Color -input ENUM_LINE_STYLE boxStyle = STYLE_SOLID; // Box Style - -// -input int startCalculationForLastBars = 5000; // Calculate Last n Bars -int sarArrowCode = 159; // Sar Arrow Code -int rrZoneLength = 7; // Draw Risk Reward Ratio till n Bars - -// -// Alert ... -input group "Alerts"; -input string alertPrefix = ""; // Alert Prefix -input bool _logAlerts = true; // Log Alerts -input bool _pushAlerts = true; // Push Alerts -input bool _mailAlerts = false; // Mail Alerts -input bool _terminalAlerts = true; // Terminal Alerts - -// -// Buffers ... - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -#property indicator_chart_window - -// -#property indicator_buffers 10 -#property indicator_plots 2 - -// -// Plot Buffers ... - -// -// TREND ... - -// -#define trendBufferIndex 0 -#define trendBufferPlotIndex 0 -double trendBuffer[]; - -// -#define trendColorBufferIndex 1 -double trendColorBuffer[]; - -// -#property indicator_label1 "X121 Trend" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_style1 STYLE_DASH -#property indicator_width1 2 - -// -// SAR ... - -// -#define sarBufferIndex 2 -#define sarBufferPlotIndex 2 -double sarBuffer[]; - -// -#define sarColorBufferIndex 3 -double sarColorBuffer[]; - -// -#property indicator_label2 "X121 SAR" -#property indicator_type2 DRAW_COLOR_ARROW -#property indicator_color2 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_width2 2 - -// -// Data Buffers ... - -#define mLastBufferIndex 3 - -// -#define trendStateBufferIndex mLastBufferIndex + 1 -double trendStateBuffer[]; - -// -#define sarStateBufferIndex mLastBufferIndex + 2 -double sarStateBuffer[]; - -// -#define rsiBufferIndex mLastBufferIndex + 3 -double rsiBuffer[]; - -// -#define adxBufferIndex mLastBufferIndex + 4 -double adxBuffer[]; - -// -#define adxpBufferIndex mLastBufferIndex + 5 -double adxpBuffer[]; - -// -#define adxnBufferIndex mLastBufferIndex + 6 -double adxnBuffer[]; - -// -// Variables, Properties and etc ... - -// -int limit; - -// -int maxLength; - -// -XCAlert *alert; -double mPoints = 0; -CArrayObj mObjects; -XCPOIDrawer *drawer; -bool mEnableAlerts = false; -XCBarAnalyser *barAnalyser; -int mTrendPeriodLength = 0; -int sarHandler = INVALID_HANDLE; -int rsiHandler = INVALID_HANDLE; -int adxHandler = INVALID_HANDLE; -int trendHandler = INVALID_HANDLE; -ENUM_TIMEFRAMES mTrendPeriod = NULL; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Indicator Handlers ... - - // - // Configure Alert ... - alert = new XCAlert(); - mEnableAlerts = - _logAlerts || - _pushAlerts || - _mailAlerts || - _terminalAlerts; - string mPrefix = ShortName + - (!IsValid(alertPrefix) - ? "" - : "[" + alertPrefix + "]"); - alert.SetPrefix(mPrefix); - alert.SetLogAlerts(_logAlerts); - alert.SetMailAlerts(_mailAlerts); - alert.SetPushAlerts(_pushAlerts); - alert.SetEnableAlerts(mEnableAlerts); - alert.SetTerminalAlerts(_terminalAlerts); - - // - drawer = new XCPOIDrawer(); - barAnalyser = new XCBarAnalyser(); - - // - // Initializing TrendPeriod ... - int cPeriodSeconds = PeriodSeconds(_Period); - if (trendPeriodMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mTrendPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mTrendPeriod = trendPeriod; - } - if (IsValid(mTrendPeriod)) - { - mTrendPeriodLength = PeriodSeconds(mTrendPeriod) / cPeriodSeconds; - } - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - bool isInited = sarHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // RSI ... - rsiHandler = iRSI( - _Symbol, - _Period, - rsiLength, - rsiAppliedTo // - ); - isInited = rsiHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // ADX ... - adxHandler = iADX( - _Symbol, - _Period, - adxLength // - ); - isInited = adxHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - // TREND ... - trendHandler = iMA( - _Symbol, - _Period, - mTrendPeriodLength, - 0, - trendMode, - trendAppliedTo // - ); - isInited = trendHandler != INVALID_HANDLE; - if (!isInited) - { - return INIT_FAILED; - } - - // - mPoints = GetPoints(_Symbol); - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - mObjects.Clear(); - - // - delete alert; - delete drawer; - - // - ZeroMemory(alert); - ZeroMemory(drawer); - ZeroMemory(barAnalyser); - - // - IndicatorRelease(sarHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(trendHandler); -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // Validate Calculated Bars ... - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - // RSI ... - int rsiCalculatedBars = BarsCalculated(rsiHandler); - - // - // ADX ... - int adxCalculatedBars = BarsCalculated(adxHandler); - - // - // TREND ... - int trendCalculatedBars = BarsCalculated(trendHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // SAR ... - sarCalculatedBars >= maxLength && - // - // RSI ... - rsiCalculatedBars >= maxLength && - // - // ADX ... - adxCalculatedBars >= maxLength && - // - // TREND ... - trendCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // SAR ... - int copiedSars = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // RSI ... - int copiedRSIs = CopyBuffer(rsiHandler, MAIN_LINE, 0, limit, rsiBuffer); - - // - // ADX ... - int copiedADXs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); - - // - // ADX Plus ... - int copiedADXPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxpBuffer); - - // - // ADX Negative ... - int copiedADXNs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxnBuffer); - - // - // TREND ... - int copiedTrends = CopyBuffer(trendHandler, MAIN_LINE, 0, limit, trendBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // SAR ... - copiedSars >= limit && - // - // RSI ... - copiedRSIs >= limit && - // - // TREND ... - copiedTrends >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - return rates_total; -} - -// -// Functions ... - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - sarMax > 0 && - sarStep > 0 && - adxLength > 0 && - rsiLength > 0 && - rsiOBLevel > 0 && - rsiOSLevel > 0 && - sarMax > sarStep && - minZoneLength > 2 && - IsValid(trendPeriodMethod, trendPeriod) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(minZoneLength, rsiLength); - result = MathMax(result, adxLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // TREND ... - - // - ArraySetAsSeries(trendBuffer, true); - SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrend); - - // - PlotIndexSetDouble(trendBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(trendColorBuffer, true); - SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSar); - - // - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Data Buffers ... - - // - ArraySetAsSeries(trendStateBuffer, true); - SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(rsiBuffer, true); - SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxBuffer, true); - SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxpBuffer, true); - SetIndexBuffer(adxpBufferIndex, adxpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxnBuffer, true); - SetIndexBuffer(adxnBufferIndex, adxnBuffer, INDICATOR_CALCULATIONS); -} - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Calculate Custom Buffers ... - * - * @param bar_index: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - // - // bool canCalculate = true; - bool canCalculate = - barsLimit == 0 || - bar_index <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - bar_index, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(bar_index); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - // SAR ... - // sarBuffer[barIndex] = emptyValue; - // sarColorBuffer[barIndex] = hideColorIDX; - // sarStateBuffer[barIndex] = neuturalState; - - // - // TREND ... - // trendBuffer[barIndex] = emptyValue; - // trendColorBuffer[barIndex] = hideColorIDX; - // trendStateBuffer[barIndex] = neuturalState; -} - -/** - * Calculate Values ... - * - * @param bar_index: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Prev Bar ... - - // - int lastBarIndex = bar_index + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - bar_index == maxBarIndex; - - // - double iLow = high[bar_index]; - double iHigh = high[bar_index]; - double iClose = close[bar_index]; - - // - double points = GetPoints(_Symbol); - - // - // Calculate Sar Color Buffer ... - double iSar = sarBuffer[bar_index]; - - // - double iSarState = neuturalState; - double iSarColor = neuturalColorIDX; - if (iLow > iSar) - { - // - iSarState = bullishState; - iSarColor = !showSar - ? hideColorIDX - : bullishColorIDX; - } - else if (iHigh < iSar) - { - // - iSarState = bearishState; - iSarColor = !showSar - ? hideColorIDX - : bearishColorIDX; - } - sarStateBuffer[bar_index] = iSarState; - sarColorBuffer[bar_index] = iSarColor; - - // - // Calculate Trend Color Buffer ... - double iTrend = trendBuffer[bar_index]; - - // - double iTrendState = neuturalState; - double iTrendColor = neuturalColorIDX; - if (iClose > iTrend) - { - // - iTrendState = bullishState; - iTrendColor = !showTrend - ? hideColorIDX - : bullishColorIDX; - } - else if (iClose < iTrend) - { - // - iTrendState = bearishState; - iTrendColor = !showTrend - ? hideColorIDX - : bearishColorIDX; - } - trendStateBuffer[bar_index] = iTrendState; - trendColorBuffer[bar_index] = iTrendColor; - - // - DetectTriggerZone( - bar_index, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); -} - -// -void DetectTriggerZone( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Prev Bar ... - - // - int lastBarIndex = bar_index + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - bar_index == maxBarIndex; - - // - // Prevent Calculation ... - if (maxBarIndex - bar_index < minZoneLength) - { - return; - } - - // - int zIDX = 0; - int cIDX = 0; - int pIDX = 0; - int p2IDX = 0; - int p3IDX = 0; - int p4IDX = 0; - double ll = 0; - double hh = 0; - bool has = false; - ENUM_X_DIRECTION iDir; - - // - // Retrieve Required Bars ... - - // - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - XOHCL cBar; // Current Finished Bar which Start Detecting Structures based on it ( End of Block and FVG Bar ) ... - XOHCL pBar; // Determines Block Gap Bar (all Filtering must applied and Check using this Bar and it's Next Bar) ... - XOHCL p2Bar; // Determines FVG's Start Bar in a Block ... - XOHCL p3Bar; // First Verification of Block ... - XOHCL p4Bar; // Seccond Verification of Block ... - - // - has = zBar.Init( - _Symbol, - _Period, - bar_index // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - has = - has && - p2Bar.GetPreviousBar(p3Bar); - has = - has && - p3Bar.GetPreviousBar(p4Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Define Zone Structure ... - XBoxZone zone; - - // - // Detect Based Order Block using CBar ... - has = barAnalyser.IsOB( - cBar, - zone, - true, // Force FVG Bar Type ... - true // Force Block Two Bar Checking ... - ); - - // - // Ensure a Block is Detected ... - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - zIDX = zBar.Index(); - cIDX = cBar.Index(); - pIDX = pBar.Index(); - p2IDX = p2Bar.Index(); - p3IDX = p3Bar.Index(); - p4IDX = p4Bar.Index(); - - // - bool isBullish = - has && - zone.IsBullish(); - - // - bool isBearish = - has && - zone.IsBearish(); - - // - int toIDX = zone.ToIndex(); - int fromIDX = zone.FromIndex(); - - // - // Validating p2Bar and p3Bar Direction ... - if (has) - { - // - iDir = Opposit(zone.dir); - - // - has = - iDir == p3Bar.GetDirection() || - iDir == p4Bar.GetDirection(); - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Start Validating Block based on - // Detected One ... - - // - // Validating Using Max Range ... - has = maxZoneRangeInPoints > 0; - if (has) - { - // - double range = zone.GetRange(); - has = range <= maxZoneRangeInPoints * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Gap Endup with PinBar ... - has = forceHasPinBarEntry; - if (has) - { - // - bool isBullishRejected = - isBullish && - cBar.IsBullish() && - cBar.GetLowShadow() > cBar.GetHighShadow(); - - // - bool isBearishRejected = - isBearish && - cBar.IsBearish() && - cBar.GetLowShadow() < cBar.GetHighShadow(); - - // - has = isBullishRejected || - isBearishRejected; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Gap Bar must a Momentum Bar and - // Breakes out Zone's Directional Edge ... - // for Bullish: Upper - // for Bearish: Lower - has = forceGapBarsBreakout; - if (has) - { - // - // Gap Bar is PBar ... - - // - // Check Gap Bar is Momentum Bar ... - has = barAnalyser.IsMomentum( - pBar, - iDir // - ); - bool isBullishMomentum = - has && - IsBullish(iDir); - bool isBearishMomentum = - has && - IsBearish(iDir); - - // - // Check Gap Bar's Breakout ... - - // - bool isBullishBreakedout = - isBullish && - pBar.IsBullish() && - isBullishMomentum && - pBar.GetUp() > zone.upper && - pBar.GetDown() < zone.upper; - - // - bool isBearishBreakedout = - isBearish && - pBar.IsBearish() && - isBearishMomentum && - pBar.GetUp() > zone.lower && - pBar.GetDown() < zone.lower; - - // - has = isBullishBreakedout || - isBearishBreakedout; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Zone Has Propper Swing ... - // for Bullish: p2Bar or p3Bar must be a Swing Low ... - // for Bearish: p2Bar or p3Bar must be a Swing High ... - has = forceHasSwing; - if (has) - { - // - // p2Bar ... - bool isP2BarSwing = - barAnalyser - .IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarSwingLow = - isP2BarSwing && - IsBullish(iDir); - bool isP2BarSwingHigh = - isP2BarSwing && - IsBearish(iDir); - - // - // p3Bar ... - bool isP3BarSwing = - barAnalyser - .IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarSwingLow = - isP3BarSwing && - IsBullish(iDir); - bool isP3BarSwingHigh = - isP3BarSwing && - IsBearish(iDir); - - // - bool hasSwingLow = - isBullish && - (isP2BarSwingLow || - isP3BarSwingLow); - - // - bool hasSwingHigh = - isBearish && - (isP2BarSwingHigh || - isP3BarSwingHigh); - - // - has = - hasSwingLow || - hasSwingHigh; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Using Swing Length ... - has = minZoneLength > 0; - if (has) - { - // - XOHCL fromBar; - has = zone.FromBar(fromBar); - if (has) - { - // - // Retrieve HH and LL ... - ll = fromBar.FindLowest(minZoneLength, MODE_LOW); - hh = fromBar.FindHighest(minZoneLength, MODE_HIGH); - - // - // Validate Using HH and LL ... - - // - bool isBullishValid = - isBullish && - ll >= zone.lower; - - // - bool isBearishValid = - isBearish && - hh <= zone.upper; - - // - has = isBullishValid || - isBearishValid; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Update Zone's From Time ... - zone.from = GetBarTime( - zone.symbol, - zone.period, - fromBar.Index() + minZoneLength // - ); - } - - // - fromBar.Clean(); - } - - // - // Validate Max Allowed Entry Distance ... - has = maxAllowedEntryDistance > 0; - if (has) - { - // - double base = - isBullish - ? zone.upper - : zone.lower; - double entryDistance = MathAbs(zBar.open - base); - has = entryDistance <= maxAllowedEntryDistance * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Here we Ensure which have a Valid Zone using Different Applied Validations ... - // from now we are Going to Filtered Validate Zones ... - - // - // Check Exists Filters or not ... - has = filterBasedOnSar || - filterBasedOnRSI || - filterBasedOnADX || - filterBasedOnTrend; - if (has) - { - // - // Do Apply Several Exists Filters ... - - // - // SAR Filter ... - if (filterBasedOnSar) - { - // - // Reading Conditions Values ... - - // - double zSar = sarBuffer[zIDX]; - double cSar = sarBuffer[cIDX]; - double pSar = sarBuffer[pIDX]; - double p2Sar = sarBuffer[p2IDX]; - double p3Sar = sarBuffer[p3IDX]; - double p4Sar = sarBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFiltered = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // RSI Filter ... - if (filterBasedOnRSI) - { - // - // Reading Conditions Values ... - - // - double rsiTrend = (rsiOBLevel + rsiOSLevel) / 2; - - // - double zRSI = rsiBuffer[zIDX]; - double cRSI = rsiBuffer[cIDX]; - double pRSI = rsiBuffer[pIDX]; - double p2RSI = rsiBuffer[p2IDX]; - double p3RSI = rsiBuffer[p3IDX]; - double p4RSI = rsiBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI <= rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI >= rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI > rsiOSLevel && - p2RSI <= rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI < rsiOBLevel && - p2RSI >= rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // ADX Filter ... - if (filterBasedOnADX) - { - // - // Reading Conditions Values ... - - // - // ADX ... - double zADX = adxBuffer[zIDX]; - double cADX = adxBuffer[cIDX]; - double pADX = adxBuffer[pIDX]; - double p2ADX = adxBuffer[p2IDX]; - double p3ADX = adxBuffer[p3IDX]; - double p4ADX = adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = adxpBuffer[zIDX]; - double cADXP = adxpBuffer[cIDX]; - double pADXP = adxpBuffer[pIDX]; - double p2ADXP = adxpBuffer[p2IDX]; - double p3ADXP = adxpBuffer[p3IDX]; - double p4ADXP = adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = adxnBuffer[zIDX]; - double cADXN = adxnBuffer[cIDX]; - double pADXN = adxnBuffer[pIDX]; - double p2ADXN = adxnBuffer[p2IDX]; - double p3ADXN = adxnBuffer[p3IDX]; - double p4ADXN = adxnBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > adxThreshold; - bool isZADXBearish = zADX < adxThreshold; - - // - bool isCADXBullish = cADX > adxThreshold; - bool isCADXBearish = cADX < adxThreshold; - - // - bool isPADXBullish = pADX > adxThreshold; - bool isPADXBearish = pADX < adxThreshold; - - // - bool isP2ADXBullish = p2ADX > adxThreshold; - bool isP2ADXBearish = p2ADX < adxThreshold; - - // - bool isP3ADXBullish = p3ADX > adxThreshold; - bool isP3ADXBearish = p3ADX < adxThreshold; - - // - bool isP4ADXBullish = p4ADX > adxThreshold; - bool isP4ADXBearish = p4ADX < adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // TREND Filter ... - if (filterBasedOnTrend) - { - // - // Reading Conditions Values ... - - // - double zTrend = trendBuffer[zIDX]; - double cTrend = trendBuffer[cIDX]; - double pTrend = trendBuffer[pIDX]; - double p2Trend = trendBuffer[p2IDX]; - double p3Trend = trendBuffer[p3IDX]; - double p4Trend = trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = trendStateBuffer[zIDX]; - double cTrendState = trendStateBuffer[cIDX]; - double pTrendState = trendStateBuffer[pIDX]; - double p2TrendState = trendStateBuffer[p2IDX]; - double p3TrendState = trendStateBuffer[p3IDX]; - double p4TrendState = trendStateBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // SCORE Filter ... - - // - // VOLUME Filter ... - } - - // - // Detect Left Side of Box ... - XOHCL zoneLeftBar; - int idx = fromIDX + 1; - bool isBaseValid = true; - while (isBaseValid) - { - // - // Retrieve iteration Bar ... - has = zoneLeftBar.Init( - _Symbol, - _Period, - idx // - ); - if (!has) - { - // - zoneLeftBar.Clean(); - break; - } - - // - // Check Bar's Validation ... - - // - bool isBullishPassed = - isBullish && - zoneLeftBar.low >= zone.lower; - - // - bool isBearishPassed = - isBearish && - zoneLeftBar.high <= zone.upper; - - // - // Summarize Conditions ... - has = - isBullishPassed || - isBearishPassed; - if (!has) - { - break; - } - - // - idx++; - } - - // - // Ray to Left Side Zone, if Provided ... - if (rayLeft) - { - // - // Update Value ... - fromIDX = zone.FromIndex(); - - // - // Check Last Iteration Bar is Valid Bar ... - // then Update Zone from Time ... - has = zoneLeftBar.IsValid(); - if (has) - { - // - zone.from = zoneLeftBar.time; - fromIDX = zone.FromIndex(); - } - } - - // - // Draw Detected Zone ... - if (drawZones) - { - // - XCBoxObject *iZoneObj; - has = drawer.DrawBox( - zone, - iZoneObj // - ); - if (has) - { - // - ApplyStyle(iZoneObj, zone.dir); - - // - mObjects.Add(iZoneObj); - - // - // TODO: Enable This for Debugging ... - // string message = ToString(zone.dir) + " Zone Detected (" + cBar.time + ") ..."; - // Print(message); - } - ZeroMemory(iZoneObj); - } - - // - // Draw RR Tool ... - if (drawRRofZones) - { - // - double rr[]{ - 1, - 1.5, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10 // - }; - XCRRObject *iRRObj; - iRRObj = new XCRRObject(); - has = iRRObj.CreateBoxRR( - drawer.ChartIdentification(), - drawer.SubWindowIdentification(), - zone, - rr, - rrZoneLength // - ); - if (has) - { - // - int iWidth = 2; - ENUM_LINE_STYLE iStyle = STYLE_SOLID; - - // - iRRObj.TPWidth(iWidth); - iRRObj.SLWidth(iWidth); - iRRObj.EntryWidth(iWidth); - iRRObj.TargetWidth(iWidth); - - // - iRRObj.TPStyle(iStyle); - iRRObj.SLStyle(iStyle); - iRRObj.EntryStyle(iStyle); - iRRObj.TargetStyle(iStyle); - - // - iRRObj.TPColor(clrLime); - iRRObj.SLColor(clrRed); - iRRObj.EntryColor(clrYellow); - iRRObj.TargetColor(clrLightBlue); - - // - mObjects.Add(iRRObj); - } - ZeroMemory(iRRObj); - } - - // - // Handle Alerst ... - bool canAlert = - mEnableAlerts && - prevCalculated > 0; - bool canLogOnly = - mEnableAlerts && - prevCalculated == 0; - if (canAlert || canLogOnly) - { - // - string message = - zone.symbol + "," + - ToString(zone.period) + "> " + - ToString(zone.dir) + - " Zone Detected at: " + ToString(zone.to); - - // - if (canLogOnly) - { - alert.LogAlert(message); - } - else if (canAlert) - { - alert.SendAlert(message); - } - } - - // - // Cleanup Resources ... - - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - zoneLeftBar.Clean(); -} - -// -void ApplyStyle( - XCBoxObject *iObj, - ENUM_X_DIRECTION dir // -) -{ - // - if (!HasDirection(dir) || iObj == NULL) - { - return; - } - - // - int width = boxWidth > 0 - ? boxWidth - : 1; - int clr = IsBullish(dir) - ? bullishColor - : bearishColor; - - // - iObj.BoxColor(clr); - iObj.BoxWidth(width); - iObj.BoxStyle(boxStyle); - - // -} - -// \ No newline at end of file diff --git a/Documents/BKP/Tests/xcaea.cond2.script.mq5 b/Documents/BKP/Tests/xcaea.cond2.script.mq5 deleted file mode 100644 index 09cdfeb8..00000000 --- a/Documents/BKP/Tests/xcaea.cond2.script.mq5 +++ /dev/null @@ -1,647 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XCond2 MQL5 Script -// ------------------------------------------------- -// Name: XCAEA -// Description: an Exper Advisor which used Panels -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XCAEA Cond2 Script" -#property strict - -// -// Imports ... - -// -// Classes ... -#include "../../Classes/x-saherelm.x-poi.class.mq5" - -// -// Libraries ... -#include "../../Libraries/x-saherelm.common.lib.mq5" -#include "../../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Helpers ... -#include "../Helpers/xcaea.helper.mq5" - -// -// Definitions ... - -// -// Holds Drawn Objects ... -CArrayObj mObjects; - -// -// Required Objects ... -int mLoopback = 10; -XCAEAInputs mInputs; -XBarTracker mBarTracker; -XCAEAConditions mConditions; -XCXCAEAHelper *helper = NULL; - -// -// Event Handlers ... - -/** - * Initialize Script ... - * - * @return ( int ) - */ -int OnInit() -{ - // - // Initialize Helper ... - bool isInited = InitHelper(); - if (!isInited) - { - return INIT_FAILED; - } - - // - return INIT_SUCCEEDED; -} - -/** - * De Initialize Script ... - * - * @param reason: Argument 1 - */ -void OnDeinit(const int reason) -{ - // - mInputs.Clean(); - mConditions.Clean(); - - // - ZeroMemory(helper); -} - -/** - * Handle Tick Event ... - */ -void OnTick() -{ - // - bool has = false; - - // - // Run on New Bar ... - bool isNewBar = mBarTracker.IsNewBar(); - if (!isNewBar) - { - return; - } - - // - // Setting Bar Index ... - int barIndex = 0; - - // - // Retrieve Conditions ... - has = helper.GetConditions( - mConditions, - barIndex, - mLoopback // - ); - if (!has) - { - return; - } - - // - // Handling Logic ... - HandleLogic(); -} - -// -// Custom Functions ... - -/** - * Initialize Helper ... - * - * @return ( bool ) - */ -bool InitHelper() -{ - // - bool result = false; - - // - mInputs.Default(); - - // - // Configure Inputs ... - - // - // Oscilators ... - mInputs.showAC = false; - mInputs.showAD = false; - mInputs.showADX = false; - mInputs.showATR = false; - mInputs.showCCI = false; - mInputs.showRSI = false; - mInputs.showMFI = false; - mInputs.showRVI = false; - mInputs.showMACD = false; - mInputs.showMomentum = false; - mInputs.showStochastic = false; - - // - // XCT ... - mInputs.ctInputs.showCandleTime = true; - - // - // XCC ... - mInputs.ccInputs.showCandles = true; - - // - // X3MA ... - mInputs.x3maInputs.showFast = false; - mInputs.x3maInputs.showSlow = false; - mInputs.x3maInputs.showMedium = false; - - // - // XOSC ... - // mInputs.oscsInputs; - - // - // XCA ... - mInputs.caInputs.showKI = false; - mInputs.caInputs.showSar = false; - mInputs.caInputs.showTKI = false; - mInputs.caInputs.showMAH = true; - mInputs.caInputs.showMAL = true; - mInputs.caInputs.showMAC = true; - mInputs.caInputs.showVidya = false; - mInputs.caInputs.showTrend = false; - mInputs.caInputs.showSwings = false; - mInputs.caInputs.showLongCycle = false; - mInputs.caInputs.showHindCycle = false; - mInputs.caInputs.showShortCycle = false; - mInputs.caInputs.showFiboLevel1 = true; - mInputs.caInputs.showFiboLevel2 = false; - mInputs.caInputs.showFiboLevel3 = true; - mInputs.caInputs.showMediumCycle = false; - mInputs.caInputs.showPeaksAndVales = false; - mInputs.caInputs.showPeakAndValeGolden = false; - mInputs.caInputs.showSupportAndResistance = true; - - // - // Initialize Helper ... - helper = new XCXCAEAHelper(); - result = helper.Init( - _Symbol, - _Period, - mInputs // - ); - if (!result) - { - return result; - } - - // - // Initialize Bar Tracker ... - result = mBarTracker.Init( - _Symbol, - _Period // - ); - if (!result) - { - return result; - } - - // - return result; -} - -/** - * Handle Logic of Script ... - */ -void HandleLogic() -{ - // - // Defining Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - bool has = false; - - // - // Reading Required Values ... - - // - // PEAK ... - double zPeak = mConditions.peakBuffer[zIDX]; - double cPeak = mConditions.peakBuffer[cIDX]; - double pPeak = mConditions.peakBuffer[pIDX]; - double p2Peak = mConditions.peakBuffer[p2IDX]; - - // - // VALE ... - double zVale = mConditions.valeBuffer[zIDX]; - double cVale = mConditions.valeBuffer[cIDX]; - double pVale = mConditions.valeBuffer[pIDX]; - double p2Vale = mConditions.valeBuffer[p2IDX]; - - // - // SAR ... - double zSar = mConditions.sarBuffer[zIDX]; - double cSar = mConditions.sarBuffer[cIDX]; - double pSar = mConditions.sarBuffer[pIDX]; - double p2Sar = mConditions.sarBuffer[p2IDX]; - - // - // KI ... - double zKI = mConditions.kiBuffer[zIDX]; - double cKI = mConditions.kiBuffer[cIDX]; - double pKI = mConditions.kiBuffer[pIDX]; - double p2KI = mConditions.kiBuffer[p2IDX]; - - // - // KI State ... - double zKIState = mConditions.kiStateBuffer[zIDX]; - double cKIState = mConditions.kiStateBuffer[cIDX]; - double pKIState = mConditions.kiStateBuffer[pIDX]; - double p2KIState = mConditions.kiStateBuffer[p2IDX]; - - // - // TKI ... - double zTKI = mConditions.tkiBuffer[zIDX]; - double cTKI = mConditions.tkiBuffer[cIDX]; - double pTKI = mConditions.tkiBuffer[pIDX]; - double p2TKI = mConditions.tkiBuffer[p2IDX]; - - // - // TKI State ... - double zTKIState = mConditions.tkiStateBuffer[zIDX]; - double cTKIState = mConditions.tkiStateBuffer[cIDX]; - double pTKIState = mConditions.tkiStateBuffer[pIDX]; - double p2TKIState = mConditions.tkiStateBuffer[p2IDX]; - - // - // MAH ... - double zMAH = mConditions.mahBuffer[zIDX]; - double cMAH = mConditions.mahBuffer[cIDX]; - double pMAH = mConditions.mahBuffer[pIDX]; - double p2MAH = mConditions.mahBuffer[p2IDX]; - - // - // MAL ... - double zMAL = mConditions.malBuffer[zIDX]; - double cMAL = mConditions.malBuffer[cIDX]; - double pMAL = mConditions.malBuffer[pIDX]; - double p2MAL = mConditions.malBuffer[p2IDX]; - - // - // MAC ... - double zMAC = mConditions.macBuffer[zIDX]; - double cMAC = mConditions.macBuffer[cIDX]; - double pMAC = mConditions.macBuffer[pIDX]; - double p2MAC = mConditions.macBuffer[p2IDX]; - - // - // TREND ... - double zTrend = mConditions.trendBuffer[zIDX]; - double cTrend = mConditions.trendBuffer[cIDX]; - double pTrend = mConditions.trendBuffer[pIDX]; - double p2Trend = mConditions.trendBuffer[p2IDX]; - - // - // TREND State ... - double zTrendState = mConditions.trendStateBuffer[zIDX]; - double cTrendState = mConditions.trendStateBuffer[cIDX]; - double pTrendState = mConditions.trendStateBuffer[pIDX]; - double p2TrendState = mConditions.trendStateBuffer[p2IDX]; - - // - // RESISTANCE ... - double zResistance = mConditions.resistanceBuffer[zIDX]; - double cResistance = mConditions.resistanceBuffer[cIDX]; - double pResistance = mConditions.resistanceBuffer[pIDX]; - double p2Resistance = mConditions.resistanceBuffer[p2IDX]; - - // - // SUPPORT ... - double zSupport = mConditions.supportBuffer[zIDX]; - double cSupport = mConditions.supportBuffer[cIDX]; - double pSupport = mConditions.supportBuffer[pIDX]; - double p2Support = mConditions.supportBuffer[p2IDX]; - - // - // VIDYA ... - double zVIDYA = mConditions.vidyaBuffer[zIDX]; - double cVIDYA = mConditions.vidyaBuffer[cIDX]; - double pVIDYA = mConditions.vidyaBuffer[pIDX]; - double p2VIDYA = mConditions.vidyaBuffer[p2IDX]; - - // - // VIDYA State ... - double zVIDYAState = mConditions.vidyaStateBuffer[zIDX]; - double cVIDYAState = mConditions.vidyaStateBuffer[cIDX]; - double pVIDYAState = mConditions.vidyaStateBuffer[pIDX]; - double p2VIDYAState = mConditions.vidyaStateBuffer[p2IDX]; - - // - // SWING Low ... - double zSwingLow = mConditions.swingLowBuffer[zIDX]; - double cSwingLow = mConditions.swingLowBuffer[cIDX]; - double pSwingLow = mConditions.swingLowBuffer[pIDX]; - double p2SwingLow = mConditions.swingLowBuffer[p2IDX]; - - // - // SWING High ... - double zSwingHigh = mConditions.swingHighBuffer[zIDX]; - double cSwingHigh = mConditions.swingHighBuffer[cIDX]; - double pSwingHigh = mConditions.swingHighBuffer[pIDX]; - double p2SwingHigh = mConditions.swingHighBuffer[p2IDX]; - - // - // FIBO Level 1 ... - double zFiboLevel1 = mConditions.fiboLevel1Buffer[zIDX]; - double cFiboLevel1 = mConditions.fiboLevel1Buffer[cIDX]; - double pFiboLevel1 = mConditions.fiboLevel1Buffer[pIDX]; - double p2FiboLevel1 = mConditions.fiboLevel1Buffer[p2IDX]; - - // - // FIBO Level 2 ... - double zFiboLevel2 = mConditions.fiboLevel2Buffer[zIDX]; - double cFiboLevel2 = mConditions.fiboLevel2Buffer[cIDX]; - double pFiboLevel2 = mConditions.fiboLevel2Buffer[pIDX]; - double p2FiboLevel2 = mConditions.fiboLevel2Buffer[p2IDX]; - - // - // FIBO Level 3 ... - double zFiboLevel3 = mConditions.fiboLevel3Buffer[zIDX]; - double cFiboLevel3 = mConditions.fiboLevel3Buffer[cIDX]; - double pFiboLevel3 = mConditions.fiboLevel3Buffer[pIDX]; - double p2FiboLevel3 = mConditions.fiboLevel3Buffer[p2IDX]; - - // - // X3MA ... - - // - // FAST ... - - // - double z3MAFast = mConditions.fastBuffer[zIDX]; - double c3MAFast = mConditions.fastBuffer[cIDX]; - double p3MAFast = mConditions.fastBuffer[pIDX]; - double p23MAFast = mConditions.fastBuffer[p2IDX]; - - // - double z3MAFastState = mConditions.fastStateBuffer[zIDX]; - double c3MAFastState = mConditions.fastStateBuffer[cIDX]; - double p3MAFastState = mConditions.fastStateBuffer[pIDX]; - double p23MAFastState = mConditions.fastStateBuffer[p2IDX]; - - // - // MEDIUM ... - - // - double z3MAMedium = mConditions.mediumBuffer[zIDX]; - double c3MAMedium = mConditions.mediumBuffer[cIDX]; - double p3MAMedium = mConditions.mediumBuffer[pIDX]; - double p23MAMedium = mConditions.mediumBuffer[p2IDX]; - - // - double z3MAMediumState = mConditions.mediumStateBuffer[zIDX]; - double c3MAMediumState = mConditions.mediumStateBuffer[cIDX]; - double p3MAMediumState = mConditions.mediumStateBuffer[pIDX]; - double p23MAMediumState = mConditions.mediumStateBuffer[p2IDX]; - - // - // SLOW ... - - // - double z3MASlow = mConditions.slowBuffer[zIDX]; - double c3MASlow = mConditions.slowBuffer[cIDX]; - double p3MASlow = mConditions.slowBuffer[pIDX]; - double p23MASlow = mConditions.slowBuffer[p2IDX]; - - // - double z3MASlowState = mConditions.slowStateBuffer[zIDX]; - double c3MASlowState = mConditions.slowStateBuffer[cIDX]; - double p3MASlowState = mConditions.slowStateBuffer[pIDX]; - double p23MASlowState = mConditions.slowStateBuffer[p2IDX]; - - // - // RSI ... - double zRSI = mConditions.rsiBuffer[zIDX]; - double cRSI = mConditions.rsiBuffer[cIDX]; - double pRSI = mConditions.rsiBuffer[pIDX]; - double p2RSI = mConditions.rsiBuffer[p2IDX]; - - // - // Reading Bars ... - - // - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - XOHCL p4Bar; - has = zBar.Init( - _Symbol, - _Period, - zIDX // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - has = - has && - p2Bar.GetPreviousBar(p3Bar); - has = - has && - p3Bar.GetPreviousBar(p4Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Reading Bars Related Data ... - - // - // Score ... - - // - double bullishScore = 0; - double bearishScore = 0; - mConditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - bool isScoreBullish = - bullishScore > bearishScore; - - // - bool isScoreBearish = - bearishScore > bullishScore; - - // - // Generating Conditions Summary ... - string summary = - mConditions - .GenerateSummary(); - - // - // Calculating Range Volumes ... - - // - double bullishVolume = 0; - double bearishVolume = 0; - int volumeRangeLoopback = 5; - helper.barAnalyser.CalculateRangeVolume( - cBar, - bullishVolume, - bearishVolume, - volumeRangeLoopback // - ); - - // - double rangeVolume = bullishVolume = bearishVolume; - double rangeVolumeAvg = rangeVolume / volumeRangeLoopback; - - // - // Preparing Complex Conditions ... - - // - bool isRSIBullish = - cRSI > pRSI && - !mConditions.isRSIOB; - - // - bool isRSIBearish = - cRSI < pRSI && - !mConditions.isRSIOS; - - // - bool isVolumeBullish = bullishVolume > bearishVolume; - bool isVolumeBearish = bullishVolume < bearishVolume; - bool isVolumeOverLast = cBar.volume > pBar.volume; - bool isVolumeOverAvg = cBar.volume > rangeVolumeAvg; - - // - // Cond2 ... - - // - bool isCond2Bullish = - // - mConditions.isUnderMal && - mConditions.isValeIsPivot && - // mConditions.swingLowBuffer[cIDX] > mConditions.valeBuffer[cIDX] && - mConditions.swingLowBuffer[cIDX] < mConditions.fiboLevel3Buffer[cIDX] - // - ; - - // - bool isCond2Bearish = - // - false // && - // - ; - - // - bool isCond2 = isCond2Bullish || - isCond2Bearish; - if (isCond2) - { - // - // Print("Cond2"); - // isCond2Bullish = false; - // isCond2Bearish = false; - } - - // - // Check Results ... - - // - bool isBullish = isCond2Bullish; - bool isBearish = isCond2Bearish; - - // - bool result = isBullish || - isBearish; - if (result) - { - // - datetime time = zBar.time; - - // - ENUM_X_DIRECTION iDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Handle Works ... - if (isCond2) - { - // - string name = "Cond2_" + ToString(iDir); - - // - color clr = isBullish - ? clrAqua - : clrMagenta; - - // - CChartObjectHLine *iObj; - iObj = new CChartObjectHLine(); - has = iObj.Create( - 0, - name, - 0, - time // - ); - if (has) - { - // - // Style Object ... - iObj.Width(1); - iObj.Color(clr); - iObj.Style(STYLE_DOT); - - // - // Store Object ... - mObjects.Add(iObj); - } - } - } -} - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-data.collector.class.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-data.collector.class.mq5 deleted file mode 100644 index bbd1d2f7..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-data.collector.class.mq5 +++ /dev/null @@ -1,167 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCAEADataCollector ... -// Description: Class for XCAEA 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 XCAEA Data Collector" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.base.class.mq5" - -// -// Definitions ... - -// -// Implementation ... -class XCXCAEADataCollector : public XCBase -{ - // - // Public ... - public: - // - // Constructors ... - XCXCAEADataCollector() - { - } - - // - // Deconstructor ... - ~XCXCAEADataCollector() - { - } - - // - // Properties ... - - // - string Path() - { - return mPath; - } - - // - void Path(string value) - { - // - // Normalizing Collector Path ... - if (IsValid(value)) - { - mPath = value; - } - else - { - mPath = "XCXCAEADataCollector"; - } - } - - // - // 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; - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - - // - string mPath; // Base Collector Path ... -}; diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 deleted file mode 100644 index 404f1866..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 +++ /dev/null @@ -1,4476 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCAEAPOIDetector ... -// Description: Class for XCAEA POI Detector ... -// -// -// 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 XCAEA POI Detector" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Definitions ... - -// -enum ENUM_XCA_PIVOTS -{ - XCA_NONE, // None - XCA_SWL, // Swing Low - XCA_SWH, // Swing High - XCA_PEAK, // Peak - XCA_VALE, // Vale - XCA_OB_BULL, // OBBull - XCA_OB_BEAR, // OBBear - XCA_FVG_BULL, // FVGBull - XCA_FVG_BEAR, // FVGBear - XCA_RSI_COOS, // RSICOOS - XCA_RSI_CUOB, // RSICUOB - XCA_TREND_BULL, // TrendBull - XCA_TREND_BEAR, // TrendBear -}; - -// -bool IsValid(ENUM_XCA_PIVOTS value) -{ - // - bool result = false; - - // - result = value != XCA_NONE; - - // - return result; -} - -// -string ToString(ENUM_XCA_PIVOTS value) -{ - // - string result = NULL; - - // - result = EnumToString(value); - - // - return result; -} - -// -ENUM_X_DIRECTION GetDirection(ENUM_XCA_PIVOTS value) -{ - // - ENUM_X_DIRECTION result = X_DIRECTION_NONE; - - // - switch (value) - { - // - case XCA_SWL: - case XCA_VALE: - case XCA_OB_BULL: - case XCA_FVG_BULL: - case XCA_RSI_COOS: - case XCA_TREND_BULL: - result = X_DIRECTION_BULLISH; - break; - - // - case XCA_SWH: - case XCA_PEAK: - case XCA_OB_BEAR: - case XCA_FVG_BEAR: - case XCA_RSI_CUOB: - case XCA_TREND_BEAR: - result = X_DIRECTION_BEARISH; - break; - } - - // - return result; -} - -// -string GetBoxType(ENUM_XCA_PIVOTS value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case XCA_SWL: - case XCA_SWH: - case XCA_VALE: - case XCA_PEAK: - case XCA_RSI_COOS: - case XCA_RSI_CUOB: - result = ToString(value); - break; - // - case XCA_OB_BULL: - case XCA_OB_BEAR: - result = "XCA_OB"; - break; - // - case XCA_FVG_BULL: - case XCA_FVG_BEAR: - result = "XCA_FVG"; - break; - - // - case XCA_TREND_BULL: - case XCA_TREND_BEAR: - result = "XCA_TREND"; - break; - } - - // - return result; -} - -// -ENUM_XCA_PIVOTS GetPivotType(XBoxZone &value) -{ - // - ENUM_XCA_PIVOTS result = XCA_NONE; - - // - bool has = value.IsValid(); - if (!has) - { - return result; - } - - // - bool isSWL = value.type == GetBoxType(XCA_SWL) && - value.dir == GetDirection(XCA_SWL); - bool isSWH = value.type == GetBoxType(XCA_SWH) && - value.dir == GetDirection(XCA_SWH); - bool isPeak = value.type == GetBoxType(XCA_PEAK) && - value.dir == GetDirection(XCA_PEAK); - bool isVale = value.type == GetBoxType(XCA_VALE) && - value.dir == GetDirection(XCA_VALE); - bool isOBBull = value.type == GetBoxType(XCA_OB_BULL) && - value.dir == GetDirection(XCA_OB_BULL); - bool isOBBear = value.type == GetBoxType(XCA_OB_BEAR) && - value.dir == GetDirection(XCA_OB_BEAR); - bool isFVGBull = value.type == GetBoxType(XCA_FVG_BULL) && - value.dir == GetDirection(XCA_FVG_BULL); - bool isFVGBear = value.type == GetBoxType(XCA_FVG_BEAR) && - value.dir == GetDirection(XCA_FVG_BEAR); - bool isRSICrossedOverOS = value.type == GetBoxType(XCA_RSI_COOS) && - value.dir == GetDirection(XCA_RSI_COOS); - bool isRSICrossedUnderOB = value.type == GetBoxType(XCA_RSI_CUOB) && - value.dir == GetDirection(XCA_RSI_CUOB); - bool isTrendBullish = value.type == GetBoxType(XCA_TREND_BULL) && - value.dir == GetDirection(XCA_TREND_BULL); - bool isTrendBearish = value.type == GetBoxType(XCA_TREND_BEAR) && - value.dir == GetDirection(XCA_TREND_BEAR); - - // - if (isSWL) - { - result = XCA_SWL; - } - else if (isSWH) - { - result = XCA_SWH; - } - else if (isPeak) - { - result = XCA_PEAK; - } - else if (isVale) - { - result = XCA_VALE; - } - else if (isOBBull) - { - result = XCA_OB_BULL; - } - else if (isOBBear) - { - result = XCA_OB_BEAR; - } - else if (isFVGBull) - { - result = XCA_FVG_BULL; - } - else if (isFVGBear) - { - result = XCA_FVG_BEAR; - } - else if (isRSICrossedOverOS) - { - result = XCA_RSI_COOS; - } - else if (isRSICrossedUnderOB) - { - result = XCA_RSI_CUOB; - } - else if (isTrendBullish) - { - result = XCA_TREND_BULL; - } - else if (isTrendBearish) - { - result = XCA_TREND_BEAR; - } - - // - return result; -} - -// -int ExtractPivots( - XBoxZone &extracted[], - ENUM_XCA_PIVOTS type, - XBoxZone &source[] // -) -{ - // - int result = 0; - - // - Clean(extracted); - - // - bool has = - IsValid(type) && - HasChild(source); - if (!has) - { - return result; - } - - // - int count = ArraySize(source); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - ENUM_XCA_PIVOTS iType = GetPivotType(iBox); - - // - has = iType == type; - if (has) - { - // - AddRef( - iBox, - extracted // - ); - } - - // - iBox.Clean(); - } - - // - result = ArraySize(extracted); - - // - return result; -} - -// -bool IsFakeBreakeout( - XBoxZone &pivot, - XCXCAEAHelper *helper, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - result = pivot.IsValid(); - if (!result) - { - return result; - } - - // - int fromIDX = pivot.FromIndex(); - result = barIndex < fromIDX; - if (!result) - { - return result; - } - - // - bool isBullish = pivot.IsBullish(); - - // - // Retrieve Required Bars ... - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - result = cBar.Init( - pivot.symbol, - pivot.period, - barIndex // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - // - // Bars Conditions ... - - // - ENUM_X_DIRECTION cBarDir; - - // - // Hammer ... - bool isCBarHammer = helper - .barAnalyser - .IsHammer( - cBar, - cBarDir // - ); - bool isCBarBullishHammer = - isCBarHammer && - IsBullish(cBarDir); - bool isCBarBearishHammer = - isCBarHammer && - IsBearish(cBarDir); - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - cBarDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isCBarBullishRejected = - isCBarRejected && - IsBullish(cBarDir); - bool isCBarBearishRejected = - isCBarRejected && - IsBearish(cBarDir); - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - cBarDir // - ); - bool isCBarBullishEngulfed = - isCBarEngulfed && - IsBullish(cBarDir); - bool isCBarBearishEngulfed = - isCBarEngulfed && - IsBearish(cBarDir); - - // - // Momentum ... - bool isCBarMomentum = helper - .barAnalyser - .IsMomentum( - cBar, - cBarDir, - 1 // - ); - bool isCBarBullishMomentum = - isCBarMomentum && - IsBullish(cBarDir); - bool isCBarBearishMomentum = - isCBarMomentum && - IsBearish(cBarDir); - - // - bool isCBarHasBullishPower = isCBarBullishRejected || - isCBarBullishEngulfed || - isCBarBullishMomentum; - - // - bool isCBarHasBearishPower = isCBarBearishRejected || - isCBarBearishEngulfed || - isCBarBearishMomentum; - - // - bool isBarPowerfull = - isBullish - ? isCBarHasBullishPower - : isCBarHasBearishPower; - - // - double breakPrice = - isBullish - ? pivot.lower - : pivot.upper; - - // - // CBar Must Go back InSide Box ... - bool isBarInside = - cBar.GetUp() > breakPrice && - cBar.GetDown() < breakPrice && - cBar.GetDirection() == pivot.dir; - - // - result = - // - // Bar Must Inside Pivot ... - isBarInside && - // - // Bar Must Has Required Direction Power ... - isBarPowerfull - // - ; - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -struct XCAPivot -{ - // - // Props ... - datetime to; - double value; - string symbol; - datetime from; - double reserve; - ENUM_XCA_PIVOTS type; - ENUM_TIMEFRAMES period; - - // - double values[]; - - // - // Constructor ... - XCAPivot() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - value = 0; - to = NULL; - reserve = 0; - from = NULL; - symbol = NULL; - period = NULL; - type = XCA_NONE; - - // - Clean(values); - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - from < to && - value != 0 && - IsValid(to) && - IsValid(from) && - IsValid(type) && - IsValid(symbol) && - IsValid(period); - - // - return result; - } - - /** - * Check a Model is Same as this or not ... - * - * @param pivot: XCAPivot ... - * - * @return ( bool ) - */ - bool IsSameAs(XCAPivot &pivot) - { - // - bool result = false; - - // - result = - IsValid() && - pivot.IsValid(); - if (!result) - { - return result; - } - - // - result = - to == pivot.to && - from == pivot.from && - type == pivot.type && - value == pivot.value && - symbol == pivot.symbol && - period == pivot.period; - - // - return result; - } - - /** - * Retrieve To Index ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int ToIndex( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - result = GetBarIndex( - symbol, - forPeriod, - to // - ); - - // - return result; - } - - /** - * Retrieve From Index ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int FromIndex( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - result = GetBarIndex( - symbol, - forPeriod, - from // - ); - - // - return result; - } - - /** - * Retrieve Age of Pivot ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int GetAge( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - int toIDX = ToIndex(forPeriod); - int fromIDX = FromIndex(forPeriod); - - // - result = fromIDX - toIDX; - - // - return result; - } - - /** - * Converts Pivot to Box ... - * - * @param box: XBoxZone instance reference ... - * - * @return ( bool ) - */ - bool AsBox( - XBoxZone &box // - ) - { - // - bool result = false; - - // - box.Clean(); - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - ENUM_X_DIRECTION iDir = GetDirection(type); - - // - result = HasDirection(iDir); - if (!result) - { - return result; - } - - // - bool isBullish = - IsBullish(iDir) && - value < reserve; - - // - bool isBearish = - IsBearish(iDir) && - value > reserve; - - // - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - box.to = to; - box.dir = iDir; - box.from = from; - box.symbol = symbol; - box.period = period; - - // - string typeStr = GetBoxType(type); - box.type = typeStr; - - // - box.upper = - isBullish - ? reserve - : value; - box.lower = - isBullish - ? value - : reserve; - - // - result = box.IsValid(); - if (!result) - { - box.Clean(); - } - - // - return result; - } - - // -}; - -// -// Implementations ... -class XCXCAEAPOIDetector : public XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - // Pivot Verifications and Max Allowed Holding Items ... - int maxAllowedPivots; // Max Allowed Holding Pibots ... - int pivotVerifications; // Pivots Verifications ... - int pivotDetectionLoopbac; // Pivots Detection Loopback ... - double ticksDividerInPoints; // Ticks and Volume Detection Divider in Point ... - - // - // TREND ... - XBoxZone trendPivotP; // Prev Pivot of Market Trend ... - XBoxZone trendPivotC; // Current Pivot of Market Trend ... - ENUM_X_DIRECTION trendDir; // Trend Direction ... - - // - // Breaked Pivots ... - XBoxZone invalidPivots[]; - - // - // Constructors ... - XCXCAEAPOIDetector( - XCXCAEAHelper *_helper // - ) - { - // - helper = _helper; - drawer = new XCPOIDrawer(); - barAnalyser = new XCBarAnalyser(); - - // - Default(); - } - - // - // De Constructors ... - ~XCXCAEAPOIDetector() - { - // - CleanPivots(); - - // - ZeroMemory(helper); - ZeroMemory(drawer); - ZeroMemory(barAnalyser); - } - - // - // Properties ... - - // - // Tools ... - - // - virtual void Default() - { - // - // COMMON ... - - // - maxAllowedPivots = 50; - pivotVerifications = 5; - ticksDividerInPoints = 15; - pivotDetectionLoopbac = 100; - - // - // SWING ... - - // - maxAllowedSwingLifetime = 0; - - // - detectSWHPivots = false; - detectSWLPivots = false; - - // - // PV ... - - // - detectPeakPivots = false; - detectValePivots = false; - - // - maxAllowedPVLifetime = 0; - applySwingsOnPVPivots = false; - selectRejectedPVPivots = false; - selectEngulfedPVPivots = false; - selectPVWhichStartByFVG = false; - applySupportAndResistanceOnPVPivots = false; - - // - // FVG ... - - // - detectFVGBullishPivots = false; - detectFVGBearishPivots = false; - - // - selectSameBarFVGs = false; - maxAllowedFVGLifetime = 0; - validateFVGUsingPV = false; - applyPVToFVGBoundary = false; - selectRejectedFVGPivots = false; - selectEngulfedFVGPivots = false; - validateFVGUsingManalyser = false; - applyLastBarToFVGBoundary = false; - selectOnlyFVGWhichHasIndirectionalLastBar = false; - - // - // OB ... - maxAllowedOBLifetime = 0; - - // - detectOBBullishPivots = false; - detectOBBearishPivots = false; - - // - // TREND ... - maxAllowedTrendLifetime = 0; - - // - detectTrendBullishPivots = false; - detectTrendBearishPivots = false; - - // - } - - // - void Detect( - int barIndex = 0 // - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - int loopback = pivotDetectionLoopbac; - loopback = NormalizeInt(loopback, 50); - - // - int idx = -1; - int count = 0; - bool has = false; - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - - // - newSWHPivotDetected = false; - newSWLPivotDetected = false; - newPeakPivotDetected = false; - newValePivotDetected = false; - newOBBullishPivotDetected = false; - newOBBearishPivotDetected = false; - newFVGBullishPivotDetected = false; - newFVGBearishPivotDetected = false; - newTrendBullishPivotDetected = false; - newTrendBearishPivotDetected = false; - - // - int index = barIndex; - int start = index; - int end = index + loopback; - while (start < end) - { - // - // Retrieve Conditions ... - XCAEAConditions conditions; - has = helper.GetConditions( - conditions, - start, - 10 // - ); - if (!has) - { - conditions.Clean(); - continue; - } - - // - // Retrieve Bars ... - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - has = zBar.Init( - conditions.symbol, - conditions.period, - start // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - conditions.Clean(); - - // - continue; - } - - // - // Checking Pivots ... - - // - // SWING ... - - // - // SWH ... - if (detectSWHPivots) - { - // - newSWHPivotDetected = DetectSwingPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // SWL ... - if (detectSWLPivots) - { - // - newSWLPivotDetected = DetectSwingPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // PV ... - - // - // PEAK ... - if (detectPeakPivots) - { - // - newPeakPivotDetected = DetectPeakAndValePivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // VALE ... - if (detectValePivots) - { - // - newValePivotDetected = DetectPeakAndValePivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // FVG ... - - // - // Bullish ... - if (detectFVGBullishPivots) - { - // - newFVGBullishPivotDetected = DetectFVGPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectFVGBearishPivots) - { - // - newFVGBearishPivotDetected = DetectFVGPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // OB ... - - // - // Bullish ... - if (detectOBBullishPivots) - { - // - newOBBullishPivotDetected = DetectOBPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectOBBearishPivots) - { - // - newOBBearishPivotDetected = DetectOBPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // TREND ... - - // - // Bullish ... - if (detectTrendBullishPivots) - { - // - newTrendBullishPivotDetected = DetectTrendPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectTrendBearishPivots) - { - // - newTrendBearishPivotDetected = DetectTrendPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Others ... - - // - start++; - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - conditions.Clean(); - } - - // - SortPivots(); - } - - // - void Validate( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - // Implement Validation Senarios ... - - // - // SWING ... - ValidateSwingPivots( - unavailables, - barIndex // - ); - - // - // PV ... - ValidatePeakValePivots( - unavailables, - barIndex // - ); - - // - // OB ... - ValidateOBPivots( - unavailables, - barIndex // - ); - - // - // FVG ... - ValidateFVGPivots( - unavailables, - barIndex // - ); - - // - // TREND ... - ValidateTrendPivots( - unavailables, - barIndex // - ); - - // - SortPivots(); - } - - // - int FillPivots( - XBoxZone &pivots[], - ENUM_X_DIRECTION forDir = X_DIRECTION_ALL // - ) - { - // - int result = 0; - - // - Clean(pivots); - - // - if (forDir == X_DIRECTION_NONE) - { - return result; - } - - // - int count = 0; - bool has = false; - - // - bool canFillBullish = - forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BULLISH; - - // - bool canFillBearish = - forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BEARISH; - - // - // Bullish ... - if (canFillBullish) - { - // - Copy( - swlPivots, - pivots, - false // - ); - - // - Copy( - valePivots, - pivots, - false // - ); - - // - Copy( - obBullishPivots, - pivots, - false // - ); - - // - Copy( - fvgBullishPivots, - pivots, - false // - ); - - // - Copy( - trendBullishPivots, - pivots, - false // - ); - } - - // - // Bearish ... - if (canFillBearish) - { - // - Copy( - swhPivots, - pivots, - false // - ); - - // - Copy( - peakPivots, - pivots, - false // - ); - - // - Copy( - obBearishPivots, - pivots, - false // - ); - - // - Copy( - fvgBearishPivots, - pivots, - false // - ); - - // - Copy( - trendBearishPivots, - pivots, - false // - ); - } - - // - result = ArraySize(pivots); - - // - return result; - } - - // - int FillPivots( - XBoxZone &pivots[], - XBoxZone &unavailables[], - ENUM_XCA_PIVOTS &allowedTypes[], - datetime to = NULL // - ) - { - // - int result = 0; - - // - Clean(pivots); - - // - bool canUpdateTo = IsValid(to); - - // - XBoxZone tmp[]; - bool has = false; - int tmpCount = FillPivots( - tmp, - X_DIRECTION_ALL // - ); - has = IsValidSize(tmpCount); - if (!has) - { - return result; - } - - // - XBoxZone iBox; - while (HasChild(tmp)) - { - // - iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - if (canUpdateTo) - { - iBox.to = to; - } - - // - ENUM_XCA_PIVOTS iType = GetPivotType(iBox); - bool isAllowed = - !HasChild(allowedTypes) - ? true - : Contains( - iType, - allowedTypes // - ); - - // - int idx = -1; - bool isUnAvailable = FindBoxIndex( - idx, - iBox, - unavailables // - ); - - // - if (isAllowed && - !isUnAvailable) - { - // - AddRef( - iBox, - pivots // - ); - } - - // - iBox.Clean(); - } - iBox.Clean(); - - // - result = ArraySize(pivots); - - // - return result; - } - - // - int FillPivots( - XBoxZone &decision, - XBoxZone &pivots[], - XBoxZone &unavailables[], - ENUM_XCA_PIVOTS &allowedTypes[], - datetime to = NULL // - ) - { - // - int result = false; - - // - bool has = false; - has = decision.IsValid(); - if (!has) - { - return result; - } - - // - XBoxZone tmp[]; - int count = FillPivots( - tmp, - unavailables, - allowedTypes, - to // - ); - - // - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = tmp[i]; - - // - // Validate Box ... - has = - // - // Validate Time .. - iBox.from > decision.from - // - && - // - // Validate Price ... - ( - // - (iBox.upper < decision.upper && - iBox.upper > decision.lower) - // - || - // - (iBox.lower > decision.lower && - iBox.lower < decision.upper) - // - ); - if (has) - { - // - AddRef( - iBox, - pivots // - ); - } - - // - iBox.Clean(); - } - - // - Clean(tmp); - - // - result = ArraySize(pivots); - - // - return result; - } - - // - // Pivots ... - - // - // INVALID Pivots ... - - // - bool HasInvalidPivots() - { - return HasChild(invalidPivots); - } - - // - int CountInvalidPivots() - { - return ArraySize(invalidPivots); - } - - // - // SWING ... - - // - int maxAllowedSwingLifetime; // Max Allowed Swing Life ... - - // - bool DetectSwingPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectSWLPivots - : detectSWHPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // SWING High .. - double zSwingHigh = conditions.swingHighBuffer[zIDX]; - double cSwingHigh = conditions.swingHighBuffer[cIDX]; - double pSwingHigh = conditions.swingHighBuffer[pIDX]; - double p2SwingHigh = conditions.swingHighBuffer[p2IDX]; - - // - // SWING Low ... - double zSwingLow = conditions.swingLowBuffer[zIDX]; - double cSwingLow = conditions.swingLowBuffer[cIDX]; - double pSwingLow = conditions.swingLowBuffer[pIDX]; - double p2SwingLow = conditions.swingLowBuffer[p2IDX]; - - // - // Prepare Conditinal Conditions ... - - // - // SWH ... - - // - bool isSWHSameLast = cSwingHigh == pSwingHigh; - bool isSWHSameLastPrev = pSwingHigh == p2SwingHigh; - - // - bool isSWHSwitchedToSameLast = isSWHSameLast && - !isSWHSameLastPrev; - bool isSWHFinishedFromSameLast = !isSWHSameLast && - isSWHSameLastPrev; - - // - // SWL ... - - // - bool isSWLSameLast = cSwingLow == pSwingLow; - bool isSWLSameLastPrev = pSwingLow == p2SwingLow; - - // - bool isSWLSwitchedToSameLast = isSWLSameLast && - !isSWLSameLastPrev; - bool isSWLFinishedFromSameLast = !isSWLSameLast && - isSWLSameLastPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - // - forBullish - ? isSWLFinishedFromSameLast - : isSWHFinishedFromSameLast - // - ; - - // - bool hasContinuationCondition = - // - forBullish - ? isSWLSameLast - : isSWHSameLast - // - ; - - // - bool hasEndCondition = - // - forBullish - ? isSWLSwitchedToSameLast - : isSWHSwitchedToSameLast - // - ; - - // - // - // - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // SWL ... - if (forBullish) - { - // - swlPivot.Clean(); - - // - swlPivot.type = XCA_SWL; - swlPivot.symbol = symbol; - swlPivot.period = period; - - // - swlPivot.to = pBar.time; - swlPivot.from = pBar.time; - swlPivot.value = pSwingLow; - swlPivot.reserve = pVale; - } - - // - // SWH ... - if (forBearish) - { - // - swhPivot.Clean(); - - // - swhPivot.type = XCA_SWH; - swhPivot.symbol = symbol; - swhPivot.period = period; - - // - swhPivot.to = pBar.time; - swhPivot.from = pBar.time; - swhPivot.value = pSwingHigh; - swhPivot.reserve = pPeak; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // SWL ... - if (forBullish) - { - // - swlPivot.from = pBar.time; - - // - swlPivot.reserve = - swlPivot.reserve == 0 - ? pVale - : MathMin(swlPivot.reserve, pVale); - } - - // - // SWH ... - if (forBearish) - { - // - swhPivot.from = pBar.time; - - // - swhPivot.reserve = - swhPivot.reserve == 0 - ? pPeak - : MathMin(swhPivot.reserve, pPeak); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // SWL ... - if (forBullish) - { - // - result = - swlPivot.IsValid() && - swlPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = swlPivot.AsBox(iBox); - if (result) - { - // - newSWLPivotDetected = AddBox( - iBox, - swlPivots // - ); - } - - // - iBox.Clean(); - } - - // - swlPivot.Clean(); - } - - // - // SWH ... - if (forBearish) - { - // - result = - swhPivot.IsValid() && - swhPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = swhPivot.AsBox(iBox); - if (result) - { - // - newSWHPivotDetected = AddBox( - iBox, - swhPivots // - ); - } - - // - iBox.Clean(); - } - - // - swhPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidateSwingPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedSwingLifetime > 0; - - // - // SWH ... - has = HasSWHPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - swhPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - swhPivots, - maxAllowedSwingLifetime, - barIndex // - ); - } - } - - // - // SWL ... - has = HasSWLPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - swlPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - swlPivots, - maxAllowedSwingLifetime, - barIndex // - ); - } - } - } - - // - // SWL ... - - // - XCAPivot swlPivot; - bool detectSWLPivots; - XBoxZone swlPivots[]; - bool newSWLPivotDetected; - - // - bool HasSWLPivots() - { - return HasChild(swlPivots); - } - - // - int CountSWLPivots() - { - return ArraySize(swlPivots); - } - - // - // SWH ... - - // - XCAPivot swhPivot; - bool detectSWHPivots; - XBoxZone swhPivots[]; - bool newSWHPivotDetected; - - // - bool HasSWHPivots() - { - return HasChild(swhPivots); - } - - // - int CountSWHPivots() - { - return ArraySize(swhPivots); - } - - // - // PV ... - - // - int maxAllowedPVLifetime; // Max Allowed PV Life ... - bool applySwingsOnPVPivots; // Apply Swings on PV Pivots ... - bool selectRejectedPVPivots; // Select Rejected PV Pivots ... - bool selectEngulfedPVPivots; // Select Engulfed PV Pivots ... - bool selectPVWhichStartByFVG; // Select PV Pivots Which Starts by FVG ... - bool applySupportAndResistanceOnPVPivots; // Apply Support and Resistance on PV Pivots ... - - // - bool DetectPeakAndValePivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectValePivots - : detectPeakPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // PEAK Golden ... - double zPeakGolden = conditions.peakGoldenBuffer[zIDX]; - double cPeakGolden = conditions.peakGoldenBuffer[cIDX]; - double pPeakGolden = conditions.peakGoldenBuffer[pIDX]; - double p2PeakGolden = conditions.peakGoldenBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // VALE Golden ... - double zValeGolden = conditions.valeGoldenBuffer[zIDX]; - double cValeGolden = conditions.valeGoldenBuffer[cIDX]; - double pValeGolden = conditions.valeGoldenBuffer[pIDX]; - double p2ValeGolden = conditions.valeGoldenBuffer[p2IDX]; - - // - // SWING High .. - double zSwingHigh = conditions.swingHighBuffer[zIDX]; - double cSwingHigh = conditions.swingHighBuffer[cIDX]; - double pSwingHigh = conditions.swingHighBuffer[pIDX]; - double p2SwingHigh = conditions.swingHighBuffer[p2IDX]; - - // - // SWING Low ... - double zSwingLow = conditions.swingLowBuffer[zIDX]; - double cSwingLow = conditions.swingLowBuffer[cIDX]; - double pSwingLow = conditions.swingLowBuffer[pIDX]; - double p2SwingLow = conditions.swingLowBuffer[p2IDX]; - - // - // SUPPORT ... - double zSupport = conditions.supportBuffer[zIDX]; - double cSupport = conditions.supportBuffer[cIDX]; - double pSupport = conditions.supportBuffer[pIDX]; - double p2Support = conditions.supportBuffer[p2IDX]; - - // - // RESISTANCE ... - double zResistance = conditions.resistanceBuffer[zIDX]; - double cResistance = conditions.resistanceBuffer[cIDX]; - double pResistance = conditions.resistanceBuffer[pIDX]; - double p2Resistance = conditions.resistanceBuffer[p2IDX]; - - // - // Detecting Bar Conditions ... - - // - ENUM_X_DIRECTION cBarDir; - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - cBarDir, - false, // Force Type ... - false // Force Fibo Pressure ... - ); - - // - bool isCBarBullishRejected = - forBullish && - isCBarRejected && - IsBullish(cBarDir); - bool isCBarBearishRejected = - forBearish && - isCBarRejected && - IsBearish(cBarDir); - - // - bool isPBarRejected = helper - .barAnalyser - .IsRejected( - pBar, - cBarDir, - false, // Force Type ... - false // Force Fibo Pressure ... - ); - bool isPBarBullishRejected = - forBullish && - isPBarRejected && - IsBullish(cBarDir); - bool isPBarBearishRejected = - forBearish && - isPBarRejected && - IsBearish(cBarDir); - - // - bool isBarBullishRejected = - forBullish && - (isCBarBullishRejected || - isPBarBullishRejected); - - // - bool isBarBearishRejected = - forBearish && - (isCBarBearishRejected || - isPBarBearishRejected); - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - cBarDir // - ); - bool isCBarBullishEngulfed = - forBullish && - isCBarEngulfed && - IsBullish(cBarDir); - bool isCBarBearishEngulfed = - forBearish && - isCBarEngulfed && - IsBearish(cBarDir); - - // - bool isPBarEngulfed = helper - .barAnalyser - .IsEngulfed( - pBar, - cBarDir // - ); - bool isPBarBullishEngulfed = - forBullish && - isPBarEngulfed && - IsBullish(cBarDir); - bool isPBarBearishEngulfed = - forBearish && - isPBarEngulfed && - IsBearish(cBarDir); - - // - bool isBarBullishEngulfed = - forBullish && - (isCBarBullishEngulfed || - isPBarBullishEngulfed); - - // - bool isBarBearishEngulfed = - forBearish && - (isCBarBearishEngulfed || - isPBarBearishEngulfed); - - // - // Prepare Conditinal Conditions ... - - // - // PEAK ... - - // - bool isPeakSameLast = cPeak == pPeak; - bool isPeakSameLastPrev = pPeak == p2Peak; - - // - if (applySwingsOnPVPivots) - { - // - isPeakSameLast = - isPeakSameLast && - cSwingHigh == cPeak && - cSwingHigh == pSwingHigh; - - // - isPeakSameLastPrev = - isPeakSameLastPrev && - pSwingHigh == pPeak && - pSwingHigh == p2SwingHigh; - } - - // - if (applySupportAndResistanceOnPVPivots) - { - // - isPeakSameLast = - isPeakSameLast && - cResistance == cPeak && - cResistance == pResistance; - - // - isPeakSameLastPrev = - isPeakSameLastPrev && - pResistance == pPeak && - pResistance == p2Resistance; - } - - // - bool isPeakSwitchedToSameLast = isPeakSameLast && - !isPeakSameLastPrev; - bool isPeakFinishedFromSameLast = !isPeakSameLast && - isPeakSameLastPrev; - - // - // VALE ... - - // - bool isValeSameLast = cVale == pVale; - bool isValeSameLastPrev = pVale == p2Vale; - - // - if (applySwingsOnPVPivots) - { - // - isValeSameLast = - isValeSameLast && - cSwingLow == cVale && - cSwingLow == pSwingLow; - - // - isValeSameLastPrev = - isValeSameLastPrev && - pSwingLow == pVale && - pSwingLow == p2SwingLow; - } - - // - if (applySupportAndResistanceOnPVPivots) - { - // - isValeSameLast = - isValeSameLast && - cSupport == cVale && - cSupport == pSupport; - - // - isValeSameLastPrev = - isValeSameLastPrev && - pSupport == pVale && - pSupport == p2Support; - } - - // - bool isValeSwitchedToSameLast = isValeSameLast && - !isValeSameLastPrev; - bool isValeFinishedFromSameLast = !isValeSameLast && - isValeSameLastPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - // - forBullish - ? isValeFinishedFromSameLast - : isPeakFinishedFromSameLast - // - ; - - // - bool hasContinuationCondition = - // - forBullish - ? isValeSameLast - : isPeakSameLast - // - ; - - // - bool hasEndCondition = - // - forBullish - ? isValeSwitchedToSameLast - : isPeakSwitchedToSameLast - // - ; - - // - // Apply Validations ... - if (hasEndCondition) - { - // - bool hasSelectionType = selectRejectedPVPivots || - selectEngulfedPVPivots; - - // - bool isPVRejected = - forBullish - ? (isBarBullishRejected && - selectRejectedPVPivots) - : (isBarBearishRejected && - selectRejectedPVPivots); - - // - bool isPVEngulfed = - forBullish - ? (isBarBullishEngulfed && - selectEngulfedPVPivots) - : (isBarBearishEngulfed && - selectEngulfedPVPivots); - - // - bool isBarPassed = - !hasSelectionType - ? true - : isPVRejected || - isPVEngulfed; - - // - hasEndCondition = - isBarPassed && - hasEndCondition; - if (!hasEndCondition) - { - // - // VALE ... - if (forBullish) - { - valePivot.Clean(); - } - - // - // PEAK ... - if (forBearish) - { - peakPivot.Clean(); - } - } - } - - // - // - // - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // VALE ... - if (forBullish) - { - // - valePivot.Clean(); - - // - valePivot.type = XCA_VALE; - valePivot.symbol = symbol; - valePivot.period = period; - - // - valePivot.to = pBar.time; - valePivot.from = pBar.time; - valePivot.value = pVale; - valePivot.reserve = pValeGolden; - } - - // - // PEAK ... - if (forBearish) - { - // - peakPivot.Clean(); - - // - peakPivot.type = XCA_PEAK; - peakPivot.symbol = symbol; - peakPivot.period = period; - - // - peakPivot.to = pBar.time; - peakPivot.from = pBar.time; - peakPivot.value = pPeak; - peakPivot.reserve = pPeakGolden; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // VALE ... - if (forBullish) - { - // - valePivot.from = pBar.time; - - // - valePivot.reserve = - valePivot.reserve == 0 - ? pValeGolden - : MathMin(valePivot.reserve, pValeGolden); - } - - // - // PEAK ... - if (forBearish) - { - // - peakPivot.from = pBar.time; - - // - peakPivot.reserve = - peakPivot.reserve == 0 - ? pPeakGolden - : MathMax(peakPivot.reserve, pPeakGolden); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // VALE ... - if (forBullish) - { - // - result = - valePivot.IsValid() && - valePivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = valePivot.AsBox(iBox); - if (result) - { - // - newValePivotDetected = AddBox( - iBox, - valePivots // - ); - } - - // - iBox.Clean(); - } - - // - valePivot.Clean(); - } - - // - // PEAK ... - if (forBearish) - { - // - result = - peakPivot.IsValid() && - peakPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = peakPivot.AsBox(iBox); - if (result) - { - // - newPeakPivotDetected = AddBox( - iBox, - peakPivots // - ); - } - - // - iBox.Clean(); - } - - // - peakPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidatePeakValePivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedPVLifetime > 0; - - // - // PEAK ... - has = HasPeakPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - peakPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - peakPivots, - maxAllowedPVLifetime, - barIndex // - ); - } - } - - // - // VALE ... - has = HasValePivots(); - if (has) - { - // - ApplyValidationOnBoxes( - valePivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - valePivots, - maxAllowedPVLifetime, - barIndex // - ); - } - } - } - - // - // PEAK ... - - // - XCAPivot peakPivot; - bool detectPeakPivots; - XBoxZone peakPivots[]; - bool newPeakPivotDetected; - - // - bool HasPeakPivots() - { - return HasChild(peakPivots); - } - - // - int CountPeakPivots() - { - return ArraySize(peakPivots); - } - - // - // VALE ... - - // - XCAPivot valePivot; - bool detectValePivots; - XBoxZone valePivots[]; - bool newValePivotDetected; - - // - bool HasValePivots() - { - return HasChild(valePivots); - } - - // - int CountValePivots() - { - return ArraySize(valePivots); - } - - // - // OB ... - int maxAllowedOBLifetime; // Max Allowed OB Life ... - - // - bool DetectOBPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectOBBullishPivots - : detectOBBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Prepare Conditinal Conditions ... - - // - // Default OB Detection ... - XBoxZone obBox; - bool isOB = barAnalyser.IsOB( - cBar, - obBox, - true, // OB FVG Bar Type ... - true // TWO Bar Verification ... - ); - bool isBullishOB = - isOB && - forBullish && - obBox.IsBullish(); - bool isBearishOB = - isOB && - forBearish && - obBox.IsBearish(); - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = false; - bool hasContinuationCondition = false; - bool hasEndCondition = isBullishOB || - isBearishOB; - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - XBoxZone iBox; - XCAPivot iPivot; - - // - iPivot.to = obBox.to; - iPivot.from = obBox.from; - iPivot.symbol = obBox.symbol; - iPivot.period = obBox.period; - iPivot.type = forBullish - ? XCA_OB_BULL - : XCA_OB_BEAR; - iPivot.value = forBullish - ? obBox.lower - : obBox.upper; - iPivot.reserve = forBullish - ? obBox.upper - : obBox.lower; - - // - result = iPivot.IsValid(); - if (result) - { - // - result = iPivot.AsBox(iBox); - if (result) - { - // - if (forBullish) - { - // - result = AddBox( - iBox, - obBullishPivots // - ); - } - else - { - // - result = AddBox( - iBox, - obBearishPivots // - ); - } - } - } - - // - iBox.Clean(); - iPivot.Clean(); - } - - // - return result; - } - - // - void ValidateOBPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedOBLifetime > 0; - - // - // Bullish ... - has = HasOBBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - obBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - obBullishPivots, - maxAllowedOBLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasOBBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - obBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - obBearishPivots, - maxAllowedOBLifetime, - barIndex // - ); - } - } - } - - // - // OB Bullish Pivots ... - - // - bool detectOBBullishPivots; - XBoxZone obBullishPivots[]; - bool newOBBullishPivotDetected; - - // - bool HasOBBullishPivots() - { - return HasChild(obBullishPivots); - } - - // - int CountOBBullishPivots() - { - return ArraySize(obBullishPivots); - } - - // - // OB Bearish Pivots ... - - // - bool detectOBBearishPivots; - XBoxZone obBearishPivots[]; - bool newOBBearishPivotDetected; - - // - bool HasOBBearishPivots() - { - return HasChild(obBearishPivots); - } - - // - int CountOBBearishPivots() - { - return ArraySize(obBearishPivots); - } - - // - // FVG ... - - // - bool selectSameBarFVGs; // Select FVGs which has Same Type Bars ... - bool validateFVGUsingPV; // Detect FVG Type Two ( Validating Using PV ) ... - int maxAllowedFVGLifetime; // Max Allowed FVG Life ... - bool applyPVToFVGBoundary; // Apply PV to FVG Boundary ... - bool selectRejectedFVGPivots; // Select Rejected FVG Pivots ... - bool selectEngulfedFVGPivots; // Select Engulfed FVG Pivots ... - bool validateFVGUsingManalyser; // Detect FVG Type One ( Validating Using MAnalyser ) ... - bool applyLastBarToFVGBoundary; // Apply Last Bar to FVG Boundary ... - bool selectOnlyFVGWhichHasIndirectionalLastBar; // Select Only FVGs which has Indirectionsl Last Bar, uses to Order Block ... - - // - bool DetectFVGPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectFVGBullishPivots - : detectFVGBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // MANALYSER ... - - // - // MAH ... - double zMAH = conditions.mahBuffer[zIDX]; - double cMAH = conditions.mahBuffer[cIDX]; - double pMAH = conditions.mahBuffer[pIDX]; - double p2MAH = conditions.mahBuffer[p2IDX]; - - // - // MAL ... - double zMAL = conditions.malBuffer[zIDX]; - double cMAL = conditions.malBuffer[cIDX]; - double pMAL = conditions.malBuffer[pIDX]; - double p2MAL = conditions.malBuffer[p2IDX]; - - // - // MAC ... - double zMAC = conditions.macBuffer[zIDX]; - double cMAC = conditions.macBuffer[cIDX]; - double pMAC = conditions.macBuffer[pIDX]; - double p2MAC = conditions.macBuffer[p2IDX]; - - // - // Detecting Bar Conditions ... - - // - ENUM_X_DIRECTION p2BarDir; - - // - // Rejected ... - bool isP2BarRejected = helper - .barAnalyser - .IsRejected( - p2Bar, - p2BarDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isP2BarBullishRejected = - isP2BarRejected && - IsBullish(p2BarDir); - bool isP2BarBearishRejected = - isP2BarRejected && - IsBearish(p2BarDir); - - // - // Engulfed ... - bool isP2BarEngulfed = helper - .barAnalyser - .IsEngulfed( - p2Bar, - p2BarDir // - ); - bool isP2BarBullishEngulfed = - isP2BarEngulfed && - IsBullish(p2BarDir); - bool isP2BarBearishEngulfed = - isP2BarEngulfed && - IsBearish(p2BarDir); - - // - // Prepare Conditinal Conditions ... - - // - // Default FVG Detection ... - XBoxZone fvgBox; - bool isFVG = barAnalyser.IsFVG( - cBar, - fvgBox // - ); - bool isBullishFVG = - isFVG && - forBullish && - fvgBox.IsBullish(); - bool isBearishFVG = - isFVG && - forBearish && - fvgBox.IsBearish(); - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = false; - bool hasContinuationCondition = false; - bool hasEndCondition = isBullishFVG || - isBearishFVG; - - // - // Apply all Filtering ... - if (hasEndCondition) - { - // - XOHCL p3Bar; - p2Bar.GetPreviousBar(p3Bar); - - // - bool isFVGValid = true; - - // - // Validate FVG Using Manalyser ... - bool isManalyserValid = false; - if (validateFVGUsingManalyser) - { - // - isManalyserValid = - hasEndCondition && - (forBullish - ? fvgBox.upper <= cMAL - : fvgBox.lower >= cMAH); - } - - // - // Validate FVG Using PV ... - bool isPVValid = false; - if (validateFVGUsingPV) - { - // - isPVValid = - hasEndCondition && - (forBullish - ? (p2Peak < pPeak || - pPeak < cPeak) - : (p2Vale > pVale || - pVale > cVale)); - } - - // - // Select Pure FVG ... - bool isPureFVGValid = - !validateFVGUsingPV && - !validateFVGUsingManalyser; - - // - // Summarise Validation ... - isFVGValid = - isPVValid || - isPureFVGValid || - isManalyserValid; - - // - bool isFVGBarPassed = false; - - // - // Select Same Bars FVGs ... - bool isFVGHasSameBar = true; - if (selectSameBarFVGs) - { - // - isFVGHasSameBar = - forBullish - ? (cBar.IsBullish() && - pBar.IsBullish() && - p2Bar.IsBullish()) - : (cBar.IsBearish() && - pBar.IsBearish() && - p2Bar.IsBearish()); - isFVGBarPassed = - isFVGBarPassed || - isFVGHasSameBar; - } - - // - // Select Rejected FVG ... - bool isFVGRejected = true; - if (selectRejectedFVGPivots) - { - // - isFVGRejected = - (forBullish - ? isP2BarBullishRejected - : isP2BarBearishRejected); - isFVGBarPassed = - isFVGBarPassed || - isFVGRejected; - } - - // - // Select Engulfed FVG ... - bool isFVGEngulfed = true; - if (selectEngulfedFVGPivots) - { - // - isFVGEngulfed = - (forBullish - ? isP2BarBullishEngulfed - : isP2BarBearishEngulfed); - isFVGBarPassed = - isFVGBarPassed || - isFVGEngulfed; - } - - // - // Select Only FVGs Which Has Indirectional Last Bar ... - bool isFVGHasIndirectionalStart = true; - if (selectOnlyFVGWhichHasIndirectionalLastBar) - { - // - isFVGHasIndirectionalStart = - p3Bar.IsValid() && - (forBullish - ? p3Bar.IsBearish() - : p3Bar.IsBullish()); - isFVGBarPassed = - isFVGBarPassed || - isFVGHasIndirectionalStart; - } - - // - // Summarise Bar Pass ... - isFVGBarPassed = - (selectSameBarFVGs || - selectRejectedFVGPivots || - selectEngulfedFVGPivots || - selectOnlyFVGWhichHasIndirectionalLastBar) - ? isFVGBarPassed - : true; - - // - hasEndCondition = isFVGValid && - isFVGBarPassed; - - // - // Apply Boundary ... - if (hasEndCondition) - { - // - double iValue = - forBullish - ? fvgBox.upper - : fvgBox.lower; - - // - if (applyPVToFVGBoundary) - { - // - fvgBox.upper = - forBullish - ? fvgBox.upper - : cPeak; - - // - fvgBox.lower = - forBullish - ? cVale - : fvgBox.lower; - } - - // - if (applyLastBarToFVGBoundary) - { - // - fvgBox.lower = MathMin(p3Bar.low, fvgBox.lower); - fvgBox.upper = MathMax(p3Bar.high, fvgBox.upper); - } - } - - // - p3Bar.Clean(); - } - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - XBoxZone iBox; - XCAPivot iPivot; - - // - iPivot.to = fvgBox.to; - iPivot.from = fvgBox.from; - iPivot.symbol = fvgBox.symbol; - iPivot.period = fvgBox.period; - iPivot.type = forBullish - ? XCA_FVG_BULL - : XCA_FVG_BEAR; - iPivot.value = forBullish - ? fvgBox.lower - : fvgBox.upper; - iPivot.reserve = forBullish - ? fvgBox.upper - : fvgBox.lower; - - // - result = iPivot.IsValid(); - if (result) - { - // - result = iPivot.AsBox(iBox); - if (result) - { - // - if (forBullish) - { - // - result = AddBox( - iBox, - fvgBullishPivots // - ); - } - else - { - // - result = AddBox( - iBox, - fvgBearishPivots // - ); - } - } - } - - // - iBox.Clean(); - iPivot.Clean(); - } - - // - return result; - } - - // - void ValidateFVGPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedFVGLifetime > 0; - - // - // Bullish ... - has = HasFVGBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - fvgBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - fvgBullishPivots, - maxAllowedFVGLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasFVGBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - fvgBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - fvgBearishPivots, - maxAllowedFVGLifetime, - barIndex // - ); - } - } - } - - // - // FVG Bullish Pivots ... - - // - bool detectFVGBullishPivots; - XBoxZone fvgBullishPivots[]; - bool newFVGBullishPivotDetected; - - // - bool HasFVGBullishPivots() - { - return HasChild(fvgBullishPivots); - } - - // - int CountFVGBullishPivots() - { - return ArraySize(fvgBullishPivots); - } - - // - // FVG Bearish Pivots ... - - // - bool detectFVGBearishPivots; - XBoxZone fvgBearishPivots[]; - bool newFVGBearishPivotDetected; - - // - bool HasFVGBearishPivots() - { - return HasChild(fvgBearishPivots); - } - - // - int CountFVGBearishPivots() - { - return ArraySize(fvgBearishPivots); - } - - // - // TREND ... - - // - int maxAllowedTrendLifetime; // Max Allowed Trend Life ... - - // - bool DetectTrendPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectTrendBullishPivots - : detectTrendBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // TREND ... - double zTrend = conditions.trendBuffer[zIDX]; - double cTrend = conditions.trendBuffer[cIDX]; - double pTrend = conditions.trendBuffer[pIDX]; - double p2Trend = conditions.trendBuffer[p2IDX]; - - // - // TREND State ... - double zTrendState = conditions.trendStateBuffer[zIDX]; - double cTrendState = conditions.trendStateBuffer[cIDX]; - double pTrendState = conditions.trendStateBuffer[pIDX]; - double p2TrendState = conditions.trendStateBuffer[p2IDX]; - - // - // Prepare Conditinal Conditions ... - - // - // Bullish ... - - // - bool isTrendBullish = - cTrendState > 0; - bool isTrendBullishPrev = - pTrendState > 0; - - // - bool isTrendSwitchedToBullish = isTrendBullish && - !isTrendBullishPrev; - bool isTrendFinishedFromBullish = !isTrendBullish && - isTrendBullishPrev; - - // - // Bearish ... - - // - bool isTrendBearish = - cTrendState < 0; - bool isTrendBearishPrev = - pTrendState < 0; - - // - bool isTrendSwitchedToBearish = isTrendBearish && - !isTrendBearishPrev; - bool isTrendFinishedFromBearish = !isTrendBearish && - isTrendBearishPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - forBullish - ? isTrendFinishedFromBullish - : isTrendFinishedFromBearish; - bool hasContinuationCondition = - forBullish - ? isTrendBullish - : isTrendBearish; - bool hasEndCondition = - forBullish - ? isTrendSwitchedToBullish - : isTrendSwitchedToBearish; - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // Bullish ... - if (forBullish) - { - // - trendBullishPivot.Clean(); - - // - trendBullishPivot.symbol = symbol; - trendBullishPivot.period = period; - trendBullishPivot.type = XCA_TREND_BULL; - - // - trendBullishPivot.to = pBar.time; - trendBullishPivot.from = pBar.time; - trendBullishPivot.value = pTrend; - trendBullishPivot.reserve = pTrend; - } - - // - // Bearish ... - if (forBearish) - { - // - trendBearishPivot.Clean(); - - // - trendBearishPivot.symbol = symbol; - trendBearishPivot.period = period; - trendBearishPivot.type = XCA_TREND_BEAR; - - // - trendBearishPivot.to = pBar.time; - trendBearishPivot.from = pBar.time; - trendBearishPivot.value = pTrend; - trendBearishPivot.reserve = pTrend; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // Bullish ... - if (forBullish) - { - // - trendBullishPivot.from = pBar.time; - - // - Add( - pTrend, - trendBullishPivot.values // - ); - Add( - pTrend, - trendBullishPivot.values // - ); - } - - // - // Bearish ... - if (forBearish) - { - // - trendBearishPivot.from = pBar.time; - - // - Add( - pTrend, - trendBearishPivot.values // - ); - Add( - pTrend, - trendBearishPivot.values // - ); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // Bullish ... - if (forBullish) - { - // - // Update Values ... - trendBullishPivot.value = GetMin(trendBullishPivot.values); - trendBullishPivot.reserve = GetMax(trendBullishPivot.values); - - // - result = - trendBullishPivot.IsValid() && - trendBullishPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = trendBullishPivot.AsBox(iBox); - if (result) - { - // - newTrendBullishPivotDetected = AddBox( - iBox, - trendBullishPivots // - ); - } - - // - iBox.Clean(); - } - - // - trendBullishPivot.Clean(); - } - - // - // Bearish ... - if (forBearish) - { - // - // Update Values ... - trendBearishPivot.value = GetMax(trendBearishPivot.values); - trendBearishPivot.reserve = GetMin(trendBearishPivot.values); - - // - result = - trendBearishPivot.IsValid() && - trendBearishPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = trendBearishPivot.AsBox(iBox); - if (result) - { - // - newTrendBearishPivotDetected = AddBox( - iBox, - trendBearishPivots // - ); - } - - // - iBox.Clean(); - } - - // - trendBearishPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidateTrendPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedTrendLifetime > 0; - - // - // Bullish ... - has = HasTrendBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - trendBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - trendBullishPivots, - maxAllowedTrendLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasTrendBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - trendBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - trendBearishPivots, - maxAllowedTrendLifetime, - barIndex // - ); - } - } - } - - // - // Bullish ... - - // - XCAPivot trendBullishPivot; - XBoxZone trendBullishPivots[]; - bool detectTrendBullishPivots; - bool newTrendBullishPivotDetected; - - // - bool HasTrendBullishPivots() - { - return HasChild(trendBullishPivots); - } - - // - int CountTrendBullishPivots() - { - return ArraySize(trendBullishPivots); - } - - // - // Bearish ... - - // - XCAPivot trendBearishPivot; - XBoxZone trendBearishPivots[]; - bool detectTrendBearishPivots; - bool newTrendBearishPivotDetected; - - // - bool HasTrendBearishPivots() - { - return HasChild(trendBearishPivots); - } - - // - int CountTrendBearishPivots() - { - return ArraySize(trendBearishPivots); - } - - // - // Protected ... - protected: - // - // Props ... - - // - // Prrivate ... - private: - // - // Props ... - - // - XCPOIDrawer *drawer; - XCXCAEAHelper *helper; - XCBarAnalyser *barAnalyser; - - // - bool AddBox( - XBoxZone &box, - XBoxZone &boxes[] // - ) - { - // - bool result = false; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - box, - boxes // - ); - result = !isExists; - if (!result) - { - return result; - } - - // - int before = ArraySize(boxes); - - // - AddRef( - box, - boxes // - ); - - // - int after = ArraySize(boxes); - - // - result = after > before; - - // - return result; - } - - // - bool ValidateBox( - XBoxZone &box, - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize Bar Index ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Ceck Input Box is Valid ... - result = box.IsValid(); - if (!result) - { - return result; - } - - // - // Check Input Box is Available ... - bool canCheckUnAvailableBoxes = HasChild(unavailables); - if (canCheckUnAvailableBoxes) - { - // - int idx = -1; - bool isUnAvailable = FindBoxIndex( - idx, - box, - unavailables // - ); - result = !isUnAvailable; - if (!result) - { - return result; - } - } - - // - // Check Input Box is Breaked or not ... - - // - // Check Bar Index must after Box To Index ... - int toIDX = box.ToIndex(); - int fromIDX = box.FromIndex(); - result = toIDX > barIndex && - fromIDX > barIndex && - fromIDX > toIDX; - if (!result) - { - return result; - } - - // - // Detect Box Applied Boundary Price ... - // For Checking Break of Box ... - bool isBullish = box.IsBullish(); - double boundary = - isBullish - ? box.lower - : box.upper; - - // - // for validating Box Break we have to wait At Least 3 Bars Close - // out of Box Boundary ... - int barsLength = 3; - - // - // Calculate Start Checking Bar Index ... - int startCheckBreaktionBarIndex = toIDX - barsLength; - bool isBarIndexValid = startCheckBreaktionBarIndex > 0 && - barIndex < startCheckBreaktionBarIndex; - result = isBarIndexValid; - if (!result) - { - // - // Assume Box is Valid if Bar Index not Valid for Checking ... - result = true; - return result; - } - - // - // Try to Check Box Validation if Everything is OK ... - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - bool isValid = false; - bool isBreaked = false; - for (int i = barIndex; i < startCheckBreaktionBarIndex; i++) - { - // - // Initialize Bars ... - isValid = cBar.Init( - box.symbol, - box.period, - i + 1 // - ); - isValid = - result && - cBar.GetPreviousBar(pBar); - isValid = - result && - pBar.GetPreviousBar(p2Bar); - if (!isValid) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - result = false; - - // - break; - } - - // - // Preparing Conditions ... - - // - bool isBullishBreaked = - isBullish && - cBar.close < boundary && - pBar.close < boundary && - p2Bar.close < boundary; - - // - bool isBearishBreaked = - !isBullish && - cBar.close > boundary && - pBar.close > boundary && - p2Bar.close > boundary; - - // - // Calculate Result ... - isBreaked = isBullishBreaked || - isBearishBreaked; - if (isBreaked) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - result = false; - - // - break; - } - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - } - - // - result = isValid && - !isBreaked; - if (!result) - { - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - box, - invalidPivots // - ); - if (!isExists) - { - // - AddRef( - box, - invalidPivots // - ); - } - } - - // - // Cleanup Resource ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - void CleanPivots() - { - // - Clean(invalidPivots); - - // - swlPivot.Clean(); - swhPivot.Clean(); - peakPivot.Clean(); - valePivot.Clean(); - trendBullishPivot.Clean(); - trendBearishPivot.Clean(); - - // - Clean(swlPivots); - Clean(swhPivots); - - // - Clean(peakPivots); - Clean(valePivots); - - // - Clean(obBullishPivots); - Clean(obBearishPivots); - - // - Clean(fvgBullishPivots); - Clean(fvgBearishPivots); - - // - Clean(trendBullishPivots); - Clean(trendBearishPivots); - } - - // - void SortPivots() - { - // - bool has = false; - - // - // Invalid Pivots ... - has = HasInvalidPivots(); - if (has) - { - ApplySortOnBoxes(invalidPivots); - } - - // - // SWING ... - - // - // SWH ... - has = HasSWHPivots(); - if (has) - { - ApplySortOnBoxes(swhPivots); - } - - // - // SWL ... - has = HasSWLPivots(); - if (has) - { - ApplySortOnBoxes(swlPivots); - } - - // - // PV ... - - // - // PEAK ... - has = HasPeakPivots(); - if (has) - { - ApplySortOnBoxes(peakPivots); - } - - // - // VALE ... - has = HasValePivots(); - if (has) - { - ApplySortOnBoxes(valePivots); - } - - // - // OB ... - - // - // Bullish ... - has = HasOBBullishPivots(); - if (has) - { - ApplySortOnBoxes(obBullishPivots); - } - - // - // Bearish ... - has = HasOBBearishPivots(); - if (has) - { - ApplySortOnBoxes(obBearishPivots); - } - - // - // FVG ... - - // - // Bullish ... - has = HasFVGBullishPivots(); - if (has) - { - ApplySortOnBoxes(fvgBullishPivots); - } - - // - // Bearish ... - has = HasFVGBearishPivots(); - if (has) - { - ApplySortOnBoxes(fvgBearishPivots); - } - - // - // TREND ... - - // - // Bullish ... - has = HasTrendBullishPivots(); - if (has) - { - ApplySortOnBoxes(trendBullishPivots); - } - - // - // Bearish ... - has = HasTrendBearishPivots(); - if (has) - { - ApplySortOnBoxes(trendBearishPivots); - } - } - - // - void ApplySortOnBoxes( - XBoxZone &items[] // - ) - { - // - int idx = -1; - bool has = false; - - // - has = HasChild(items); - if (!has) - { - return; - } - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - - // - while (HasChild(tmp)) - { - // - idx = GetOldest(tmp); - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - XBoxZone iBox = tmp[idx]; - ArrayRemove( - tmp, - idx, - 1 // - ); - - // - AddRef( - iBox, - items // - ); - } - - // - CleanupArray( - items, - maxAllowedPivots // - ); - - // - Clean(tmp); - } - - // - void ApplyValidationOnBoxes( - XBoxZone &items[], - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - has = HasChild(items); - if (!has) - { - return; - } - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - while (HasChild(tmp)) - { - // - XBoxZone iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - has = ValidateBox( - iBox, - unavailables, - barIndex // - ); - if (has) - { - // - AddRef( - iBox, - items // - ); - } - - // - iBox.Clean(); - // - } - - // - Clean(tmp); - } - - // - void ApplyLifeTimeValidationOnBoxes( - XBoxZone &items[], - int maxAllowedAge = 0, - int barIndex = 0 // - ) - { - // - bool has = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - has = - maxAllowedAge > 0 && - HasChild(items); - if (!has) - { - return; - } - - // - datetime cTime = GetBarTime( - helper.GetSymbol(), - helper.GetPeriod(), - barIndex // - ); - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - - // - while (HasChild(tmp)) - { - // - XBoxZone iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - datetime defTo = iBox.to; - iBox.to = cTime; - - // - int iAge = iBox.GetAge(); - has = iAge <= maxAllowedAge; - iBox.to = defTo; - if (has) - { - // - AddRef( - iBox, - items // - ); - } - else - { - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - iBox, - invalidPivots // - ); - if (!isExists) - { - // - AddRef( - iBox, - invalidPivots // - ); - } - } - - // - iBox.Clean(); - } - - // - Clean(tmp); - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 deleted file mode 100644 index 1031fc77..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 +++ /dev/null @@ -1,1490 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCAEAPOIDrawer ... -// Description: Class for XCAEA POI Drawer ... -// -// -// 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 XCAEA POI Drawer" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" - -// -// Definitions ... -struct XCAPivotStyle -{ - // - // Properties ... - int width; - color clr; - ENUM_LINE_STYLE style; - - // - // Constructor ... - XCAPivotStyle() - { - Default(); - } - - // - // Tools ... - - // - // Cleanup Model ... - void Clean() - { - // - width = 1; - clr = CLR_NONE; - style = STYLE_SOLID; - - // - ZeroMemory(this); - } - - // - // Default Props ... - void Default() - { - // - width = 1; - clr = CLR_NONE; - style = STYLE_SOLID; - } -}; - -// -// Implementations ... -class XCXCAEAPOIDrawer : public XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - bool ignoreUpdateOSCTos; - - // - // Drawers ... - bool drawSWHPivots; - bool drawSWLPivots; - bool drawPeakPivots; - bool drawValePivots; - bool drawOBBullishPivots; - bool drawOBBearishPivots; - bool drawFVGBullishPivots; - bool drawFVGBearishPivots; - bool drawTrendBullishPivots; - bool drawTrendBearishPivots; - - // - // Styling ... - - // - XCAPivotStyle defaultBullishStyle; - XCAPivotStyle defaultBearishStyle; - - // - XCAPivotStyle swhPivotStyle; - XCAPivotStyle swlPivotStyle; - - // - XCAPivotStyle peakPivotStyle; - XCAPivotStyle valePivotStyle; - - // - XCAPivotStyle obBullishPivotStyle; - XCAPivotStyle obBearishPivotStyle; - - // - XCAPivotStyle fvgBullishPivotStyle; - XCAPivotStyle fvgBearishPivotStyle; - - // - XCAPivotStyle trendBullishPivotStyle; - XCAPivotStyle trendBearishPivotStyle; - - // - // Constructors ... - XCXCAEAPOIDrawer( - XCXCAEAPOIDetector *_detector // - ) - { - // - detector = _detector; - drawer = new XCPOIDrawer(); - - // - Default(); - } - - // - // De Constructors ... - ~XCXCAEAPOIDrawer() - { - // - Clear(); - - // - ZeroMemory(drawer); - ZeroMemory(detector); - } - - // - // Properties ... - - // - // Tools ... - - // - virtual void Default() - { - // - // Drawing ... - drawSWHPivots = false; - drawSWLPivots = false; - drawPeakPivots = false; - drawValePivots = false; - drawOBBullishPivots = false; - drawOBBearishPivots = false; - drawFVGBullishPivots = false; - drawFVGBearishPivots = false; - drawTrendBullishPivots = false; - drawTrendBearishPivots = false; - - // - // Styling ... - - // - // Bullish ... - defaultBullishStyle.width = 1; - defaultBullishStyle.clr = clrLime; - defaultBullishStyle.style = STYLE_SOLID; - - // - // Bearish ... - defaultBearishStyle.width = 1; - defaultBearishStyle.clr = clrRed; - defaultBearishStyle.style = STYLE_SOLID; - - // - // Pivots ... - - // - // SWING ... - swhPivotStyle = defaultBearishStyle; - swlPivotStyle = defaultBullishStyle; - - // - // PV ... - peakPivotStyle = defaultBearishStyle; - valePivotStyle = defaultBullishStyle; - - // - // OB ... - obBullishPivotStyle = defaultBullishStyle; - obBearishPivotStyle = defaultBearishStyle; - - // - // FVG ... - fvgBullishPivotStyle = defaultBullishStyle; - fvgBearishPivotStyle = defaultBearishStyle; - - // - // TREND ... - trendBullishPivotStyle = defaultBullishStyle; - trendBearishPivotStyle = defaultBearishStyle; - } - - // - void Draw(datetime to = NULL) - { - // - // SWING ... - DrawSWHPivots(to); - DrawSWLPivots(to); - - // - // PV ... - DrawPeakPivots(to); - DrawValePivots(to); - - // - // OB ... - DrawOBBullishPivots(to); - DrawOBBearishPivots(to); - - // - // FVG ... - DrawFVGBullishPivots(to); - DrawFVGBearishPivots(to); - - // - // TREND ... - DrawTrendBullishPivots(to); - DrawTrendBearishPivots(to); - } - - // - void DrawPivot( - XBoxZone &pivot, - datetime to = NULL // - ) - { - // - DrawBox( - pivot, - to, - false, - false // - ); - } - - // - void DrawBox( - XBoxZone &box, - datetime to = NULL, - bool drawMiddle = false, - bool ignoreType = false // - ) - { - // - bool has = box.IsValid(); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - box.to = to; - } - - // - // Draw Box as POI ... - if (!ignoreType) - { - // - // Detect Pivot Type ... - ENUM_XCA_PIVOTS iType = GetPivotType(box); - has = IsValid(iType); - if (!has) - { - return; - } - - // - switch (iType) - { - // - case XCA_SWH: - // - DrawSWHPivot( - box, - to // - ); - break; - - // - case XCA_SWL: - // - DrawSWLPivot( - box, - to // - ); - break; - - // - case XCA_PEAK: - // - DrawPeakPivot( - box, - to // - ); - break; - - // - case XCA_VALE: - // - DrawValePivot( - box, - to // - ); - break; - - // - case XCA_OB_BULL: - // - DrawOBBullishPivot( - box, - to // - ); - break; - - // - case XCA_OB_BEAR: - // - DrawOBBearishPivot( - box, - to // - ); - break; - - // - case XCA_FVG_BULL: - // - DrawFVGBullishPivot( - box, - to // - ); - break; - - // - case XCA_FVG_BEAR: - // - DrawFVGBearishPivot( - box, - to // - ); - break; - - // - case XCA_TREND_BULL: - // - DrawTrendBullishPivot( - box, - to // - ); - break; - - // - case XCA_TREND_BEAR: - // - DrawTrendBearishPivot( - box, - to // - ); - break; - } - } - // - // Draw Regular Box ... - else - { - // - // Select Styling Config ... - XCAPivotStyle style; - - // - if (box.IsBullish()) - { - style = defaultBullishStyle; - } - else - { - style = defaultBearishStyle; - } - - // - // Draw Box itself ... - XCBoxObject *iBoxObj; - has = drawer.DrawBox( - box, - iBoxObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iBoxObj, - style // - ); - - // - // Store Object ... - mObjects.Add(iBoxObj); - } - - // - // Draw Box Middle Range ... - if (drawMiddle) - { - // - double middle = box.GetMid(); - string middleName = box.GetMiddleTag(); - - // - CChartObjectTrend *iMidObj; - iMidObj = new CChartObjectTrend(); - has = iMidObj.Create( - drawer.ChartIdentification(), - middleName, - drawer.SubWindowIdentification(), - box.from, - middle, - box.to, - middle // - ); - if (has) - { - // - // Styling Object ... - iMidObj.Color(style.clr); - iMidObj.Width(style.width); - iMidObj.Style(style.style); - - // - // Store Object ... - mObjects.Add(iMidObj); - } - } - - // - style.Clean(); - } - } - - // - void DrawBoxes( - XBoxZone &boxes[], - datetime to = NULL, - bool drawMiddle = false, - bool ignoreType = false // - ) - { - // - bool has = HasChild(boxes); - if (!has) - { - return; - } - - // - int count = ArraySize(boxes); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = boxes[i]; - - // - // Detect Pivot Type ... - DrawBox( - iBox, - to, - drawMiddle, - ignoreType // - ); - - // - iBox.Clean(); - } - } - - // - void Clear() - { - // - // Cleanup Models ... - defaultBullishStyle.Clean(); - defaultBearishStyle.Clean(); - - // - // Cleanup Styles ... - swhPivotStyle.Clean(); - swlPivotStyle.Clean(); - peakPivotStyle.Clean(); - valePivotStyle.Clean(); - obBullishPivotStyle.Clean(); - obBearishPivotStyle.Clean(); - fvgBullishPivotStyle.Clean(); - fvgBearishPivotStyle.Clean(); - trendBullishPivotStyle.Clean(); - trendBearishPivotStyle.Clean(); - - // - // Cleanup Pivot Objects Holder ... - mObjects.Clear(); - mSWHPivotObjects.Clear(); - mSWLPivotObjects.Clear(); - mPeakPivotObjects.Clear(); - mValePivotObjects.Clear(); - mOBBullishPivotObjects.Clear(); - mOBBearishPivotObjects.Clear(); - mFVGBullishPivotObjects.Clear(); - mFVGBearishPivotObjects.Clear(); - mTrendBullishPivotObjects.Clear(); - mTrendBearishPivotObjects.Clear(); - } - - // - // Collection Drawers ... - - // - void DrawSWHPivots(datetime to = NULL) - { - // - bool has = drawSWHPivots; - if (!has) - { - return; - } - - // - has = detector.HasSWHPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountSWHPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.swhPivots[i]; - - // - DrawSWHPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawSWLPivots(datetime to = NULL) - { - // - bool has = drawSWLPivots; - if (!has) - { - return; - } - - // - has = detector.HasSWLPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountSWLPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.swlPivots[i]; - - // - DrawSWLPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawPeakPivots(datetime to = NULL) - { - // - bool has = drawPeakPivots; - if (!has) - { - return; - } - - // - has = detector.HasPeakPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountPeakPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.peakPivots[i]; - - // - DrawPeakPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawValePivots(datetime to = NULL) - { - // - bool has = drawValePivots; - if (!has) - { - return; - } - - // - has = detector.HasValePivots(); - if (!has) - { - return; - } - - // - int count = detector.CountValePivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.valePivots[i]; - - // - DrawValePivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawOBBullishPivots(datetime to = NULL) - { - // - bool has = drawOBBullishPivots; - if (!has) - { - return; - } - - // - has = detector.HasOBBullishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountOBBullishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.obBullishPivots[i]; - - // - DrawOBBullishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawOBBearishPivots(datetime to = NULL) - { - // - bool has = drawOBBearishPivots; - if (!has) - { - return; - } - - // - has = detector.HasOBBearishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountOBBearishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.obBearishPivots[i]; - - // - DrawOBBearishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawFVGBullishPivots(datetime to = NULL) - { - // - bool has = drawFVGBullishPivots; - if (!has) - { - return; - } - - // - has = detector.HasFVGBullishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountFVGBullishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.fvgBullishPivots[i]; - - // - DrawFVGBullishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawFVGBearishPivots(datetime to = NULL) - { - // - bool has = drawFVGBearishPivots; - if (!has) - { - return; - } - - // - has = detector.HasFVGBearishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountFVGBearishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.fvgBearishPivots[i]; - - // - DrawFVGBearishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawTrendBullishPivots(datetime to = NULL) - { - // - bool has = drawTrendBullishPivots; - if (!has) - { - return; - } - - // - has = detector.HasTrendBullishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountTrendBullishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.trendBullishPivots[i]; - - // - DrawTrendBullishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - void DrawTrendBearishPivots(datetime to = NULL) - { - // - bool has = drawTrendBearishPivots; - if (!has) - { - return; - } - - // - has = detector.HasTrendBearishPivots(); - if (!has) - { - return; - } - - // - int count = detector.CountTrendBearishPivots(); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = detector.trendBearishPivots[i]; - - // - DrawTrendBearishPivot( - iBox, - to // - ); - - // - iBox.Clean(); - } - } - - // - // One Item Drawers ... - - // - void DrawSWHPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawSWHPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_SWH) && - item.dir == GetDirection(XCA_SWH); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - swhPivotStyle // - ); - - // - // Store Object ... - mSWHPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawSWLPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawSWLPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_SWL) && - item.dir == GetDirection(XCA_SWL); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - swlPivotStyle // - ); - - // - // Store Object ... - mSWLPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawPeakPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawPeakPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_PEAK) && - item.dir == GetDirection(XCA_PEAK); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - peakPivotStyle // - ); - - // - // Store Object ... - mPeakPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawValePivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawValePivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_VALE) && - item.dir == GetDirection(XCA_VALE); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - valePivotStyle // - ); - - // - // Store Object ... - mValePivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawOBBullishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawOBBullishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_OB_BULL) && - item.dir == GetDirection(XCA_OB_BULL); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - obBullishPivotStyle // - ); - - // - // Store Object ... - mOBBullishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawOBBearishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawOBBearishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_OB_BEAR) && - item.dir == GetDirection(XCA_OB_BEAR); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - obBearishPivotStyle // - ); - - // - // Store Object ... - mOBBearishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawFVGBullishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawFVGBullishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_FVG_BULL) && - item.dir == GetDirection(XCA_FVG_BULL); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - fvgBullishPivotStyle // - ); - - // - // Store Object ... - mFVGBullishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawFVGBearishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawFVGBearishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_FVG_BEAR) && - item.dir == GetDirection(XCA_FVG_BEAR); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - fvgBearishPivotStyle // - ); - - // - // Store Object ... - mFVGBearishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawTrendBullishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawTrendBullishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_TREND_BULL) && - item.dir == GetDirection(XCA_TREND_BULL); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - trendBullishPivotStyle // - ); - - // - // Store Object ... - mTrendBullishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - void DrawTrendBearishPivot( - XBoxZone &item, - datetime to = NULL // - ) - { - // - bool has = drawTrendBearishPivots; - if (!has) - { - return; - } - - // - has = item.IsValid() && - item.type == GetBoxType(XCA_TREND_BEAR) && - item.dir == GetDirection(XCA_TREND_BEAR); - if (!has) - { - return; - } - - // - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - item.to = to; - } - - // - XCBoxObject *iObj; - has = drawer.DrawBox( - item, - iObj // - ); - if (has) - { - // - // Style Object ... - ApplyPivotStyle( - iObj, - trendBearishPivotStyle // - ); - - // - // Store Object ... - mTrendBearishPivotObjects.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Protected ... - protected: - // - // Props ... - - // - void ApplyPivotStyle( - XCBoxObject *&object, - XCAPivotStyle &style // - ) - { - // - if (object == NULL) - { - return; - } - - // - object.BoxColor(style.clr); - object.BoxWidth(style.width); - object.BoxStyle(style.style); - } - - // - // Prrivate ... - private: - // - // Props ... - - // - XCPOIDrawer *drawer; - XCXCAEAPOIDetector *detector; - - // - CArrayObj mObjects; - - // - CArrayObj mSWHPivotObjects; - CArrayObj mSWLPivotObjects; - - // - CArrayObj mPeakPivotObjects; - CArrayObj mValePivotObjects; - - // - CArrayObj mOBBullishPivotObjects; - CArrayObj mOBBearishPivotObjects; - - // - CArrayObj mFVGBullishPivotObjects; - CArrayObj mFVGBearishPivotObjects; - - // - CArrayObj mTrendBullishPivotObjects; - CArrayObj mTrendBearishPivotObjects; - - // - CArrayObj mTriggerBlockBullishPivotObjects; - CArrayObj mTriggerBlockBearishPivotObjects; - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 deleted file mode 100644 index 055b87dc..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 +++ /dev/null @@ -1,2296 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XCXCAEATradeManager -// Description: provides all Requirements for Managing Trades ... -// -// -// 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-poi.drawer.class.mq5" -#include "../../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/xcaea.x-data.collector.class.mq5" -#include "../Libraries/xcaea.signaller.lib.mq5" - -// -// Definitions ... - -// -enum ENUM_XCAEA_TRADE_RESTRICTION_PERIOD -{ - XCAEA_TRADE_RESTRICATION_NONE, // None - XCAEA_TRADE_RESTRICATION_HOURLY, // Per Hour - XCAEA_TRADE_RESTRICATION_DAILY, // Per Day - XCAEA_TRADE_RESTRICATION_WEEKLY, // Per Week - XCAEA_TRADE_RESTRICATION_MONTHLY, // Per Month -}; - -// -string ToString(ENUM_XCAEA_TRADE_RESTRICTION_PERIOD value) -{ - // - string result = NULL; - - // - result = EnumToString(value); - - // - return result; -} - -// -enum ENUM_XCAEA_TRADE_FINALIZATION -{ - XCAEA_TRADE_FINAL_NONE, // None - XCAEA_TRADE_FINAL_TP, // TP - XCAEA_TRADE_FINAL_SL, // SL - XCAEA_TRADE_FINAL_CLOSE_IN_PROFIT, // Profit - XCAEA_TRADE_FINAL_CLOSE_IN_LOSE, // Lost -}; - -// -string ToString(ENUM_XCAEA_TRADE_FINALIZATION value) -{ - // - string result = NULL; - - // - result = EnumToString(value); - - // - return result; -} - -// -struct XCAEASymbolInfo -{ - // - // Properties ... - - // - string symbol; // Trading Symbol - - // - int longs; // All Long Trades - int shorts; // All Short Trades - - // - int trades; // All Trades - - // - int losses; // All Loosing Trades - int profits; // All Winning Trades - - // - int managedSLs; // Managed SL(s) - int managedTPs; // Managed TP(s) - int managedTrades; // Managed Trades - - // - // Constructor ... - XCAEASymbolInfo() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - - // - longs = 0; - shorts = 0; - - // - trades = 0; - - // - losses = 0; - profits = 0; - - // - managedSLs = 0; - managedTPs = 0; - managedTrades = 0; - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid(symbol); - - // - return result; - } - - // - bool IsSameAs(XCAEASymbolInfo &item) - { - // - bool result = false; - - // - result = IsValid() && - item.IsValid() && - symbol == item.symbol; - - // - return result; - } -}; - -// -struct XCAEATradeSession -{ - // - // Properties ... - string start; // Session Start Time (hh:mm) - string end; // Session End Time (hh:mm) - string name; // Session Name - - // - // Constructor ... - XCAEATradeSession() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - end = NULL; - name = NULL; - start = NULL; - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid(start) && - IsValid(end); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Check Session is Active or Not ... - bool IsActive(datetime time = NULL) - { - // - bool result = false; - - // - time = NormalizeTime(time); - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - result = IsTimeInRange( - time, - start, - end // - ); - - // - return result; - } -}; - -struct XCAEASymbolSession -{ - // - // Propeties ... - - // - string symbol; // Trading Symbol - XCAEATradeSession sessions[]; // Trading Sessions - - // - // Constructor ... - XCAEASymbolSession() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - Clean(sessions); - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid(symbol); - - // - return result; - } - - // - // Check Allow Trade in Active Sessions ... - bool CanTrade(datetime time = NULL) - { - // - bool result = false; - - // - // Normalize Args ... - time = NormalizeTime(time); - - // - // Validating ... - result = IsValid(); - if (!result) - { - return result; - } - - // - // if there is not any defined sessions for Symbol ... - // it's allow Trading in all times ... - result = !HasChild(sessions); - if (result) - { - return result; - } - - // - // Detect an Active Session ... - int count = ArraySize(sessions); - for (int i = 0; i < count; i++) - { - // - result = sessions[i].IsActive(time); - if (result) - { - break; - } - } - - // - return result; - } - - // -}; - -// -struct XCAEATrade -{ - // - // Props ... - double swap; - double profit; - XSignal signal; - ulong positionID; - double commission; - XCAEAStrategyConditions conditions; - ENUM_XCAEA_TRADE_FINALIZATION finalize; - - // - datetime signaledAt; - datetime executedAt; - datetime finalizedAt; - - // - // Constructor ... - XCAEATrade() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup Model ... - */ - void Clean() - { - // - swap = 0; - profit = 0; - signal.Clean(); - commission = 0; - positionID = 0; - conditions.Clean(); - finalize = XCAEA_TRADE_FINAL_NONE; - - // - signaledAt = NULL; - executedAt = NULL; - finalizedAt = NULL; - - // - ZeroMemory(this); - } - - /** - * Check Has Signal ... - * - * @return ( bool ) - */ - bool HasSignal() - { - // - bool result = false; - - // - result = signal.IsValid(); - - // - return result; - } - - /** - * Check Signal Executed or Not ... - * - * @return ( bool ) - */ - bool IsExecuted() - { - // - bool result = false; - - // - result = positionID > 0; - - // - return result; - } - - /** - * Check a Trade is Finalized or not ... - * - * @return ( bool ) - */ - bool IsFinalized() - { - // - bool result = false; - - // - result = HasSignal() && - IsExecuted() && - finalize != XCAEA_TRADE_FINAL_NONE; - - // - return result; - } - - /** - * Generate Summary Info ... - * - * @return ( string ) - */ - string Summary() - { - // - string result = NULL; - - // - result = - // - ToString("Swap: ", swap) + - ToString("Profit: ", profit) + - ToString("Commission: ", commission) + - ToString("Finalize: ", ToString(finalize)) + - ToString("PositionID: ", positionID) + - ToString("----------------") + "\n" + - ToString("Signaled At: ", ToFormatString(signaledAt)) + - ToString("Executed At: ", ToFormatString(executedAt)) + - ToString("Finalized At: ", ToFormatString(finalizedAt)) - // - ; - - // - return result; - } - - /** - * Get Data Collection File Name ... - * - * @return ( string ) - */ - string GetFileName() - { - // - string result = NULL; - - // - bool hasSignal = HasSignal(); - bool isExecuted = IsExecuted(); - bool isFinalized = IsFinalized(); - if (!hasSignal && !isExecuted && !isFinalized) - { - return result; - } - - // - result = - // - signal.symbol + "\\" + - ToString(signal.type) + "\\" + - (profit >= 0 ? "Profit" : "Loss") + "\\" + - ToString(positionID) + "_" + - ToString(signal.period) + "_" + - ToFormatString(signaledAt) - // - ; - - // - return result; - } - - /** - * Converts Model to String Representation ... - * - * @param onlySignals: Boolean, Specified Represent Only Signal or not ... - * - * @return ( string ) - */ - string ToString( - bool includeSummary = true, - bool includeSignal = true, - bool includeConditions = true // - ) - { - // - string result = NULL; - - // - // Generating Model Summary ... - string summary = Summary(); - - // - // Generating Signal Summary ... - string signalSummary = signal.ToString(); - - // - // Generating Conditions Summary ... - string conditionsSummary = conditions - .conditions - .GenerateSummary( - true, - true, - true, - false // Ignore False Conditions ... - ); - - // - if (includeSummary) - { - // - result += - ToString("----------------") + "\n" + - ToString("Summary: ") + "\n" + - ToString("----------------") + "\n" + - summary + "\n"; - } - - // - if (includeSignal) - { - // - result += - ToString("----------------") + "\n" + - ToString("Signal: ") + "\n" + - ToString("----------------") + "\n" + - signalSummary + "\n"; - } - - // - if (includeConditions) - { - // - result += - ToString("----------------") + "\n" + - ToString("Conditions: ") + "\n" + - ToString("----------------") + "\n" + - conditionsSummary + "\n"; - } - - // - return result; - } -}; - -// -// Implementations ... -class XCXCAEATradeManager : public XCBaseAlert -{ - // - // Public ... - public: - // - // Props ... - XCTrade *trader; - bool drawSignal; - XCPOIDrawer *drawer; - XTimeTracker timeTracker; - XCXCAEADataCollector *collector; - - // - // Constructors ... - XCXCAEATradeManager( - XCTrade *&_trader, - string _path = NULL // Base Path - ) - { - // - trader = _trader; - drawSignal = true; - drawer = new XCPOIDrawer(); - - // - allowTrade = true; - allowLongs = true; - allowShorts = true; - - // - forceCloseAt = NULL; - isForceCloseAtTime = false; - - // - maxAllowedTPs = 0; - maxAllowedSLs = 0; - maxAllowedTrades = 0; - restrictionsPeriod = XCAEA_TRADE_RESTRICATION_NONE; - - // - reportTrades = true; - reportSignals = true; - reportProtector = true; - reportAfterTradesBalance = true; - - // - SaveTrades(false); - - // - // Normalizing Collector Path ... - if (!IsValid(_path)) - { - _path = "X121XCAEATradeManager" + "\\" + trader.mAccount.GetCompany(); - } - - // - collector = new XCXCAEADataCollector(); - collector.Path(_path); - } - - // - // De Constructors ... - ~XCXCAEATradeManager() - { - // - Clean(trades); - - // - timeTracker.Clean(); - - // - ZeroMemory(trader); - ZeroMemory(drawer); - ZeroMemory(collector); - } - - // - // Properties ... - - // - bool SaveTrades() - { - return mSaveTrades; - } - - // - void SaveTrades(bool value) - { - mSaveTrades = value; - } - - // - void SetForceCloseTradesAt( - string _forceCloseAt // - ) - { - forceCloseAt = _forceCloseAt; - } - - // - void SetTradeSession( - string symbol, - string start, - string end, - string name = NULL // - ) - { - // - // Validate Args ... - bool has = IsValid(end) && - IsValid(start) && - IsValid(symbol); - if (!has) - { - return; - } - - // - // Create Session ... - - // - XCAEATradeSession session; - - // - session.end = end; - session.name = name; - session.start = start; - - // - int sessionIDX = -1; - has = FindSymbolSession( - sessionIDX, - symbol // - ); - - // - if (!has) - { - // - // Add New Symbol Session ... - - // - XCAEASymbolSession iSymbolSession; - iSymbolSession.symbol = symbol; - - // - AddTradingSession( - session, - iSymbolSession // - ); - - // - AddRef( - iSymbolSession, - sessions // - ); - - // - iSymbolSession.Clean(); - } - else - { - // - // Update Trading Sessions of Exists Symbol Session ... - AddTradingSession( - session, - sessions[sessionIDX] // - ); - } - - // - // Cleanup Resources ... - session.Clean(); - } - - // - void SetTradeReports( - bool _reportTrades, - bool _reportSignals, - bool _reportProtector, - bool _reportAfterTradesBalance // - ) - { - // - reportTrades = _reportTrades; - reportSignals = _reportSignals; - reportProtector = _reportProtector; - reportAfterTradesBalance = _reportAfterTradesBalance; - } - - // - void SetTradePermissions( - bool _allowTrade, - bool _allowLongs, - bool _allowShorts // - ) - { - // - allowTrade = _allowTrade; - allowLongs = _allowLongs; - allowShorts = _allowShorts; - } - - // - void SetTradeRestrictions( - ENUM_XCAEA_TRADE_RESTRICTION_PERIOD _period, - int _maxAllowedTPs, - int _maxAllowedSLs, - int _maxAllowedTrades // - ) - { - // - // Normalizing Args ... - _maxAllowedTPs = NormalizeInt(_maxAllowedTPs, 0); - _maxAllowedSLs = NormalizeInt(_maxAllowedSLs, 0); - _maxAllowedTrades = NormalizeInt(_maxAllowedTrades, 0); - - // - restrictionsPeriod = _period; - maxAllowedTPs = _maxAllowedTPs; - maxAllowedSLs = _maxAllowedSLs; - maxAllowedTrades = _maxAllowedTrades; - } - - // - // Tools ... - - /** - * Do All Position Managing Senaros ... - */ - void Manage() - { - // - // Handle Restrictions ... - HandleRestrictions(); - - // - // Check Contains Trades for Managing ... - bool has = HasChild(trades); - if (!has) - { - return; - } - - // - // Update Required Infos of Trades ... - int count = ArraySize(trades); - for (int i = 0; i < count; i++) - { - // - has = trades[i].IsExecuted() && - !trades[i].IsFinalized(); - if (!has) - { - continue; - } - - // - XPosition iPosition; - has = trader.GetPosition( - trades[i].positionID, - iPosition // - ); - if (!has) - { - continue; - } - - // - // Update Trade Data ... - trades[i].swap = iPosition.swap; - trades[i].profit = iPosition.profit; - } - - // - // Do Trade Protection ... - Protect(); - } - - /** - * Do All Position Protection Here ... - */ - void Protect() - { - // - string prefix = "Protector: "; - int targetDistance = 5; - - // - bool has = HasChild(trades); - if (!has) - { - return; - } - - // - XPosition ownPosition[]; - XPosition ownLongPosition[]; - XPosition ownShortPosition[]; - - // - int count = ArraySize(trades); - for (int i = 0; i < count; i++) - { - // - has = - trades[i].IsExecuted() && - !trades[i].IsFinalized(); - if (!has) - { - continue; - } - - // - XPosition iPosition; - has = trader.GetPosition( - trades[i].positionID, - iPosition // - ); - if (!has) - { - continue; - } - - // - AddRef( - iPosition, - ownPosition // - ); - - // - if (IsLong(iPosition.type)) - { - // - AddRef( - iPosition, - ownLongPosition // - ); - } - else - { - // - AddRef( - iPosition, - ownShortPosition // - ); - } - } - - // - has = HasChild(ownPosition); - if (!has) - { - // - Clean(ownPosition); - Clean(ownLongPosition); - Clean(ownShortPosition); - - // - return; - } - - // - double swapSum = 0; - double profitSum = 0; - double commissionSum = 0; - - // - // Calculate Required Data On Collection ... - count = ArraySize(ownPosition); - for (int i = 0; i < count; i++) - { - // - XPosition iPosition = ownPosition[i]; - - // - swapSum += iPosition.swap; - profitSum += iPosition.profit; - commissionSum += iPosition.commission; - } - - // - // Do Collection Protectiong ... - - // - // Check Force Close ... - if (IsValid(forceCloseAt)) - { - // - datetime forceCloseTime = ParseDateTimeFromTimeString(forceCloseAt); - bool canForceClose = IsTimeInRange( - TimeCurrent(), - forceCloseTime // - ) && - !isForceCloseAtTime; - if (canForceClose) - { - // - isForceCloseAtTime = HandleForceCloseTrades(ownPosition); - - // - // Prevent Moving Forward ... - return; - } - } - - // - // Do Signle Protections ... - for (int i = 0; i < count; i++) - { - // - // Select Position ... - XPosition iPosition = ownPosition[i]; - int idx = -1; - has = HasTrade( - idx, - iPosition.ticket // - ); - if (!has) - { - continue; - } - - // - bool isLong = IsLong(iPosition.type); - double points = GetPoints(iPosition.symbol); - - // - // Handle RF On Targets ... - if (iPosition.profit > 0) - { - // - // Handle Risk Free On Targets ... - XTarget targets[]; - Copy( - trades[idx].signal.targets, - targets // - ); - int targetsCount = ArraySize(targets); - has = IsValidSize(targetsCount); - if (has) - { - // - for (int j = 0; j < targetsCount; j++) - { - // - XTarget jTarget = targets[j]; - - // - int appliedTargetIDX = -1; - - // - // Check Target is Applied Before or Not ... - has = - !trades[idx].signal.isTargetApplied - ? true - : trades[idx].signal.appliedTargetIDX < j; - if (!has) - { - continue; - } - - // - // Check Traget Validation ... - has = - iPosition.sl == 0 - ? true - : isLong - ? iPosition.sl < jTarget.target - : iPosition.sl > jTarget.target; - if (!has) - { - continue; - } - - // - double targetDelta = isLong - ? jTarget.target + (targetDistance * points) - : jTarget.target - (targetDistance * points); - - // - // Can Risk Free ... - bool canRF = - jTarget.doRF && - jTarget.target > 0 && - (isLong - ? jTarget.target > iPosition.entry - : jTarget.target < iPosition.entry) && - (isLong - ? iPosition.price > targetDelta - : iPosition.price < targetDelta); - - // - // Can Partial Close ... - bool canPC = - jTarget.volumeMultiplier > 0 && - jTarget.target > 0 && - (isLong - ? jTarget.target > iPosition.entry - : jTarget.target < iPosition.entry) && - (isLong - ? iPosition.price > targetDelta - : iPosition.price < targetDelta); - bool canRFPC = canRF || - canPC; - if (canRFPC) - { - // - // Handle Risk Free ... - bool isRFDone = false; - if (canRF) - { - // - double tp = iPosition.tp; - double sl = jTarget.target; - string comment = "RF On Target ..."; - isRFDone = trader.Modify( - iPosition.ticket, - sl, - tp, - comment // - ); - } - - // - // Handle Partail Close ... - bool isPCDone = false; - if (canPC) - { - // - double volume = jTarget.volumeMultiplier * iPosition.volume; - volume = NormalizeVolume(volume, iPosition.symbol); - string comment = "RF On Target ..."; - isPCDone = trader.ClosePartial( - iPosition.ticket, - volume, - comment // - ); - } - - // - // Handle Report Action ... - bool isRFPCDone = isRFDone || - isPCDone; - if (isRFPCDone) - { - // - trades[idx].signal.appliedTargetIDX = j; - trades[idx].signal.isTargetApplied = true; - - // - string message = prefix + - ToString(iPosition.type) + - " Position: " + - ToString(iPosition.ticket) + - (isRFDone ? " RF" : "") + - (isPCDone ? " PC" : "") + - " On Traget: " + ToString(jTarget.target) + - " Successfully ..."; - HandleReportProtector(message); - } - } - } - } - } - } - } - - /** - * Check Signal Execution Conditions ... - * - * @param signal: XSignal instance reference ... - * @param executionResult: ENUM_X_SIGNAL_EXECUTION_RESULT member reference ... - * - * @return ( bool ) - */ - bool CheckSignal( - XSignal &signal, - ENUM_X_SIGNAL_EXECUTION_RESULT &executionResult // - ) - { - // - bool result = false; - - // - // Cleanup ... - executionResult = X_SIGNAL_EXECUTION_UNKNOWN; - - // - // Validate Signal ... - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - // Reporting Signal ... - if (reportSignals) - { - // - string message = signal.GetMessage("Provided"); - SendAlert(message); - } - - // - // Check Trade Permission ... - if (!allowTrade) - { - // - result = false; - executionResult = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; - - // - return result; - } - - // - bool isLong = IsLong(signal.type); - bool isShort = IsShort(signal.type); - - // - bool isLongAndAllowed = - isLong && - allowLongs; - - // - bool isShortAndAllowed = - isShort && - allowShorts; - - // - result = isLongAndAllowed || - isShortAndAllowed; - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; - - // - return result; - } - - // - // Check Symbol Info Exists or not ... - int symbolInfoIDX = -1; - bool isSymbolInfoExists = FindSymbolIndex( - symbolInfoIDX, - signal.symbol // - ); - - // - // Check Symbol Session Exists or not ... - int symbolSessionIDX = -1; - bool isSymbolSessionExists = FindSymbolSession( - symbolSessionIDX, - signal.symbol // - ); - - // - // Chack Trade Session Validating ... - if (isSymbolSessionExists) - { - // - result = sessions[symbolSessionIDX].CanTrade(); - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED; - - // - return result; - } - } - - // - // Check Trade Permissions Based on SL(s) Count ... - bool hasRestrictions = restrictionsPeriod != XCAEA_TRADE_RESTRICATION_NONE; - if (hasRestrictions) - { - // - // Only Can Check Restrictions when - // Symbol Info Exists ... - if (isSymbolInfoExists) - { - // - bool isTPAllowed = maxAllowedTPs == 0 - ? true - : symbols[symbolInfoIDX].managedTPs < maxAllowedTPs; - bool isSLAllowed = maxAllowedSLs == 0 - ? true - : symbols[symbolInfoIDX].managedSLs < maxAllowedSLs; - bool isTradeAllowed = maxAllowedTrades == 0 - ? true - : symbols[symbolInfoIDX].managedTrades < maxAllowedTrades; - - // - result = isTPAllowed && - isSLAllowed && - isTradeAllowed; - } - - // - // Report Error ... - if (!result) - { - // - executionResult = X_SIGNAL_EXECUTION_FAILED_MAX_REACHED; - - // - return result; - } - } - - // - return result; - } - - /** - * Execute Specified Signal ... - * - * @param signal: XSignal instance reference ... - * @param conditions: XCAEAStrategyConditions instance reference ... - * - * @return ( bool ) - */ - bool Execute( - XSignal &signal, - XCAEAStrategyConditions &conditions // - ) - { - // - bool result = false; - - // - result = signal.IsValid(); - if (!result) - { - return result; - } - - // - int idx = -1; - bool isExists = HasTrade( - idx, - signal // - ); - result = !isExists; - if (!result) - { - return result; - } - - // - ENUM_X_SIGNAL_EXECUTION_RESULT executionResult; - - // - // Checking Signal For Execution ... - result = CheckSignal( - signal, - executionResult // - ); - if (result) - { - // - result = trader.ExecuteSignal( - signal, - executionResult // - ); - } - - // - // Alert Signal Execution ... - if (reportTrades) - { - // - string executionMessage = ToString(executionResult); - - // - string message = NULL; - if (result) - { - message = signal.GetMessage("Executed"); - } - else - { - message = signal.GetMessage("Failed due (" + executionMessage + ")"); - } - - // - SendAlert(message); - } - - // - if (result) - { - // - // Draw Signal ... - if (drawSignal) - { - // - XCSignalObject *iObj; - isExists = drawer.DrawSignal( - signal, - iObj // - ); - - // - if (isExists) - { - // - mObjects.Add(iObj); - ZeroMemory(iObj); - } - } - - // - // Create Symbol Info Struct ... - XCAEASymbolInfo iSymbolInfo; - - // - iSymbolInfo.trades = 1; - iSymbolInfo.managedTrades = 1; - iSymbolInfo.symbol = signal.symbol; - - // - bool isLong = IsLong(signal.type); - if (isLong) - { - iSymbolInfo.longs = 1; - } - else - { - iSymbolInfo.shorts = 1; - } - - // - AddOrUpdateSymbolInfo(iSymbolInfo); - - // - // Create Trade Struct ... - XCAEATrade iTrade; - - // - ulong positionID = trader.GetLastOpenPositionTicket(); - double commission = trader.GetPositionCommission(positionID); - - // - iTrade.signal = signal; - iTrade.conditions = conditions; - iTrade.positionID = positionID; - iTrade.commission = commission; - iTrade.signaledAt = signal.time; - iTrade.executedAt = TimeCurrent(); - - // - AddRef( - iTrade, - trades // - ); - } - - // - return result; - } - - /** - * Handle Position Take Profit ... - * - * @param deal: XDeal instance reference ... - */ - void HandleTP(const XDeal &deal) - { - // - // Check Ticket Exists or not ... - int idx = -1; - bool isExists = HasTrade( - idx, - deal.positionId // - ); - if (!isExists) - { - return; - } - - // - // Apply Required Data ... - trades[idx].swap = deal.swap; - trades[idx].profit = deal.profit; - trades[idx].finalizedAt = TimeCurrent(); - trades[idx].finalize = XCAEA_TRADE_FINAL_TP; - - // - // Save Trade ... - Save(trades[idx]); - - // - // Handle Balance Reporting ... - string prefix = "TP: " + ToString(trades[idx].profit); - HandleReportBalance(prefix); - - // - // Handle Symbol Info ... - - // - XCAEASymbolInfo iSymbolInfo; - - // - iSymbolInfo.profits = 1; - iSymbolInfo.managedTPs = 1; - iSymbolInfo.symbol = trades[idx].signal.symbol; - - // - AddOrUpdateSymbolInfo(iSymbolInfo); - - // - RemoveTrade(idx); - } - - /** - * Handle Position Stop Loss ... - * - * @param deal: XDeal instance reference ... - */ - void HandleSL(const XDeal &deal) - { - // - // Check Ticket Exists or not ... - int idx = -1; - bool isExists = HasTrade( - idx, - deal.positionId // - ); - if (!isExists) - { - return; - } - - // - // Apply Required Data ... - trades[idx].swap = deal.swap; - trades[idx].profit = deal.profit; - trades[idx].finalizedAt = TimeCurrent(); - trades[idx].finalize = XCAEA_TRADE_FINAL_SL; - - // - // Save Trade ... - Save(trades[idx]); - - // - // Handle Balance Reporting ... - string prefix = "SL: " + ToString(trades[idx].profit); - HandleReportBalance(prefix); - - // - // Handle Symbol Info ... - - // - bool isInProfit = trades[idx].profit > 0; - - // - XCAEASymbolInfo iSymbolInfo; - - // - if (isInProfit) - { - // - iSymbolInfo.profits = 1; - iSymbolInfo.managedTPs = 1; - } - else - { - // - iSymbolInfo.losses = 1; - iSymbolInfo.managedSLs = 1; - } - iSymbolInfo.symbol = trades[idx].signal.symbol; - - // - AddOrUpdateSymbolInfo(iSymbolInfo); - - // - RemoveTrade(idx); - } - - /** - * Handle Position Force Close ... - * - * @param deal: XDeal instance reference ... - */ - void HandleForceClose(const XPosition &position) - { - // - // Check Ticket Exists or not ... - int idx = -1; - bool isExists = HasTrade( - idx, - position.ticket // - ); - if (!isExists) - { - return; - } - - // - bool isInProfit = position.profit > 0; - - // - // Apply Required Data ... - trades[idx].swap = position.swap; - trades[idx].profit = position.profit; - trades[idx].finalizedAt = TimeCurrent(); - trades[idx].commission = position.commission; - trades[idx].finalize = isInProfit - ? XCAEA_TRADE_FINAL_CLOSE_IN_PROFIT - : XCAEA_TRADE_FINAL_CLOSE_IN_LOSE; - - // - // Save Trade ... - Save(trades[idx]); - - // - // Handle Balance Reporting ... - string prefix = "Force Close " + - (isInProfit - ? "Profit" - : "Loss") + - ": " + - ToString(trades[idx].profit); - HandleReportBalance(prefix); - - // - // Handle Symbol Info ... - - // - XCAEASymbolInfo iSymbolInfo; - - // - if (isInProfit) - { - // - iSymbolInfo.profits = 1; - iSymbolInfo.managedTPs = 1; - } - else - { - // - iSymbolInfo.losses = 1; - iSymbolInfo.managedSLs = 1; - } - iSymbolInfo.symbol = trades[idx].signal.symbol; - - // - AddOrUpdateSymbolInfo(iSymbolInfo); - - // - RemoveTrade(idx); - } - - /** - * Handle Position Partially Closed Event ... - * - * @param ticket: ULONG ... - * @param profit: double ... - * @param comment: string ... - */ - void HandlePartiallyClosed( - const ulong ticket, - const double profit, - const string comment // - ) - { - // - // Handle Balance Reporting ... - string prefix = "Partially Closed: " + ToString(ticket); - - // - // Handle Balance Reporting ... - HandleReportBalance(prefix); - } - - /** - * Handle Force Close Trades ... - */ - bool HandleForceCloseTrades( - XPosition &positions[] // - ) - { - // - bool result = false; - - // - result = HasChild(positions); - if (!result) - { - return result; - } - - // - string prefix = "Protector: "; - string comment = "Force Close ..."; - - // - int closedsCount = trader.Close( - positions, - comment // - ); - result = IsValidSize(closedsCount); - if (result) - { - // - string message = prefix + "Force Close (" + ToString(closedsCount) + ") Trades at Specified Time ..."; - HandleReportProtector(message); - } - - // - return result; - } - - // - // TODO: Complete this ... - void HandleGuard() - { - } - - /** - * Find Executed Trade by Providing Position Ticket ... - * - * @param index: int reference, holding founded item index ... - * @param ticket: ulong, Specified Position Ticket ... - * - * @return ( bool ) - */ - bool HasTrade( - int &index, - ulong ticket // - ) - { - // - bool result = false; - - // - index = -1; - - // - result = - ticket > 0 && - HasChild(trades); - if (!result) - { - return result; - } - - // - int count = ArraySize(trades); - for (int i = 0; i < count; i++) - { - // - XCAEATrade iTrade = trades[i]; - - // - result = - iTrade.HasSignal() && - iTrade.IsExecuted() && - iTrade.positionID == ticket; - if (result) - { - // - index = i; - - // - iTrade.Clean(); - break; - } - - // - iTrade.Clean(); - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Find Trade Item By Signal ... - * - * @param index: int reference, holding founded item index ... - * - * @return ( bool ) - */ - bool HasTrade( - int &index, - XSignal &signal // - ) - { - // - bool result = false; - - // - index = -1; - - // - result = - signal.IsValid() && - HasChild(trades); - if (!result) - { - return result; - } - - // - int count = ArraySize(trades); - for (int i = 0; i < count; i++) - { - // - XCAEATrade iTrade = trades[i]; - - // - result = - iTrade.HasSignal() && - iTrade.signal.IsSameAs(signal); - if (result) - { - // - index = i; - - // - iTrade.Clean(); - break; - } - - // - iTrade.Clean(); - } - - // - result = IsValidIndex(index); - - // - return result; - } - - /** - * Remove a Trade From List ... - * - * @param index: int ... - */ - void RemoveTrade(int index) - { - // - bool has = - HasChild(trades) && - IsValidIndex(index) && - index < ArraySize(trades); - if (!has) - { - return; - } - - // - ArrayRemove( - trades, - index, - 1 // - ); - } - - // - // Protected ... - protected: - // - // Tools ... - - // - string GetFilePath(XCAEATrade &trade) - { - // - string fileName = trade.GetFileName(); - - // - return GetFilePath(fileName); - } - - // - string GetFilePath(string fileName) - { - // - string result = NULL; - - // - string mPath = collector.Path(); - - // - result = - // - mPath + "\\" + "Trades" + "\\" + fileName + ".x121.log" - // - ; - - // - return result; - } - - // - void HandleReportBalance(string prefix = NULL) - { - // - if (!reportAfterTradesBalance) - { - return; - } - - // - double balance = trader.mAccount.GetBalance(); - string currency = trader.mAccount.GetCurrency(); - - // - string message = - (IsValid(prefix) - ? prefix + "\n" - : "") + - "Account Balance: " + ToString(balance) + currency; - SendAlert(message); - } - - // - void HandleReportProtector(string message = NULL) - { - // - if (!reportProtector) - { - return; - } - - // - SendAlert(message); - } - - // - bool Save( - XCAEATrade &trade, - bool includeSummary = true, - bool includeSignal = true, - bool includeConditions = true // - ) - { - // - bool result = false; - - // - if (!mSaveTrades) - { - return result; - } - - // - string filePath = GetFilePath(trade); - result = IsValid(filePath); - if (!result) - { - return result; - } - - // - string content = trade.ToString( - includeSummary, - includeSignal, - includeConditions // - ); - - // - result = collector.Save( - filePath, - content // - ); - - // - return result; - } - - // - // Symbol Info ... - - // - bool FindSymbolIndex( - int &index, - XCAEASymbolInfo &item // - ) - { - // - bool result = false; - - // - index = -1; - - // - result = item.IsValid(); - if (!result) - { - return result; - } - - // - result = HasChild(symbols); - if (!result) - { - return result; - } - - // - index = FindIndex( - item, - symbols // - ); - - // - result = IsValidIndex(index); - - // - return result; - } - - // - bool FindSymbolIndex( - int &index, - string symbol // - ) - { - // - bool result = false; - - // - index = -1; - - // - result = IsValid(symbol) && - HasChild(symbols); - if (!result) - { - return result; - } - - // - int count = ArraySize(symbols); - for (int i = 0; i < count; i++) - { - // - result = symbols[i].symbol == symbol; - if (result) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - // - void AddOrUpdateSymbolInfo(XCAEASymbolInfo &item) - { - // - bool has = item.IsValid(); - if (!has) - { - return; - } - - // - int index = -1; - bool isExists = FindSymbolIndex( - index, - item // - ); - if (!isExists) - { - // - AddRef( - item, - symbols // - ); - } - else - { - // - symbols[index].longs += item.longs; - symbols[index].shorts += item.shorts; - symbols[index].trades += item.trades; - symbols[index].losses += item.losses; - symbols[index].profits += item.profits; - symbols[index].managedSLs += item.managedSLs; - symbols[index].managedTPs += item.managedTPs; - symbols[index].managedTrades += item.managedTrades; - } - } - - // - void ResetSymbolsRestrictions() - { - // - bool has = HasChild(symbols); - if (has) - { - // - string prefix = "Protector: "; - - // - int count = ArraySize(symbols); - for (int i = 0; i < count; i++) - { - // - symbols[i].managedSLs = 0; - symbols[i].managedTPs = 0; - symbols[i].managedTrades = 0; - } - - // - string message = prefix + "Reset Symbols Restrictions"; - HandleReportProtector(message); - } - } - - // - void HandleRestrictions() - { - // - bool isNewDay = timeTracker.IsNewDay(); - bool isNewHour = timeTracker.IsNewHour(); - bool isNewWeek = timeTracker.IsNewWeek(); - bool isNewMonth = timeTracker.IsNewMonth(); - - // - // Reset Force Closed Flag on new Day Starts ... - if (isNewDay) - { - isForceCloseAtTime = false; - } - - // - bool canResetRestrictions = - ( - // - // Hourly ... - (isNewHour && - restrictionsPeriod == XCAEA_TRADE_RESTRICATION_HOURLY) - // - || - // - // Daily ... - (isNewDay && - restrictionsPeriod == XCAEA_TRADE_RESTRICATION_DAILY) - // - || - // - // Weekly ... - (isNewWeek && - restrictionsPeriod == XCAEA_TRADE_RESTRICATION_WEEKLY) - // - || - // - // Monthly ... - (isNewMonth && - restrictionsPeriod == XCAEA_TRADE_RESTRICATION_MONTHLY) - // - ) - // - ; - if (canResetRestrictions) - { - ResetSymbolsRestrictions(); - } - } - - // - // Symbol Session ... - - // - bool FindSymbolSession( - int &index, - string symbol // - ) - { - // - bool result = false; - - // - index = -1; - - // - result = IsValid(symbol) && - HasChild(sessions); - if (!result) - { - return result; - } - - // - int count = ArraySize(sessions); - for (int i = 0; i < count; i++) - { - // - result = sessions[i].symbol == symbol; - if (result) - { - // - index = i; - break; - } - } - - // - result = IsValidIndex(index); - - // - return result; - } - - // - void AddTradingSession( - XCAEATradeSession &session, - XCAEASymbolSession &symbolSession // - ) - { - // - bool has = session.IsValid() && - symbolSession.IsValid(); - if (!has) - { - return; - } - - // - // Check Session Exists in Symbol Session ... - bool isExists = false; - if (HasChild(symbolSession.sessions)) - { - // - int count = ArraySize(symbolSession.sessions); - for (int i = 0; i < count; i++) - { - // - isExists = symbolSession.sessions[i].end == session.end && - symbolSession.sessions[i].start == session.start; - if (isExists) - { - break; - } - } - } - - // - if (!isExists) - { - // - AddRef( - session, - symbolSession.sessions // - ); - } - } - - // - // Private ... - private: - // - // Props ... - - // - bool allowTrade; - bool allowLongs; - bool allowShorts; - - // - string forceCloseAt; - bool isForceCloseAtTime; - - // - int maxAllowedTPs; - int maxAllowedSLs; - int maxAllowedTrades; - ENUM_XCAEA_TRADE_RESTRICTION_PERIOD restrictionsPeriod; - - // - bool mSaveTrades; - - // - bool reportTrades; - bool reportSignals; - bool reportProtector; - bool reportAfterTradesBalance; - - // - CArrayObj mObjects; - - // - XCAEATrade trades[]; - XCAEASymbolInfo symbols[]; - XCAEASymbolSession sessions[]; -}; - -// diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Helpers/xcaea.helper.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Helpers/xcaea.helper.mq5 deleted file mode 100644 index b5f44c00..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Helpers/xcaea.helper.mq5 +++ /dev/null @@ -1,4822 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XCXCAEAHelper -// Description: provides all Indicator -// Helper requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../../Classes/x-saherelm.x-poi.class.mq5" -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../../Helpers/x-saherelm.x121.x3ma.helper.mq5" -#include "../../Helpers/x-saherelm.x121.xca.helper.mq5" -#include "../../Helpers/x-saherelm.x121.xcc.helper.mq5" -#include "../../Helpers/x-saherelm.x121.xct.helper.mq5" -#include "../../Helpers/x-saherelm.x121.xoscs.helper.mq5" - -// -// Input Structure ... -struct XCAEAInputs -{ - // - bool showAC; - bool showAD; - bool showADX; - bool showATR; - bool showCCI; - bool showRSI; - bool showMFI; - bool showRVI; - bool showMACD; - bool showMomentum; - bool showStochastic; - - // - X121XCTInputs ctInputs; - X121XCCInputs ccInputs; - X121XCAInputs caInputs; - X121X3MAInputs x3maInputs; - X121XOCSInputs oscsInputs; - - // - // Constructor ... - XCAEAInputs() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - showAC = false; - showAD = false; - showADX = false; - showATR = false; - showCCI = false; - showRSI = false; - showMFI = false; - showRVI = false; - showMACD = false; - showMomentum = false; - showStochastic = false; - - // - ctInputs.Clean(); - ccInputs.Clean(); - caInputs.Clean(); - x3maInputs.Clean(); - oscsInputs.Clean(); - - // - ZeroMemory(this); - } - - /** - * Set Default Values ... - */ - void Default() - { - // - ctInputs.Default(); - ccInputs.Default(); - caInputs.Default(); - x3maInputs.Default(); - oscsInputs.Default(); - } - - /** - * Hide all Visibles ... - */ - void Hide() - { - // - ctInputs.Hide(); - caInputs.Hide(); - x3maInputs.Hide(); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - // - ctInputs.IsValid() && - ccInputs.IsValid() && - caInputs.IsValid() && - x3maInputs.IsValid() && - oscsInputs.IsValid() - // - ; - - // - return result; - } - - /** - * Extract Max Input Length ... - * - * @return ( int ) - */ - int Max() - { - // - int result = 0; - - // - int ctMax = ctInputs.Max(); - int ccMax = ccInputs.Max(); - int caMax = caInputs.Max(); - int ocsMax = oscsInputs.Max(); - int x3maMax = x3maInputs.Max(); - - // - result = MathMax(ctMax, ccMax); - result = MathMax(result, caMax); - result = MathMax(result, ocsMax); - result = MathMax(result, x3maMax); - - // - return result; - } -}; - -// -// Conditions Structure ... -struct XCAEAConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - datetime to; - datetime from; - - // - // Bars ... - XOHCL bars[]; - double bodies[]; - double ranges[]; - double velocities[]; - double scoreBullish; - double scoreBearish; - double volumeBullish; - double volumeBearish; - double priceChangeRate; - bool bullishEngulfedBars[]; - bool bearishEngulfedBars[]; - bool bullishRejectedBars[]; - bool bearishRejectedBars[]; - - // - // X3MA ... - - // - // Buffers ... - - // - double fastBuffer[]; - double mediumBuffer[]; - double slowBuffer[]; - double fastStateBuffer[]; - double mediumStateBuffer[]; - double slowStateBuffer[]; - - // - // Conditions ... - - // - bool isFastOverMedium; - bool isFastUnderMedium; - - // - bool isFastCrossedOverMedium; - bool isFastCrossedUnderMedium; - - // - bool isFastOverSlow; - bool isFastUnderSlow; - - // - bool isFastCrossedOverSlow; - bool isFastCrossedUnderSlow; - - // - bool isMediumOverSlow; - bool isMediumUnderSlow; - - // - bool isMediumCrossedOverSlow; - bool isMediumCrossedUnderSlow; - - // - bool is3MaBullishOrdered; - bool is3MaBearishOrdered; - - // - bool is3MaSwitchedToBullishOrdered; - bool is3MaSwitchedToBearishOrdered; - - // - bool is3MaBullishState; - bool is3MaBearishState; - - // - bool is3MaSwitchedToBullishState; - bool is3MaSwitchedToBearishState; - - // - bool is3MaBullish; - bool is3MaBearish; - - // - bool is3MaSwitchedToBullish; - bool is3MaSwitchedToBearish; - - // - bool is3MaFinishedFromBullish; - bool is3MaFinishedFromBearish; - - // - // XCA ... - - // - // Buffers ... - - // - double kiBuffer[]; - double tkiBuffer[]; - double sHHBuffer[]; - double sLLBuffer[]; - double mHHBuffer[]; - double mLLBuffer[]; - double lHHBuffer[]; - double lLLBuffer[]; - double hHHBuffer[]; - double hLLBuffer[]; - double sarBuffer[]; - double mahBuffer[]; - double malBuffer[]; - double macBuffer[]; - double peakBuffer[]; - double valeBuffer[]; - double vidyaBuffer[]; - double trendBuffer[]; - double kiStateBuffer[]; - double supportBuffer[]; - double tkiStateBuffer[]; - double swingLowBuffer[]; - double swingHighBuffer[]; - double vidyaStateBuffer[]; - double resistanceBuffer[]; - double peakGoldenBuffer[]; - double valeGoldenBuffer[]; - double fiboLevel1Buffer[]; - double fiboLevel2Buffer[]; - double fiboLevel3Buffer[]; - double fiboLevel4Buffer[]; - double fiboLevel5Buffer[]; - double trendStateBuffer[]; - - // - // Conditions ... - - // - // KI ... - - // - bool isKIRejectUp; - bool isKIRejectDown; - - // - bool isKIBullish; - bool isKIBearish; - - // - bool isKISwitchedToBullish; - bool isKISwitchedToBearish; - - // - bool isKIFinishedFromBullish; - bool isKIFinishedFromBearish; - - // - // TKI ... - - // - bool isTKIRejectUp; - bool isTKIRejectDown; - - // - bool isTKIBullish; - bool isTKIBearish; - - // - bool isTKISwitchedToBullish; - bool isTKISwitchedToBearish; - - // - bool isTKIFinishedFromBullish; - bool isTKIFinishedFromBearish; - - // - // VIDYA ... - - // - bool isVidyaRejectUp; - bool isVidyaRejectDown; - - // - bool isVidyaBullish; - bool isVidyaBearish; - - // - bool isVidyaSwitchedToBullish; - bool isVidyaSwitchedToBearish; - - // - bool isVidyaFinishedFromBullish; - bool isVidyaFinishedFromBearish; - - // - // SAR ... - - // - bool isSarBullish; - bool isSarBearish; - - // - bool isSarSwitchedToBullish; - bool isSarSwitchedToBearish; - - // - bool isSarFinishedFromBullish; - bool isSarFinishedFromBearish; - - // - // MANALYSER ... - - // - // MAH ... - - // - bool isOverMah; - bool isUnderMah; - bool isCrossedOverMah; - bool isCrossedUnderMah; - - // - bool isCloseOverMah; - bool isCloseUnderMah; - bool isCloseCrossedOverMah; - bool isCloseCrossedUnderMah; - - // - bool isMahBullishRejected; - bool isMahBearishRejected; - - // - // MAL ... - - // - bool isOverMal; - bool isUnderMal; - bool isCrossedOverMal; - bool isCrossedUnderMal; - - // - bool isCloseOverMal; - bool isCloseUnderMal; - bool isCloseCrossedOverMal; - bool isCloseCrossedUnderMal; - - // - bool isMalBullishRejected; - bool isMalBearishRejected; - - // - // MAC ... - - // - bool isOverMac; - bool isUnderMac; - bool isCrossedOverMac; - bool isCrossedUnderMac; - - // - bool isCloseOverMac; - bool isCloseUnderMac; - bool isCloseCrossedOverMac; - bool isCloseCrossedUnderMac; - - // - bool isMacBullishRejected; - bool isMacBearishRejected; - - // - // PEAK ... - - // - bool isPeakSameLast; - bool isPeakOverLast; - bool isPeakUnderLast; - - // - // VALE ... - - // - bool isValeSameLast; - bool isValeOverLast; - bool isValeUnderLast; - - // - // TREND ... - - // - bool isTrendRejectUp; - bool isTrendRejectDown; - - // - bool isTrendBullish; - bool isTrendBearish; - - // - bool isTrendSwitchedToBullish; - bool isTrendSwitchedToBearish; - - // - bool isTrendFinishedFromBullish; - bool isTrendFinishedFromBearish; - - // - // SUPPORT ... - - // - bool isSupportSameLast; - bool isSupportOverLast; - bool isSupportUnderLast; - - // - bool isLastSupportBreaked; - bool isLastSupportRejected; - - // - // RESISTANCE ... - - // - bool isResistanceSameLast; - bool isResistanceOverLast; - bool isResistanceUnderLast; - - // - bool isLastResistanceBreaked; - bool isLastResistanceRejected; - - // - // SWING Low ... - - // - bool isSwingLowSameLast; - bool isSwingLowOverLast; - bool isSwingLowUnderLast; - - // - bool isLastSwingLowBreaked; - bool isLastSwingLowRejected; - - // - // SWING High ... - - // - bool isSwingHighSameLast; - bool isSwingHighOverLast; - bool isSwingHighUnderLast; - - // - bool isLastSwingHighBreaked; - bool isLastSwingHighRejected; - - // - // COMPLEX Conditions ... - - // - bool isPeakIsPivot; - bool isValeIsPivot; - - // - bool isPeakSwitchedToPivot; - bool isValeSwitchedToPivot; - - // - bool isPeakFinishedFromPivot; - bool isValeFinishedFromPivot; - - // - bool isSwingLowSameAsVale; - bool isSwingHighSameAsPeak; - - // - bool isSupportSameAsVale; - bool isResistanceSameAsPeak; - - // - bool isSupportSameAsSwingLow; - bool isResistanceSameAsSwingHigh; - - // - // XOSCS ... - - // - // Buffers ... - - // - double acBuffer[]; - double adBuffer[]; - double atrBuffer[]; - double cciBuffer[]; - double rsiBuffer[]; - double mfiBuffer[]; - double rviBuffer[]; - double adxBuffer[]; - double adxpBuffer[]; - double adxnBuffer[]; - double macdBuffer[]; - double momentumBuffer[]; - double rviSignalBuffer[]; - double macdSignalBuffer[]; - double stochasticBuffer[]; - double stochasticSignalBuffer[]; - - // - // Values ... - - // - double adxThreshold; - double cciOBLevel; - double cciOSLevel; - double cciReversalLevel; - double rsiOBLevel; - double rsiOSLevel; - double rsiReversalLevel; - double mfiOBLevel; - double mfiOSLevel; - double mfiReversalLevel; - double rviBullishLevel; - double rviBearishLevel; - double macdBullishLevel; - double macdBearishLevel; - double momentumBullishLevel; - double momentumBearishLevel; - double stochasticOBLevel; - double stochasticOSLevel; - double stochasticReversalLevel; - - // - // Conditions ... - - // - // AC ... - - // - bool isACBullish; - bool isACBearish; - - // - bool isACSwitchedToBullish; - bool isACSwitchedToBearish; - - // - bool isACOverMax; - bool isACUnderMin; - - // - // AD ... - - // - bool isADBiggerLast; - bool isADLesserLast; - - // - bool isADOverMax; - bool isADUnderMin; - - // - // ADX ... - - // - bool isADXBiggerLast; - bool isADXLesserLast; - - // - bool isADXOverThreshold; - bool isADXUnderThreshold; - - // - bool isDXPBiggerThanDXN; - bool isDXNBiggerThanDXP; - - // - bool isADXBullish; - bool isADXBearish; - - // - bool isADXSwitchedToBullish; - bool isADXSwitchedToBearish; - - // - // ATR ... - - bool isATROverLast; - bool isATRUnderLast; - - // - // CCI ... - - // - bool isCCIBullish; - bool isCCIBearish; - - // - bool isCCISwitchedToBullish; - bool isCCISwitchedToBearish; - - // - bool isCCIOB; - bool isCCIOS; - - // - bool isCCICrossedOverOB; - bool isCCICrossedOverOS; - - // - bool isCCICrossedUnderOB; - bool isCCICrossedUnderOS; - - // - // RSI ... - - // - bool isRSIBullish; - bool isRSIBearish; - - // - bool isRSISwitchedToBullish; - bool isRSISwitchedToBearish; - - // - bool isRSIOB; - bool isRSIOS; - - // - bool isRSICrossedOverOB; - bool isRSICrossedOverOS; - - // - bool isRSICrossedUnderOB; - bool isRSICrossedUnderOS; - - // - // MFI ... - - // - bool isMFIBullish; - bool isMFIBearish; - - // - bool isMFISwitchedToBullish; - bool isMFISwitchedToBearish; - - // - bool isMFIOB; - bool isMFIOS; - - // - bool isMFICrossedOverOB; - bool isMFICrossedOverOS; - - // - bool isMFICrossedUnderOB; - bool isMFICrossedUnderOS; - - // - // RVI ... - - // - bool isRVIBullish; - bool isRVIBearish; - - // - bool isRVISwitchedToBullish; - bool isRVISwitchedToBearish; - - // - bool isRVIOverSignal; - bool isRVIUnderSignal; - - // - bool isRVICrossedOverSignal; - bool isRVICrossedUnderSignal; - - // - // MACD ... - - // - bool isMACDBullish; - bool isMACDBearish; - - // - bool isMACDSwitchedToBullish; - bool isMACDSwitchedToBearish; - - // - bool isMACDOverSignal; - bool isMACDUnderSignal; - - // - bool isMACDCrossedOverSignal; - bool isMACDCrossedUnderSignal; - - // - // MOMENTUM ... - - // - bool isMomentumBullish; - bool isMomentumBearish; - - // - bool isMomentumSwitchedToBullish; - bool isMomentumSwitchedToBearish; - - // - // STOCHASTIC ... - - // - bool isStochasticBullish; - bool isStochasticBearish; - - // - bool isStochasticSwitchedToBullish; - bool isStochasticSwitchedToBearish; - - // - bool isStochasticOverSignal; - bool isStochasticUnderSignal; - - // - bool isStochasticCrossedOverSignal; - bool isStochasticCrossedUnderSignal; - - // - bool isStochasticOB; - bool isStochasticOS; - - // - bool isStochasticCrossedOverOB; - bool isStochasticCrossedOverOS; - - // - bool isStochasticCrossedUnderOB; - bool isStochasticCrossedUnderOS; - - // - // Specified Conditions ... - - // - // Constructor ... - XCAEAConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - // Commons ... - symbol = NULL; - period = NULL; - - // - to = NULL; - from = NULL; - time = NULL; - - // - // Bars ... - Clean(bars); - Clean(bodies); - Clean(ranges); - scoreBullish = 0; - scoreBearish = 0; - volumeBullish = 0; - volumeBearish = 0; - Clean(velocities); - priceChangeRate = 0; - Clean(bullishEngulfedBars); - Clean(bearishEngulfedBars); - Clean(bullishRejectedBars); - Clean(bearishRejectedBars); - ArraySetAsSeries(bars, true); - ArraySetAsSeries(bodies, true); - ArraySetAsSeries(ranges, true); - ArraySetAsSeries(velocities, true); - ArraySetAsSeries(bullishEngulfedBars, true); - ArraySetAsSeries(bearishEngulfedBars, true); - ArraySetAsSeries(bullishRejectedBars, true); - ArraySetAsSeries(bearishRejectedBars, true); - - // - // X3MA ... - - // - // Buffers ... - - // - Clean(fastBuffer); - Clean(mediumBuffer); - Clean(slowBuffer); - Clean(fastStateBuffer); - Clean(mediumStateBuffer); - Clean(slowStateBuffer); - - // - ArraySetAsSeries(fastBuffer, true); - ArraySetAsSeries(mediumBuffer, true); - ArraySetAsSeries(slowBuffer, true); - ArraySetAsSeries(fastStateBuffer, true); - ArraySetAsSeries(mediumStateBuffer, true); - ArraySetAsSeries(slowStateBuffer, true); - - // - // Conditions ... - - // - isFastOverMedium = false; - isFastUnderMedium = false; - - // - isFastCrossedOverMedium = false; - isFastCrossedUnderMedium = false; - - // - isFastOverSlow = false; - isFastUnderSlow = false; - - // - isFastCrossedOverSlow = false; - isFastCrossedUnderSlow = false; - - // - isMediumOverSlow = false; - isMediumUnderSlow = false; - - // - isMediumCrossedOverSlow = false; - isMediumCrossedUnderSlow = false; - - // - is3MaBullishOrdered = false; - is3MaBearishOrdered = false; - - // - is3MaSwitchedToBullishOrdered = false; - is3MaSwitchedToBearishOrdered = false; - - // - is3MaBullishState = false; - is3MaBearishState = false; - - // - is3MaSwitchedToBullishState = false; - is3MaSwitchedToBearishState = false; - - // - is3MaBullish = false; - is3MaBearish = false; - - // - is3MaSwitchedToBullish = false; - is3MaSwitchedToBearish = false; - - // - is3MaFinishedFromBullish = false; - is3MaFinishedFromBearish = false; - - // - // XCA ... - - // - // Buffers ... - - // - Clean(kiBuffer); - Clean(tkiBuffer); - Clean(sHHBuffer); - Clean(sLLBuffer); - Clean(mHHBuffer); - Clean(mLLBuffer); - Clean(lHHBuffer); - Clean(lLLBuffer); - Clean(hHHBuffer); - Clean(hLLBuffer); - Clean(sarBuffer); - Clean(mahBuffer); - Clean(malBuffer); - Clean(macBuffer); - Clean(peakBuffer); - Clean(valeBuffer); - Clean(vidyaBuffer); - Clean(trendBuffer); - Clean(kiStateBuffer); - Clean(supportBuffer); - Clean(tkiStateBuffer); - Clean(swingLowBuffer); - Clean(swingHighBuffer); - Clean(resistanceBuffer); - Clean(peakGoldenBuffer); - Clean(valeGoldenBuffer); - Clean(fiboLevel1Buffer); - Clean(fiboLevel2Buffer); - Clean(fiboLevel3Buffer); - Clean(fiboLevel4Buffer); - Clean(fiboLevel5Buffer); - Clean(vidyaStateBuffer); - Clean(trendStateBuffer); - - // - ArraySetAsSeries(kiBuffer, true); - ArraySetAsSeries(tkiBuffer, true); - ArraySetAsSeries(sHHBuffer, true); - ArraySetAsSeries(sLLBuffer, true); - ArraySetAsSeries(mHHBuffer, true); - ArraySetAsSeries(mLLBuffer, true); - ArraySetAsSeries(lHHBuffer, true); - ArraySetAsSeries(lLLBuffer, true); - ArraySetAsSeries(hHHBuffer, true); - ArraySetAsSeries(hLLBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(mahBuffer, true); - ArraySetAsSeries(malBuffer, true); - ArraySetAsSeries(macBuffer, true); - ArraySetAsSeries(peakBuffer, true); - ArraySetAsSeries(valeBuffer, true); - ArraySetAsSeries(vidyaBuffer, true); - ArraySetAsSeries(trendBuffer, true); - ArraySetAsSeries(kiStateBuffer, true); - ArraySetAsSeries(supportBuffer, true); - ArraySetAsSeries(tkiStateBuffer, true); - ArraySetAsSeries(swingLowBuffer, true); - ArraySetAsSeries(swingHighBuffer, true); - ArraySetAsSeries(resistanceBuffer, true); - ArraySetAsSeries(peakGoldenBuffer, true); - ArraySetAsSeries(valeGoldenBuffer, true); - ArraySetAsSeries(fiboLevel1Buffer, true); - ArraySetAsSeries(fiboLevel2Buffer, true); - ArraySetAsSeries(fiboLevel3Buffer, true); - ArraySetAsSeries(fiboLevel4Buffer, true); - ArraySetAsSeries(fiboLevel5Buffer, true); - ArraySetAsSeries(vidyaStateBuffer, true); - ArraySetAsSeries(trendStateBuffer, true); - - // - // Conditions ... - - // - // KI ... - - // - isKIRejectUp = false; - isKIRejectDown = false; - - // - isKIBullish = false; - isKIBearish = false; - - // - isKISwitchedToBullish = false; - isKISwitchedToBearish = false; - - // - isKIFinishedFromBullish = false; - isKIFinishedFromBearish = false; - - // - // TKI ... - - // - isTKIRejectUp = false; - isTKIRejectDown = false; - - // - isTKIBullish = false; - isTKIBearish = false; - - // - isTKISwitchedToBullish = false; - isTKISwitchedToBearish = false; - - // - isTKIFinishedFromBullish = false; - isTKIFinishedFromBearish = false; - - // - // VIDYA ... - - // - isVidyaRejectUp = false; - isVidyaRejectDown = false; - - // - isVidyaBullish = false; - isVidyaBearish = false; - - // - isVidyaSwitchedToBullish = false; - isVidyaSwitchedToBearish = false; - - // - isVidyaFinishedFromBullish = false; - isVidyaFinishedFromBearish = false; - - // - // SAR ... - - // - isSarBullish = false; - isSarBearish = false; - - // - isSarSwitchedToBullish = false; - isSarSwitchedToBearish = false; - - // - isSarFinishedFromBullish = false; - isSarFinishedFromBearish = false; - - // - // MANALYSER ... - - // - // MAH ... - - // - isOverMah = false; - isUnderMah = false; - isCrossedOverMah = false; - isCrossedUnderMah = false; - - // - isCloseOverMah = false; - isCloseUnderMah = false; - isCloseCrossedOverMah = false; - isCloseCrossedUnderMah = false; - - // - isMahBullishRejected = false; - isMahBearishRejected = false; - - // - // MAL ... - - // - isOverMal = false; - isUnderMal = false; - isCrossedOverMal = false; - isCrossedUnderMal = false; - - // - isCloseOverMal = false; - isCloseUnderMal = false; - isCloseCrossedOverMal = false; - isCloseCrossedUnderMal = false; - - // - isMalBullishRejected = false; - isMalBearishRejected = false; - - // - // MAC ... - - // - isOverMac = false; - isUnderMac = false; - isCrossedOverMac = false; - isCrossedUnderMac = false; - - // - isCloseOverMac = false; - isCloseUnderMac = false; - isCloseCrossedOverMac = false; - isCloseCrossedUnderMac = false; - - // - isMacBullishRejected = false; - isMacBearishRejected = false; - - // - // PEAK ... - - // - isPeakSameLast = false; - isPeakOverLast = false; - isPeakUnderLast = false; - - // - // VALE ... - - // - isValeSameLast = false; - isValeOverLast = false; - isValeUnderLast = false; - - // - // TREND ... - - // - isTrendRejectUp = false; - isTrendRejectDown = false; - - // - isTrendBullish = false; - isTrendBearish = false; - - // - isTrendSwitchedToBullish = false; - isTrendSwitchedToBearish = false; - - // - isTrendFinishedFromBullish = false; - isTrendFinishedFromBearish = false; - - // - // SUPPORT ... - - // - isSupportSameLast = false; - isSupportOverLast = false; - isSupportUnderLast = false; - - // - isLastSupportBreaked = false; - isLastSupportRejected = false; - - // - // RESISTANCE ... - - // - isResistanceSameLast = false; - isResistanceOverLast = false; - isResistanceUnderLast = false; - - // - isLastResistanceBreaked = false; - isLastResistanceRejected = false; - - // - // SWING Low ... - - // - isSwingLowSameLast = false; - isSwingLowOverLast = false; - isSwingLowUnderLast = false; - - // - isLastSwingLowBreaked = false; - isLastSwingLowRejected = false; - - // - // SWING High ... - - // - isSwingHighSameLast = false; - isSwingHighOverLast = false; - isSwingHighUnderLast = false; - - // - isLastSwingHighBreaked = false; - isLastSwingHighRejected = false; - - // - // COMPLEX Conditions ... - - // - isPeakIsPivot = false; - isValeIsPivot = false; - - // - isPeakSwitchedToPivot = false; - isValeSwitchedToPivot = false; - - // - isPeakFinishedFromPivot = false; - isValeFinishedFromPivot = false; - - // - isSwingLowSameAsVale = false; - isSwingHighSameAsPeak = false; - - // - isSupportSameAsVale = false; - isResistanceSameAsPeak = false; - - // - isSupportSameAsSwingLow = false; - isResistanceSameAsSwingHigh = false; - - // - // XOSCS ... - - // - // Buffers ... - - // - Clean(acBuffer); - Clean(adBuffer); - Clean(atrBuffer); - Clean(cciBuffer); - Clean(rsiBuffer); - Clean(mfiBuffer); - Clean(rviBuffer); - Clean(adxBuffer); - Clean(adxpBuffer); - Clean(adxnBuffer); - Clean(macdBuffer); - Clean(momentumBuffer); - Clean(rviSignalBuffer); - Clean(macdSignalBuffer); - Clean(stochasticBuffer); - Clean(stochasticSignalBuffer); - - // - ArraySetAsSeries(acBuffer, true); - ArraySetAsSeries(adBuffer, true); - ArraySetAsSeries(atrBuffer, true); - ArraySetAsSeries(cciBuffer, true); - ArraySetAsSeries(rsiBuffer, true); - ArraySetAsSeries(mfiBuffer, true); - ArraySetAsSeries(rviBuffer, true); - ArraySetAsSeries(adxBuffer, true); - ArraySetAsSeries(adxpBuffer, true); - ArraySetAsSeries(adxnBuffer, true); - ArraySetAsSeries(macdBuffer, true); - ArraySetAsSeries(momentumBuffer, true); - ArraySetAsSeries(rviSignalBuffer, true); - ArraySetAsSeries(macdSignalBuffer, true); - ArraySetAsSeries(stochasticBuffer, true); - ArraySetAsSeries(stochasticSignalBuffer, true); - - // - // Values ... - - // - adxThreshold = 0.0; - cciOBLevel = 0.0; - cciOSLevel = 0.0; - cciReversalLevel = 0.0; - rsiOBLevel = 0.0; - rsiOSLevel = 0.0; - rsiReversalLevel = 0.0; - mfiOBLevel = 0.0; - mfiOSLevel = 0.0; - mfiReversalLevel = 0.0; - rviBullishLevel = 0.0; - rviBearishLevel = 0.0; - macdBullishLevel = 0.0; - macdBearishLevel = 0.0; - momentumBullishLevel = 0.0; - momentumBearishLevel = 0.0; - stochasticOBLevel = 0.0; - stochasticOSLevel = 0.0; - stochasticReversalLevel = 0.0; - - // - // Conditions ... - - // - // AC ... - - // - isACBullish = false; - isACBearish = false; - isACSwitchedToBullish = false; - isACSwitchedToBearish = false; - isACOverMax = false; - isACUnderMin = false; - - // - // AD ... - - // - isADBiggerLast = false; - isADLesserLast = false; - isADOverMax = false; - isADUnderMin = false; - - // - // ADX ... - - // - isADXBiggerLast = false; - isADXLesserLast = false; - isADXOverThreshold = false; - isADXUnderThreshold = false; - isDXPBiggerThanDXN = false; - isDXNBiggerThanDXP = false; - isADXBullish = false; - isADXBearish = false; - isADXSwitchedToBullish = false; - isADXSwitchedToBearish = false; - - // - // ATR ... - - // - isATROverLast = false; - isATRUnderLast = false; - - // - // CCI ... - - // - isCCIBullish = false; - isCCIBearish = false; - isCCISwitchedToBullish = false; - isCCISwitchedToBearish = false; - isCCIOB = false; - isCCIOS = false; - isCCICrossedOverOB = false; - isCCICrossedOverOS = false; - isCCICrossedUnderOB = false; - isCCICrossedUnderOS = false; - - // - // RSI ... - - // - isRSIBullish = false; - isRSIBearish = false; - isRSISwitchedToBullish = false; - isRSISwitchedToBearish = false; - isRSIOB = false; - isRSIOS = false; - isRSICrossedOverOB = false; - isRSICrossedOverOS = false; - isRSICrossedUnderOB = false; - isRSICrossedUnderOS = false; - - // - // MFI ... - - // - isMFIBullish = false; - isMFIBearish = false; - isMFISwitchedToBullish = false; - isMFISwitchedToBearish = false; - isMFIOB = false; - isMFIOS = false; - isMFICrossedOverOB = false; - isMFICrossedOverOS = false; - isMFICrossedUnderOB = false; - isMFICrossedUnderOS = false; - - // - // RVI ... - - // - isRVIBullish = false; - isRVIBearish = false; - isRVISwitchedToBullish = false; - isRVISwitchedToBearish = false; - isRVIOverSignal = false; - isRVIUnderSignal = false; - isRVICrossedOverSignal = false; - isRVICrossedUnderSignal = false; - - // - // MACD ... - - // - isMACDBullish = false; - isMACDBearish = false; - isMACDSwitchedToBullish = false; - isMACDSwitchedToBearish = false; - isMACDOverSignal = false; - isMACDUnderSignal = false; - isMACDCrossedOverSignal = false; - isMACDCrossedUnderSignal = false; - - // - // MOMENTUM ... - - // - isMomentumBullish = false; - isMomentumBearish = false; - isMomentumSwitchedToBullish = false; - isMomentumSwitchedToBearish = false; - - // - // STOCHASTIC ... - - // - isStochasticBullish = false; - isStochasticBearish = false; - isStochasticSwitchedToBullish = false; - isStochasticSwitchedToBearish = false; - isStochasticOverSignal = false; - isStochasticUnderSignal = false; - isStochasticCrossedOverSignal = false; - isStochasticCrossedUnderSignal = false; - isStochasticOB = false; - isStochasticOS = false; - isStochasticCrossedOverOB = false; - isStochasticCrossedOverOS = false; - isStochasticCrossedUnderOB = false; - isStochasticCrossedUnderOS = false; - - // - ZeroMemory(this); - } - - /** - * Generate Conditions Scores ... - * - * @param bullishScore: Double, Directional Scores Reference ... - * @param bearishScore: Double, Directional Scores Reference ... - */ - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - double score = 1; - double minScore = 0.5; - double highScore = 1.5; - - // - // X3MA ... - - // - // XCA ... - - // - if (isFastOverSlow) - { - bullishScore += minScore; - } - if (isFastOverMedium) - { - bullishScore += minScore; - } - if (isMediumOverSlow) - { - bullishScore += minScore; - } - if (isFastCrossedOverSlow) - { - bullishScore += score; - } - if (isFastCrossedOverMedium) - { - bullishScore += score; - } - if (isMediumCrossedOverSlow) - { - bullishScore += score; - } - - // - if (is3MaBullish) - { - bullishScore += minScore; - } - if (is3MaBullishState) - { - bullishScore += minScore; - } - if (is3MaBullishOrdered) - { - bullishScore += minScore; - } - if (is3MaSwitchedToBullish) - { - bullishScore += minScore; - } - if (is3MaFinishedFromBearish) - { - bullishScore += minScore; - } - if (is3MaSwitchedToBullishState) - { - bullishScore += minScore; - } - if (is3MaSwitchedToBullishOrdered) - { - bullishScore += minScore; - } - - // - if (isFastUnderSlow) - { - bearishScore += minScore; - } - if (isMediumUnderSlow) - { - bearishScore += minScore; - } - if (isFastUnderMedium) - { - bearishScore += minScore; - } - if (isFastCrossedUnderSlow) - { - bearishScore += score; - } - if (isFastCrossedUnderMedium) - { - bearishScore += score; - } - if (isMediumCrossedUnderSlow) - { - bearishScore += score; - } - - // - if (is3MaBearish) - { - bearishScore += minScore; - } - if (is3MaBearishState) - { - bearishScore += minScore; - } - if (is3MaBearishOrdered) - { - bearishScore += minScore; - } - if (is3MaSwitchedToBearish) - { - bearishScore += minScore; - } - if (is3MaFinishedFromBullish) - { - bearishScore += minScore; - } - if (is3MaSwitchedToBearishState) - { - bearishScore += minScore; - } - if (is3MaSwitchedToBearishOrdered) - { - bearishScore += minScore; - } - // - // KI ... - - // - if (isKIBullish) - { - bullishScore += minScore; - } - if (isKIRejectUp) - { - bullishScore += minScore; - } - if (isKISwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isKIBearish) - { - bearishScore += minScore; - } - if (isKIRejectDown) - { - bearishScore += minScore; - } - if (isKISwitchedToBearish) - { - bearishScore += minScore; - } - - // - // TKI ... - - // - if (isTKIBullish) - { - bullishScore += minScore; - } - if (isTKIRejectUp) - { - bullishScore += minScore; - } - if (isTKISwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isTKIBearish) - { - bearishScore += minScore; - } - if (isTKIRejectDown) - { - bearishScore += minScore; - } - if (isTKISwitchedToBearish) - { - bearishScore += minScore; - } - - // - // VIDYA ... - - // - if (isVidyaBullish) - { - bullishScore += minScore; - } - if (isVidyaRejectUp) - { - bullishScore += minScore; - } - if (isVidyaSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isVidyaBearish) - { - bearishScore += minScore; - } - if (isVidyaRejectDown) - { - bearishScore += minScore; - } - if (isVidyaSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // SAR ... - - // - if (isSarBullish) - { - bullishScore += minScore; - } - if (isSarSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isSarBearish) - { - bearishScore += minScore; - } - if (isSarSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // MANALYSER ... - - // - // MAH ... - - // - if (isUnderMah) - { - bullishScore += minScore; - } - if (isCloseUnderMah) - { - bullishScore += minScore; - } - if (isCrossedUnderMah) - { - bullishScore += minScore; - } - if (isMahBullishRejected) - { - bullishScore += minScore; - } - if (isCloseCrossedUnderMah) - { - bullishScore += minScore; - } - - // - if (isOverMah) - { - bearishScore += minScore; - } - if (isCloseOverMah) - { - bearishScore += minScore; - } - if (isCrossedOverMah) - { - bearishScore += minScore; - } - if (isMahBearishRejected) - { - bearishScore += minScore; - } - if (isCloseCrossedOverMah) - { - bearishScore += minScore; - } - - // - - // - // MAL ... - - // - if (isOverMal) - { - bullishScore += minScore; - } - if (isCloseOverMal) - { - bullishScore += minScore; - } - if (isCrossedOverMal) - { - bullishScore += minScore; - } - if (isMalBullishRejected) - { - bullishScore += minScore; - } - if (isCloseCrossedOverMal) - { - bullishScore += minScore; - } - - // - if (isUnderMal) - { - bearishScore += minScore; - } - if (isCloseUnderMal) - { - bearishScore += minScore; - } - if (isCrossedUnderMal) - { - bearishScore += minScore; - } - if (isMalBearishRejected) - { - bearishScore += minScore; - } - if (isCloseCrossedUnderMal) - { - bearishScore += minScore; - } - - // - // MAC ... - - // - if (isOverMac) - { - bullishScore += minScore; - } - if (isCloseOverMac) - { - bullishScore += minScore; - } - if (isCrossedOverMac) - { - bullishScore += minScore; - } - if (isMacBullishRejected) - { - bullishScore += minScore; - } - if (isCloseCrossedOverMac) - { - bullishScore += minScore; - } - - // - if (isUnderMac) - { - bearishScore += minScore; - } - if (isCloseUnderMac) - { - bearishScore += minScore; - } - if (isCrossedUnderMac) - { - bearishScore += minScore; - } - if (isMacBearishRejected) - { - bearishScore += minScore; - } - if (isCloseCrossedUnderMac) - { - bearishScore += minScore; - } - - // - // TREND ... - - // - if (isTrendBullish) - { - bullishScore += minScore; - } - if (isTrendRejectUp) - { - bullishScore += minScore; - } - if (isTrendSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isTrendBearish) - { - bearishScore += minScore; - } - if (isTrendRejectDown) - { - bearishScore += minScore; - } - if (isTrendSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // SUPPORT ... - - // - if (isSupportSameLast) - { - bullishScore += minScore; - } - if (isSupportOverLast) - { - bullishScore += minScore; - } - if (isLastSupportRejected) - { - bullishScore += minScore; - } - - // - if (isSupportUnderLast) - { - bearishScore += minScore; - } - if (isLastSupportBreaked) - { - bearishScore += minScore; - } - - // - // RESISTANCE ... - - // - if (isResistanceOverLast) - { - bullishScore += minScore; - } - if (isLastResistanceBreaked) - { - bullishScore += minScore; - } - - // - if (isResistanceSameLast) - { - bearishScore += minScore; - } - if (isResistanceUnderLast) - { - bearishScore += minScore; - } - if (isLastResistanceRejected) - { - bearishScore += minScore; - } - - // - // SWING Low ... - - // - if (isSwingLowSameLast) - { - bullishScore += minScore; - } - if (isSwingLowOverLast) - { - bullishScore += minScore; - } - if (isLastSwingLowRejected) - { - bullishScore += minScore; - } - - // - if (isSwingLowUnderLast) - { - bearishScore += minScore; - } - if (isLastSwingLowBreaked) - { - bearishScore += minScore; - } - - // - // SWING High ... - - // - if (isSwingHighOverLast) - { - bullishScore += minScore; - } - if (isLastSwingHighBreaked) - { - bullishScore += minScore; - } - - // - if (isSwingHighSameLast) - { - bearishScore += minScore; - } - if (isSwingHighUnderLast) - { - bearishScore += minScore; - } - if (isLastSwingHighRejected) - { - bearishScore += minScore; - } - - // - // COMPLEX Conditions ... - - // - if (isValeIsPivot) - { - bullishScore += score; - } - if (isSupportSameAsVale) - { - bullishScore += score; - } - if (isSwingLowSameAsVale) - { - bullishScore += score; - } - if (isSupportSameAsSwingLow) - { - bullishScore += score; - } - - // - if (isPeakIsPivot) - { - bearishScore += score; - } - if (isSwingHighSameAsPeak) - { - bearishScore += score; - } - if (isResistanceSameAsPeak) - { - bearishScore += score; - } - if (isResistanceSameAsSwingHigh) - { - bearishScore += score; - } - - // - // XOCS ... - - // - // AC ... - - // - if (isACBullish) - { - bullishScore += minScore; - } - if (isACOverMax) - { - bullishScore += minScore; - } - if (isACSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isACBearish) - { - bearishScore += minScore; - } - if (isACUnderMin) - { - bearishScore += minScore; - } - if (isACSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // AD ... - - // - if (isADOverMax) - { - bullishScore += minScore; - } - if (isADBiggerLast) - { - bullishScore += minScore; - } - - // - if (isADUnderMin) - { - bearishScore += minScore; - } - if (isADLesserLast) - { - bearishScore += minScore; - } - - // - // ADX ... - - // - if (isADXBullish) - { - bullishScore += minScore; - } - if (isADXBiggerLast) - { - bullishScore += minScore; - } - if (isADXOverThreshold) - { - bullishScore += minScore; - } - if (isDXPBiggerThanDXN) - { - bullishScore += minScore; - } - if (isADXSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isADXBearish) - { - bearishScore += minScore; - } - if (isADXLesserLast) - { - bearishScore += minScore; - } - if (isDXNBiggerThanDXP) - { - bearishScore += minScore; - } - if (isADXUnderThreshold) - { - bearishScore += minScore; - } - if (isADXSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // ATR ... - - // - if (isATROverLast) - { - bullishScore += minScore; - } - - // - if (isATRUnderLast) - { - bearishScore += minScore; - } - - // - // CCI ... - - // - if (isCCIOS) - { - bullishScore += minScore; - } - if (isCCIBullish) - { - bullishScore += minScore; - } - if (isCCICrossedOverOS) - { - bullishScore += minScore; - } - if (isCCICrossedOverOB) - { - bullishScore += minScore; - } - if (isCCISwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isCCIOB) - { - bearishScore += minScore; - } - if (isCCIBearish) - { - bearishScore += minScore; - } - if (isCCICrossedUnderOS) - { - bearishScore += minScore; - } - if (isCCICrossedUnderOB) - { - bearishScore += minScore; - } - if (isCCISwitchedToBearish) - { - bearishScore += minScore; - } - - // - // RSI ... - - // - if (isRSIOS) - { - bullishScore += minScore; - } - if (isRSIBullish) - { - bullishScore += minScore; - } - if (isRSICrossedOverOB) - { - bullishScore += minScore; - } - if (isRSICrossedOverOS) - { - bullishScore += minScore; - } - if (isRSISwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isRSIOB) - { - bearishScore += minScore; - } - if (isRSIBearish) - { - bearishScore += minScore; - } - if (isRSICrossedUnderOB) - { - bearishScore += minScore; - } - if (isRSICrossedUnderOS) - { - bearishScore += minScore; - } - if (isRSISwitchedToBearish) - { - bearishScore += minScore; - } - - // - // MFI ... - - // - if (isMFIOS) - { - bullishScore += minScore; - } - if (isMFIBullish) - { - bullishScore += minScore; - } - if (isMFICrossedOverOB) - { - bullishScore += minScore; - } - if (isMFICrossedOverOS) - { - bullishScore += minScore; - } - if (isMFISwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isMFIOB) - { - bearishScore += minScore; - } - if (isMFIBearish) - { - bearishScore += minScore; - } - if (isMFICrossedUnderOB) - { - bearishScore += minScore; - } - if (isMFICrossedUnderOS) - { - bearishScore += minScore; - } - if (isMFISwitchedToBearish) - { - bearishScore += minScore; - } - - // - // RVI ... - - // - if (isRVIBullish) - { - bullishScore += minScore; - } - if (isRVIOverSignal) - { - bullishScore += minScore; - } - if (isRVISwitchedToBullish) - { - bullishScore += minScore; - } - if (isRVICrossedOverSignal) - { - bullishScore += minScore; - } - - // - if (isRVIBearish) - { - bearishScore += minScore; - } - if (isRVIUnderSignal) - { - bearishScore += minScore; - } - if (isRVISwitchedToBearish) - { - bearishScore += minScore; - } - if (isRVICrossedUnderSignal) - { - bearishScore += minScore; - } - - // - // MACD ... - - // - if (isMACDBullish) - { - bullishScore += minScore; - } - if (isMACDOverSignal) - { - bullishScore += minScore; - } - if (isMACDSwitchedToBullish) - { - bullishScore += minScore; - } - if (isMACDCrossedOverSignal) - { - bullishScore += minScore; - } - - // - if (isMACDBearish) - { - bearishScore += minScore; - } - if (isMACDUnderSignal) - { - bearishScore += minScore; - } - if (isMACDSwitchedToBearish) - { - bearishScore += minScore; - } - if (isMACDCrossedUnderSignal) - { - bearishScore += minScore; - } - - // - // MOMENTUM ... - - // - if (isMomentumBullish) - { - bullishScore += minScore; - } - if (isMomentumSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isMomentumBearish) - { - bearishScore += minScore; - } - if (isMomentumSwitchedToBearish) - { - bearishScore += minScore; - } - - // - // STOCHASTIC ... - - // - if (isStochasticOS) - { - bullishScore += minScore; - } - if (isStochasticOverSignal) - { - bullishScore += minScore; - } - if (isStochasticBullish) - { - bullishScore += minScore; - } - if (isStochasticCrossedOverSignal) - { - bullishScore += minScore; - } - if (isStochasticCrossedOverOB) - { - bullishScore += minScore; - } - if (isStochasticCrossedOverOS) - { - bullishScore += minScore; - } - if (isStochasticSwitchedToBullish) - { - bullishScore += minScore; - } - - // - if (isStochasticOB) - { - bearishScore += minScore; - } - if (isStochasticUnderSignal) - { - bearishScore += minScore; - } - if (isStochasticBearish) - { - bearishScore += minScore; - } - if (isStochasticCrossedUnderSignal) - { - bearishScore += minScore; - } - if (isStochasticCrossedUnderOB) - { - bearishScore += minScore; - } - if (isStochasticCrossedUnderOS) - { - bearishScore += minScore; - } - if (isStochasticSwitchedToBearish) - { - bearishScore += minScore; - } - } - - /** - * Generate Summary String for Represent Conditions State ... - * - * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... - * @param onlyConditions: Boolean, Just Generate Only Conditions ... - * @param includeScores: Boolean, Attach Scores Representations on Result ... - * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... - * @param separator: String, Separate Lines ... - * - * @return ( string ) - */ - string GenerateSummary( - bool onlyCommons = false, - bool onlyConditions = false, - bool includeScores = true, - bool ignoreFalseConditions = true, - string separator = "\n" // - ) - { - // - string result = NULL; - - // - double bullishScore = 0; - double bearishScore = 0; - GenerateScore( - bullishScore, - bearishScore // - ); - - // - string scoresStr = - // - "Scores: " + separator + - "---------------" + separator + - "Bullish: " + ToString(bullishScore) + separator + - "Bearish: " + ToString(bearishScore) + separator + - "" - // - ; - - // - string commonStr = GenerateSpecifiedCommonSummary( - this, - separator, - includeScores // - ); - - // - string conditionsStr = - // - // - "-----------------------" + separator + - "X3MA: " + separator + - "-----------------------" + separator + - ToString("isFastOverMedium", isFastOverMedium, ignoreFalseConditions, separator) + - ToString("isFastUnderMedium", isFastUnderMedium, ignoreFalseConditions, separator) + - ToString("isFastCrossedOverMedium", isFastCrossedOverMedium, ignoreFalseConditions, separator) + - ToString("isFastCrossedUnderMedium", isFastCrossedUnderMedium, ignoreFalseConditions, separator) + - ToString("isFastOverSlow", isFastOverSlow, ignoreFalseConditions, separator) + - ToString("isFastUnderSlow", isFastUnderSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedOverSlow", isFastCrossedOverSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedUnderSlow", isFastCrossedUnderSlow, ignoreFalseConditions, separator) + - ToString("isMediumOverSlow", isMediumOverSlow, ignoreFalseConditions, separator) + - ToString("isMediumUnderSlow", isMediumUnderSlow, ignoreFalseConditions, separator) + - ToString("isMediumCrossedOverSlow", isMediumCrossedOverSlow, ignoreFalseConditions, separator) + - ToString("isMediumCrossedUnderSlow", isMediumCrossedUnderSlow, ignoreFalseConditions, separator) + - ToString("is3MaBullishOrdered", is3MaBullishOrdered, ignoreFalseConditions, separator) + - ToString("is3MaBearishOrdered", is3MaBearishOrdered, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBullishOrdered", is3MaSwitchedToBullishOrdered, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBearishOrdered", is3MaSwitchedToBearishOrdered, ignoreFalseConditions, separator) + - ToString("is3MaBullishState", is3MaBullishState, ignoreFalseConditions, separator) + - ToString("is3MaBearishState", is3MaBearishState, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBullishState", is3MaSwitchedToBullishState, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBearishState", is3MaSwitchedToBearishState, ignoreFalseConditions, separator) + - ToString("is3MaBullish", is3MaBullish, ignoreFalseConditions, separator) + - ToString("is3MaBearish", is3MaBearish, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBullish", is3MaSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("is3MaSwitchedToBearish", is3MaSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("is3MaFinishedFromBullish", is3MaFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("is3MaFinishedFromBearish", is3MaFinishedFromBearish, ignoreFalseConditions, separator) + - "-----------------------" + separator + - "XCA: " + separator + - "-----------------------" + separator + - ToString("isKIRejectUp", isKIRejectUp, ignoreFalseConditions, separator) + - ToString("isKIRejectDown", isKIRejectDown, ignoreFalseConditions, separator) + - ToString("isKIBullish", isKIBullish, ignoreFalseConditions, separator) + - ToString("isKIBearish", isKIBearish, ignoreFalseConditions, separator) + - ToString("isKISwitchedToBullish", isKISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isKIFinishedFromBullish", isKIFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("isKISwitchedToBearish", isKISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isKIFinishedFromBearish", isKIFinishedFromBearish, ignoreFalseConditions, separator) + - ToString("isTKIRejectUp", isTKIRejectUp, ignoreFalseConditions, separator) + - ToString("isTKIRejectDown", isTKIRejectDown, ignoreFalseConditions, separator) + - ToString("isTKIBullish", isTKIBullish, ignoreFalseConditions, separator) + - ToString("isTKIBearish", isTKIBearish, ignoreFalseConditions, separator) + - ToString("isTKISwitchedToBullish", isTKISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isTKIFinishedFromBullish", isTKIFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("isTKISwitchedToBearish", isTKISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isTKIFinishedFromBearish", isTKIFinishedFromBearish, ignoreFalseConditions, separator) + - ToString("isVidyaRejectUp", isVidyaRejectUp, ignoreFalseConditions, separator) + - ToString("isVidyaRejectDown", isVidyaRejectDown, ignoreFalseConditions, separator) + - ToString("isVidyaBullish", isVidyaBullish, ignoreFalseConditions, separator) + - ToString("isVidyaBearish", isVidyaBearish, ignoreFalseConditions, separator) + - ToString("isVidyaSwitchedToBullish", isVidyaSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isVidyaFinishedFromBullish", isVidyaFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("isVidyaSwitchedToBearish", isVidyaSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isVidyaFinishedFromBearish", isVidyaFinishedFromBearish, ignoreFalseConditions, separator) + - ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + - ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + - ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSarFinishedFromBullish", isSarFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isSarFinishedFromBearish", isSarFinishedFromBearish, ignoreFalseConditions, separator) + - ToString("isOverMah", isOverMah, ignoreFalseConditions, separator) + - ToString("isUnderMah", isUnderMah, ignoreFalseConditions, separator) + - ToString("isCrossedOverMah", isCrossedOverMah, ignoreFalseConditions, separator) + - ToString("isCrossedUnderMah", isCrossedUnderMah, ignoreFalseConditions, separator) + - ToString("isCloseOverMah", isCloseOverMah, ignoreFalseConditions, separator) + - ToString("isCloseUnderMah", isCloseUnderMah, ignoreFalseConditions, separator) + - ToString("isCloseCrossedOverMah", isCloseCrossedOverMah, ignoreFalseConditions, separator) + - ToString("isCloseCrossedUnderMah", isCloseCrossedUnderMah, ignoreFalseConditions, separator) + - ToString("isMahBullishRejected", isMahBullishRejected, ignoreFalseConditions, separator) + - ToString("isMahBearishRejected", isMahBearishRejected, ignoreFalseConditions, separator) + - ToString("isOverMal", isOverMal, ignoreFalseConditions, separator) + - ToString("isUnderMal", isUnderMal, ignoreFalseConditions, separator) + - ToString("isCrossedOverMal", isCrossedOverMal, ignoreFalseConditions, separator) + - ToString("isCrossedUnderMal", isCrossedUnderMal, ignoreFalseConditions, separator) + - ToString("isCloseOverMal", isCloseOverMal, ignoreFalseConditions, separator) + - ToString("isCloseUnderMal", isCloseUnderMal, ignoreFalseConditions, separator) + - ToString("isCloseCrossedOverMal", isCloseCrossedOverMal, ignoreFalseConditions, separator) + - ToString("isCloseCrossedUnderMal", isCloseCrossedUnderMal, ignoreFalseConditions, separator) + - ToString("isMalBullishRejected", isMalBullishRejected, ignoreFalseConditions, separator) + - ToString("isMalBearishRejected", isMalBearishRejected, ignoreFalseConditions, separator) + - ToString("isOverMac", isOverMac, ignoreFalseConditions, separator) + - ToString("isUnderMac", isUnderMac, ignoreFalseConditions, separator) + - ToString("isCrossedOverMac", isCrossedOverMac, ignoreFalseConditions, separator) + - ToString("isCrossedUnderMac", isCrossedUnderMac, ignoreFalseConditions, separator) + - ToString("isCloseOverMac", isCloseOverMac, ignoreFalseConditions, separator) + - ToString("isCloseUnderMac", isCloseUnderMac, ignoreFalseConditions, separator) + - ToString("isCloseCrossedOverMac", isCloseCrossedOverMac, ignoreFalseConditions, separator) + - ToString("isCloseCrossedUnderMac", isCloseCrossedUnderMac, ignoreFalseConditions, separator) + - ToString("isMacBullishRejected", isMacBullishRejected, ignoreFalseConditions, separator) + - ToString("isMacBearishRejected", isMacBearishRejected, ignoreFalseConditions, separator) + - ToString("isPeakSameLast", isPeakSameLast, ignoreFalseConditions, separator) + - ToString("isPeakOverLast", isPeakOverLast, ignoreFalseConditions, separator) + - ToString("isPeakUnderLast", isPeakUnderLast, ignoreFalseConditions, separator) + - ToString("isValeSameLast", isValeSameLast, ignoreFalseConditions, separator) + - ToString("isValeOverLast", isValeOverLast, ignoreFalseConditions, separator) + - ToString("isValeUnderLast", isValeUnderLast, ignoreFalseConditions, separator) + - ToString("isTrendRejectUp", isTrendRejectUp, ignoreFalseConditions, separator) + - ToString("isTrendRejectDown", isTrendRejectDown, ignoreFalseConditions, separator) + - ToString("isTrendBullish", isTrendBullish, ignoreFalseConditions, separator) + - ToString("isTrendBearish", isTrendBearish, ignoreFalseConditions, separator) + - ToString("isTrendSwitchedToBullish", isTrendSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isTrendFinishedFromBullish", isTrendFinishedFromBullish, ignoreFalseConditions, separator) + - ToString("isTrendSwitchedToBearish", isTrendSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isTrendFinishedFromBearish", isTrendFinishedFromBearish, ignoreFalseConditions, separator) + - ToString("isSupportSameLast", isSupportSameLast, ignoreFalseConditions, separator) + - ToString("isSupportOverLast", isSupportOverLast, ignoreFalseConditions, separator) + - ToString("isSupportUnderLast", isSupportUnderLast, ignoreFalseConditions, separator) + - ToString("isLastSupportBreaked", isLastSupportBreaked, ignoreFalseConditions, separator) + - ToString("isLastSupportRejected", isLastSupportRejected, ignoreFalseConditions, separator) + - ToString("isResistanceSameLast", isResistanceSameLast, ignoreFalseConditions, separator) + - ToString("isResistanceOverLast", isResistanceOverLast, ignoreFalseConditions, separator) + - ToString("isResistanceUnderLast", isResistanceUnderLast, ignoreFalseConditions, separator) + - ToString("isLastResistanceBreaked", isLastResistanceBreaked, ignoreFalseConditions, separator) + - ToString("isLastResistanceRejected", isLastResistanceRejected, ignoreFalseConditions, separator) + - ToString("isSwingLowSameLast", isSwingLowSameLast, ignoreFalseConditions, separator) + - ToString("isSwingLowOverLast", isSwingLowOverLast, ignoreFalseConditions, separator) + - ToString("isSwingLowUnderLast", isSwingLowUnderLast, ignoreFalseConditions, separator) + - ToString("isLastSwingLowBreaked", isLastSwingLowBreaked, ignoreFalseConditions, separator) + - ToString("isLastSwingLowRejected", isLastSwingLowRejected, ignoreFalseConditions, separator) + - ToString("isSwingHighSameLast", isSwingHighSameLast, ignoreFalseConditions, separator) + - ToString("isSwingHighOverLast", isSwingHighOverLast, ignoreFalseConditions, separator) + - ToString("isSwingHighUnderLast", isSwingHighUnderLast, ignoreFalseConditions, separator) + - ToString("isLastSwingHighBreaked", isLastSwingHighBreaked, ignoreFalseConditions, separator) + - ToString("isLastSwingHighRejected", isLastSwingHighRejected, ignoreFalseConditions, separator) + - ToString("isPeakIsPivot", isPeakIsPivot, ignoreFalseConditions, separator) + - ToString("isValeIsPivot", isValeIsPivot, ignoreFalseConditions, separator) + - ToString("isPeakSwitchedToPivot", isPeakSwitchedToPivot, ignoreFalseConditions, separator) + - ToString("isPeakFinishedFromPivot", isPeakFinishedFromPivot, ignoreFalseConditions, separator) + - ToString("isValeSwitchedToPivot", isValeSwitchedToPivot, ignoreFalseConditions, separator) + - ToString("isValeFinishedFromPivot", isValeFinishedFromPivot, ignoreFalseConditions, separator) + - ToString("isSwingLowSameAsVale", isSwingLowSameAsVale, ignoreFalseConditions, separator) + - ToString("isSwingHighSameAsPeak", isSwingHighSameAsPeak, ignoreFalseConditions, separator) + - ToString("isSupportSameAsVale", isSupportSameAsVale, ignoreFalseConditions, separator) + - ToString("isResistanceSameAsPeak", isResistanceSameAsPeak, ignoreFalseConditions, separator) + - ToString("isSupportSameAsSwingLow", isSupportSameAsSwingLow, ignoreFalseConditions, separator) + - ToString("isResistanceSameAsSwingHigh", isResistanceSameAsSwingHigh, ignoreFalseConditions, separator) + - "-----------------------" + separator + - "XOCS: " + separator + - "-----------------------" + separator + - ToString("isACBullish", isACBullish, ignoreFalseConditions, separator) + - ToString("isACBearish", isACBearish, ignoreFalseConditions, separator) + - ToString("isACSwitchedToBullish", isACSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isACSwitchedToBearish", isACSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isACOverMax", isACOverMax, ignoreFalseConditions, separator) + - ToString("isACUnderMin", isACUnderMin, ignoreFalseConditions, separator) + - ToString("isADBiggerLast", isADBiggerLast, ignoreFalseConditions, separator) + - ToString("isADLesserLast", isADLesserLast, ignoreFalseConditions, separator) + - ToString("isADOverMax", isADOverMax, ignoreFalseConditions, separator) + - ToString("isADUnderMin", isADUnderMin, ignoreFalseConditions, separator) + - ToString("isADXBiggerLast", isADXBiggerLast, ignoreFalseConditions, separator) + - ToString("isADXLesserLast", isADXLesserLast, ignoreFalseConditions, separator) + - ToString("isADXOverThreshold", isADXOverThreshold, ignoreFalseConditions, separator) + - ToString("isADXUnderThreshold", isADXUnderThreshold, ignoreFalseConditions, separator) + - ToString("isDXPBiggerThanDXN", isDXPBiggerThanDXN, ignoreFalseConditions, separator) + - ToString("isDXNBiggerThanDXP", isDXNBiggerThanDXP, ignoreFalseConditions, separator) + - ToString("isADXBullish", isADXBullish, ignoreFalseConditions, separator) + - ToString("isADXBearish", isADXBearish, ignoreFalseConditions, separator) + - ToString("isADXSwitchedToBullish", isADXSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isADXSwitchedToBearish", isADXSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isATROverLast", isATROverLast, ignoreFalseConditions, separator) + - ToString("isATRUnderLast", isATRUnderLast, ignoreFalseConditions, separator) + - ToString("isCCIBullish", isCCIBullish, ignoreFalseConditions, separator) + - ToString("isCCIBearish", isCCIBearish, ignoreFalseConditions, separator) + - ToString("isCCISwitchedToBullish", isCCISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isCCISwitchedToBearish", isCCISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isCCIOB", isCCIOB, ignoreFalseConditions, separator) + - ToString("isCCIOS", isCCIOS, ignoreFalseConditions, separator) + - ToString("isCCICrossedOverOB", isCCICrossedOverOB, ignoreFalseConditions, separator) + - ToString("isCCICrossedOverOS", isCCICrossedOverOS, ignoreFalseConditions, separator) + - ToString("isCCICrossedUnderOB", isCCICrossedUnderOB, ignoreFalseConditions, separator) + - ToString("isCCICrossedUnderOS", isCCICrossedUnderOS, ignoreFalseConditions, separator) + - ToString("isRSIBullish", isRSIBullish, ignoreFalseConditions, separator) + - ToString("isRSIBearish", isRSIBearish, ignoreFalseConditions, separator) + - ToString("isRSISwitchedToBullish", isRSISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isRSISwitchedToBearish", isRSISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isRSIOB", isRSIOB, ignoreFalseConditions, separator) + - ToString("isRSIOS", isRSIOS, ignoreFalseConditions, separator) + - ToString("isRSICrossedOverOB", isRSICrossedOverOB, ignoreFalseConditions, separator) + - ToString("isRSICrossedOverOS", isRSICrossedOverOS, ignoreFalseConditions, separator) + - ToString("isRSICrossedUnderOB", isRSICrossedUnderOB, ignoreFalseConditions, separator) + - ToString("isRSICrossedUnderOS", isRSICrossedUnderOS, ignoreFalseConditions, separator) + - ToString("isMFIBullish", isMFIBullish, ignoreFalseConditions, separator) + - ToString("isMFIBearish", isMFIBearish, ignoreFalseConditions, separator) + - ToString("isMFISwitchedToBullish", isMFISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMFISwitchedToBearish", isMFISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isMFIOB", isMFIOB, ignoreFalseConditions, separator) + - ToString("isMFIOS", isMFIOS, ignoreFalseConditions, separator) + - ToString("isMFICrossedOverOB", isMFICrossedOverOB, ignoreFalseConditions, separator) + - ToString("isMFICrossedOverOS", isMFICrossedOverOS, ignoreFalseConditions, separator) + - ToString("isMFICrossedUnderOB", isMFICrossedUnderOB, ignoreFalseConditions, separator) + - ToString("isMFICrossedUnderOS", isMFICrossedUnderOS, ignoreFalseConditions, separator) + - ToString("isRVIBullish", isRVIBullish, ignoreFalseConditions, separator) + - ToString("isRVIBearish", isRVIBearish, ignoreFalseConditions, separator) + - ToString("isRVISwitchedToBullish", isRVISwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isRVISwitchedToBearish", isRVISwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isRVIOverSignal", isRVIOverSignal, ignoreFalseConditions, separator) + - ToString("isRVIUnderSignal", isRVIUnderSignal, ignoreFalseConditions, separator) + - ToString("isRVICrossedOverSignal", isRVICrossedOverSignal, ignoreFalseConditions, separator) + - ToString("isRVICrossedUnderSignal", isRVICrossedUnderSignal, ignoreFalseConditions, separator) + - ToString("isMACDBullish", isMACDBullish, ignoreFalseConditions, separator) + - ToString("isMACDBearish", isMACDBearish, ignoreFalseConditions, separator) + - ToString("isMACDSwitchedToBullish", isMACDSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMACDSwitchedToBearish", isMACDSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isMACDOverSignal", isMACDOverSignal, ignoreFalseConditions, separator) + - ToString("isMACDUnderSignal", isMACDUnderSignal, ignoreFalseConditions, separator) + - ToString("isMACDCrossedOverSignal", isMACDCrossedOverSignal, ignoreFalseConditions, separator) + - ToString("isMACDCrossedUnderSignal", isMACDCrossedUnderSignal, ignoreFalseConditions, separator) + - ToString("isMomentumBullish", isMomentumBullish, ignoreFalseConditions, separator) + - ToString("isMomentumBearish", isMomentumBearish, ignoreFalseConditions, separator) + - ToString("isMomentumSwitchedToBullish", isMomentumSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMomentumSwitchedToBearish", isMomentumSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isStochasticBullish", isStochasticBullish, ignoreFalseConditions, separator) + - ToString("isStochasticBearish", isStochasticBearish, ignoreFalseConditions, separator) + - ToString("isStochasticSwitchedToBullish", isStochasticSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isStochasticSwitchedToBearish", isStochasticSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isStochasticOverSignal", isStochasticOverSignal, ignoreFalseConditions, separator) + - ToString("isStochasticUnderSignal", isStochasticUnderSignal, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedOverSignal", isStochasticCrossedOverSignal, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedUnderSignal", isStochasticCrossedUnderSignal, ignoreFalseConditions, separator) + - ToString("isStochasticOB", isStochasticOB, ignoreFalseConditions, separator) + - ToString("isStochasticOS", isStochasticOS, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedOverOB", isStochasticCrossedOverOB, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedOverOS", isStochasticCrossedOverOS, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedUnderOB", isStochasticCrossedUnderOB, ignoreFalseConditions, separator) + - ToString("isStochasticCrossedUnderOS", isStochasticCrossedUnderOS, ignoreFalseConditions, separator) + - // - "" - // - ; - - // - if (onlyCommons && !onlyConditions) - { - result += commonStr = separator; - } - else if (onlyConditions && !onlyCommons) - { - result += conditionsStr + separator; - } - else - { - // - result += - // - commonStr + separator + - conditionsStr + separator - // - ; - } - - // - return result; - } - - /** - * Retrieve nique Tag Identifier ... - * - * @return ( string ) - */ - string GetTag() - { - return GetTypeName(this); - } -}; - -// -// Helper Class Implementation ... -class XCXCAEAHelper : XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - XCPOIDrawer *poiDrawer; - XCPOIDetector *poiDetector; - - // - XCBarAnalyser *barAnalyser; - - // - XCX121XCCHelper *ccHelper; - XCX121XCTHelper *ctHelper; - XCX121XCAHelper *caHelper; - XCX121XOCSHelper *ocsHelper; - XCX121X3MAHelper *x3maHelper; - - // - // Constructor ... - XCXCAEAHelper() - { - // - barAnalyser = new XCBarAnalyser(); - } - - // - // Deconstructor ... - ~XCXCAEAHelper() - { - // - mInputs.Clean(); - - // - ZeroMemory(ccHelper); - ZeroMemory(ctHelper); - ZeroMemory(caHelper); - ZeroMemory(ocsHelper); - ZeroMemory(x3maHelper); - - // - ZeroMemory(poiDrawer); - ZeroMemory(poiDetector); - ZeroMemory(barAnalyser); - - // - IndicatorRelease(acHandler); - IndicatorRelease(adHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(atrHandler); - IndicatorRelease(cciHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(mfiHandler); - IndicatorRelease(rviHandler); - IndicatorRelease(macdHandler); - IndicatorRelease(momentumHandler); - IndicatorRelease(stochasticHandler); - } - - // - string GetSymbol() - { - return mSymbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - // - // Tools ... - - /** - * Initialize Indicator Helper ... - * - * @param symbol: String, Symbol ... - * @param period: ENUM_TIMEFRAMES member, Period ... - * @param inputs: XCAEAInputs instance, Indicator Inputs ... - * - * @return ( bool ) - */ - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XCAEAInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - result = - IsValid(symbol) && - IsValid(period) && - inputs.IsValid(); - if (!result) - { - return result; - } - - // - mSymbol = symbol; - mPeriod = period; - - // - poiDetector = new XCPOIDetector( - symbol, - period // - ); - poiDetector.Init(); - - // - poiDrawer = new XCPOIDrawer(); - - // - // Setting Inputs ... - - // - mInputs = inputs; - - // - // Initial Helpers ... - - // - // XCT ... - ctHelper = new XCX121XCTHelper(); - result = - result && - ctHelper.Init( - symbol, - period, - mInputs.ctInputs // - ); - - // - // XCC ... - ccHelper = new XCX121XCCHelper(); - result = - result && - ccHelper.Init( - symbol, - period, - mInputs.ccInputs // - ); - - // - // XCA ... - caHelper = new XCX121XCAHelper(); - result = - result && - caHelper.Init( - symbol, - period, - mInputs.caInputs // - ); - - // - // XOSC ... - ocsHelper = new XCX121XOCSHelper(); - result = - result && - ocsHelper.Init( - symbol, - period, - mInputs.oscsInputs // - ); - - // - // X3MA ... - x3maHelper = new XCX121X3MAHelper(); - result = - result && - x3maHelper.Init( - symbol, - period, - mInputs.x3maInputs // - ); - - // - if (!result) - { - // - ZeroMemory(ccHelper); - ZeroMemory(ctHelper); - ZeroMemory(caHelper); - ZeroMemory(ocsHelper); - ZeroMemory(x3maHelper); - - // - ZeroMemory(poiDrawer); - ZeroMemory(poiDetector); - - // - return result; - } - - // - // OSCILLATORS Viewers ... - - // - // AC ... - if (mInputs.showAC) - { - // - acHandler = iAC( - symbol, - period // - ); - - // - result = - result && - acHandler != INVALID_HANDLE; - } - - // - // AD ... - if (mInputs.showAD) - { - // - adHandler = iAD( - symbol, - period, - mInputs.oscsInputs.adAppliedTo // - ); - - // - result = - result && - adHandler != INVALID_HANDLE; - } - - // - // ADX ... - if (mInputs.showADX) - { - // - adxHandler = iADX( - symbol, - period, - mInputs.oscsInputs.adxLength // - ); - - // - result = - result && - adxHandler != INVALID_HANDLE; - } - - // - // ATR ... - if (mInputs.showATR) - { - // - atrHandler = iATR( - symbol, - period, - mInputs.oscsInputs.atrLength // - ); - - // - result = - result && - atrHandler != INVALID_HANDLE; - } - - // - // CCI ... - if (mInputs.showCCI) - { - // - cciHandler = iCCI( - symbol, - period, - mInputs.oscsInputs.cciLength, - mInputs.oscsInputs.cciAppliedTo // - ); - - // - result = - result && - cciHandler != INVALID_HANDLE; - } - - // - // RSI ... - if (mInputs.showRSI) - { - // - rsiHandler = iRSI( - symbol, - period, - mInputs.oscsInputs.rsiLength, - mInputs.oscsInputs.rsiAppliedTo // - ); - - // - result = - result && - rsiHandler != INVALID_HANDLE; - } - - // - // MFI ... - if (mInputs.showMFI) - { - // - mfiHandler = iMFI( - symbol, - period, - mInputs.oscsInputs.mfiLength, - mInputs.oscsInputs.mfiAppliedTo // - ); - - // - result = - result && - mfiHandler != INVALID_HANDLE; - } - - // - // RVI ... - if (mInputs.showRVI) - { - // - rviHandler = iRVI( - symbol, - period, - mInputs.oscsInputs.rviLength // - ); - - // - result = - result && - rviHandler != INVALID_HANDLE; - } - - // - // MACD ... - if (mInputs.showMACD) - { - // - macdHandler = iMACD( - symbol, - period, - mInputs.oscsInputs.macdFastLength, - mInputs.oscsInputs.macdSlowLength, - mInputs.oscsInputs.macdSignalLength, - mInputs.oscsInputs.macdAppliedTo // - ); - - // - result = - result && - macdHandler != INVALID_HANDLE; - } - - // - // Momentum ... - if (mInputs.showMomentum) - { - // - momentumHandler = iMomentum( - symbol, - period, - mInputs.oscsInputs.momentumLength, - mInputs.oscsInputs.momentumAppliedTo // - ); - - // - result = - result && - momentumHandler != INVALID_HANDLE; - } - - // - // Stochastic ... - if (mInputs.showStochastic) - { - // - stochasticHandler = iStochastic( - symbol, - period, - mInputs.oscsInputs.stochasticKLength, - mInputs.oscsInputs.stochasticDLength, - mInputs.oscsInputs.stochasticSmoothingLength, - mInputs.oscsInputs.stochasticSmoothingMethod, - mInputs.oscsInputs.stochasticAppliedTo // - ); - - // - result = - result && - stochasticHandler != INVALID_HANDLE; - } - - // - // If Result is False, Cleanup Resources ... - if (!result) - { - // - mInputs.Clean(); - - // - ZeroMemory(ccHelper); - ZeroMemory(ctHelper); - ZeroMemory(caHelper); - ZeroMemory(ocsHelper); - ZeroMemory(x3maHelper); - - // - IndicatorRelease(acHandler); - IndicatorRelease(adHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(atrHandler); - IndicatorRelease(cciHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(mfiHandler); - IndicatorRelease(rviHandler); - IndicatorRelease(macdHandler); - IndicatorRelease(momentumHandler); - IndicatorRelease(stochasticHandler); - - // - return result; - } - - // - return result; - } - - // - // Conditions Readers ... - - /** - * Retrieve Conditions ... - * - * @param conditions: Argument 1 - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Loopback looking for others ... - * - * @return ( bool ) - */ - bool Get3MAConditions( - X121X3MAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = false; - - // - result = x3maHelper.GetConditions( - conditions, - barIndex, - loopback // - ); - - // - return result; - } - - /** - * Retrieve Conditions ... - * - * @param conditions: Argument 1 - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Loopback looking for others ... - * - * @return ( bool ) - */ - bool GetCAConditions( - X121XCAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = false; - - // - result = caHelper.GetConditions( - conditions, - barIndex, - loopback // - ); - - // - return result; - } - - /** - * Retrieve Conditions ... - * - * @param conditions: Argument 1 - * @param barIndex: int, Specified Bar Index ... - * @param loopback: int, Loopback looking for others ... - * - * @return ( bool ) - */ - bool GetOSCSConditions( - X121XOCSConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = false; - - // - result = ocsHelper.GetConditions( - conditions, - barIndex, - loopback // - ); - - // - return result; - } - - // - // Others ... - - // - void Free() - { - // - caHelper.Free(); - ocsHelper.Free(); - x3maHelper.Free(); - } - - // - bool GetConditions( - XCAEAConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = true; - - // - if (loopback < 5) - { - loopback = 5; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - // Filling Bars ... - int barsCount = GetBars( - conditions.bars, - mSymbol, - mPeriod, - barIndex, - loopback // - ); - result = barsCount == loopback; - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - // Reading Bars Conditions ... - XOHCL iBar; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - for (int i = 0; i < ArraySize(conditions.bars); i++) - { - // - iBar = conditions.bars[i]; - - // - // Reading Bars Patterns ... - - // - // Rejection ... - bool isRejected = - barAnalyser - .IsRejected( - iBar, - iDir, - false, - true // - ); - bool isBullishRejected = - isRejected && - IsBullish(iDir); - bool isBearishRejected = - isRejected && - IsBearish(iDir); - - // - Add( - isBullishRejected, - conditions.bullishRejectedBars // - ); - - // - Add( - isBearishRejected, - conditions.bearishRejectedBars // - ); - - // - // Engulfing ... - bool isEngulfed = - barAnalyser - .IsEngulfed( - iBar, - iDir // - ); - bool isBullishEngulfed = - isEngulfed && - IsBullish(iDir); - bool isBearishEngulfed = - isEngulfed && - IsBearish(iDir); - - // - Add( - isBullishEngulfed, - conditions.bullishEngulfedBars // - ); - - // - Add( - isBearishEngulfed, - conditions.bearishEngulfedBars // - ); - - // - // Momentum ... - bool isMomentum = - barAnalyser - .IsMomentum( - iBar, - iDir, - 1 // - ); - bool isBullishMomentum = - isMomentum && - IsBullish(iDir); - bool isBearishMomentum = - isMomentum && - IsBearish(iDir); - - // - iBar.Clean(); - } - iBar.Clean(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL fromBar; - - // - X121XCAConditions xcaConditions; - X121XOCSConditions xocsConditions; - X121X3MAConditions x3maConditions; - - // - result = zBar.Init( - mSymbol, - mPeriod, - zIndex // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - fromBar.Init( - zBar.symbol, - zBar.period, - zIndex + loopback - 1); - - // - // Conditions Retriever ... - - // - // XCA ... - result = - result && - GetCAConditions( - xcaConditions, - barIndex, - loopback // - ); - - // - // XOSCS ... - result = - result && - GetOSCSConditions( - xocsConditions, - barIndex, - loopback // - ); - - // - // X3MA ... - result = - result && - Get3MAConditions( - x3maConditions, - barIndex, - loopback // - ); - - // - // Check Result ... - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - fromBar.Clean(); - - // - xcaConditions.Clean(); - xocsConditions.Clean(); - x3maConditions.Clean(); - - // - return result; - } - - // - conditions.to = zBar.time; - conditions.from = fromBar.time; - - // - // Fill X121 Conditions Reference by Using - // Retrieved Conditions ... - - // - int cIDX = 1; - int pIDX = cIDX + 1; - - // - // X3MA ... - - // - // Buffers ... - - // - Copy( - x3maConditions.fastBuffer, - conditions.fastBuffer // - ); - - // - Copy( - x3maConditions.mediumBuffer, - conditions.mediumBuffer // - ); - - // - Copy( - x3maConditions.slowBuffer, - conditions.slowBuffer // - ); - - // - Copy( - x3maConditions.fastStateBuffer, - conditions.fastStateBuffer // - ); - - // - Copy( - x3maConditions.mediumStateBuffer, - conditions.mediumStateBuffer // - ); - - // - Copy( - x3maConditions.slowStateBuffer, - conditions.slowStateBuffer // - ); - - // - // Conditions ... - - // - conditions.is3MaBullish = x3maConditions.is3MaBullish; - conditions.is3MaBearish = x3maConditions.is3MaBearish; - conditions.isFastOverSlow = x3maConditions.isFastOverSlow; - conditions.isFastUnderSlow = x3maConditions.isFastUnderSlow; - conditions.isFastOverMedium = x3maConditions.isFastOverMedium; - conditions.isMediumOverSlow = x3maConditions.isMediumOverSlow; - conditions.isFastUnderMedium = x3maConditions.isFastUnderMedium; - conditions.isMediumUnderSlow = x3maConditions.isMediumUnderSlow; - conditions.is3MaBullishState = x3maConditions.is3MaBullishState; - conditions.is3MaBearishState = x3maConditions.is3MaBearishState; - conditions.is3MaBullishOrdered = x3maConditions.is3MaBullishOrdered; - conditions.is3MaBearishOrdered = x3maConditions.is3MaBearishOrdered; - conditions.isFastCrossedOverSlow = x3maConditions.isFastCrossedOverSlow; - conditions.is3MaSwitchedToBullish = x3maConditions.is3MaSwitchedToBullish; - conditions.is3MaSwitchedToBearish = x3maConditions.is3MaSwitchedToBearish; - conditions.isFastCrossedUnderSlow = x3maConditions.isFastCrossedUnderSlow; - conditions.isFastCrossedOverMedium = x3maConditions.isFastCrossedOverMedium; - conditions.isMediumCrossedOverSlow = x3maConditions.isMediumCrossedOverSlow; - conditions.is3MaFinishedFromBullish = x3maConditions.is3MaFinishedFromBullish; - conditions.is3MaFinishedFromBearish = x3maConditions.is3MaFinishedFromBearish; - conditions.isFastCrossedUnderMedium = x3maConditions.isFastCrossedUnderMedium; - conditions.isMediumCrossedUnderSlow = x3maConditions.isMediumCrossedUnderSlow; - conditions.is3MaSwitchedToBullishState = x3maConditions.is3MaSwitchedToBullishState; - conditions.is3MaSwitchedToBearishState = x3maConditions.is3MaSwitchedToBearishState; - conditions.is3MaSwitchedToBullishOrdered = x3maConditions.is3MaSwitchedToBullishOrdered; - conditions.is3MaSwitchedToBearishOrdered = x3maConditions.is3MaSwitchedToBearishOrdered; - - // - // XCA ... - - // - // Buffers ... - - // - Copy( - xcaConditions.kiBuffer, - conditions.kiBuffer // - ); - - // - Copy( - xcaConditions.tkiBuffer, - conditions.tkiBuffer // - ); - - // - Copy( - xcaConditions.vidyaBuffer, - conditions.vidyaBuffer // - ); - - // - Copy( - xcaConditions.sHHBuffer, - conditions.sHHBuffer // - ); - - // - Copy( - xcaConditions.sLLBuffer, - conditions.sLLBuffer // - ); - - // - Copy( - xcaConditions.mHHBuffer, - conditions.mHHBuffer // - ); - - // - Copy( - xcaConditions.mLLBuffer, - conditions.mLLBuffer // - ); - - // - Copy( - xcaConditions.lHHBuffer, - conditions.lHHBuffer // - ); - - // - Copy( - xcaConditions.lLLBuffer, - conditions.lLLBuffer // - ); - - // - Copy( - xcaConditions.hHHBuffer, - conditions.hHHBuffer // - ); - - // - Copy( - xcaConditions.hLLBuffer, - conditions.hLLBuffer // - ); - - // - Copy( - xcaConditions.sarBuffer, - conditions.sarBuffer // - ); - - // - Copy( - xcaConditions.mahBuffer, - conditions.mahBuffer // - ); - - // - Copy( - xcaConditions.malBuffer, - conditions.malBuffer // - ); - - // - Copy( - xcaConditions.macBuffer, - conditions.macBuffer // - ); - - // - Copy( - xcaConditions.peakBuffer, - conditions.peakBuffer // - ); - - // - Copy( - xcaConditions.valeBuffer, - conditions.valeBuffer // - ); - - // - Copy( - xcaConditions.trendBuffer, - conditions.trendBuffer // - ); - - // - Copy( - xcaConditions.kiStateBuffer, - conditions.kiStateBuffer // - ); - - // - Copy( - xcaConditions.tkiStateBuffer, - conditions.tkiStateBuffer // - ); - - // - Copy( - xcaConditions.vidyaStateBuffer, - conditions.vidyaStateBuffer // - ); - - // - Copy( - xcaConditions.supportBuffer, - conditions.supportBuffer // - ); - - // - Copy( - xcaConditions.swingLowBuffer, - conditions.swingLowBuffer // - ); - - // - Copy( - xcaConditions.swingHighBuffer, - conditions.swingHighBuffer // - ); - - // - Copy( - xcaConditions.resistanceBuffer, - conditions.resistanceBuffer // - ); - - // - Copy( - xcaConditions.peakGoldenBuffer, - conditions.peakGoldenBuffer // - ); - - // - Copy( - xcaConditions.valeGoldenBuffer, - conditions.valeGoldenBuffer // - ); - - // - Copy( - xcaConditions.fiboLevel1Buffer, - conditions.fiboLevel1Buffer // - ); - - // - Copy( - xcaConditions.fiboLevel2Buffer, - conditions.fiboLevel2Buffer // - ); - - // - Copy( - xcaConditions.fiboLevel3Buffer, - conditions.fiboLevel3Buffer // - ); - - // - Copy( - xcaConditions.fiboLevel4Buffer, - conditions.fiboLevel4Buffer // - ); - - // - Copy( - xcaConditions.fiboLevel5Buffer, - conditions.fiboLevel5Buffer // - ); - - // - Copy( - xcaConditions.trendStateBuffer, - conditions.trendStateBuffer // - ); - - // - // Conditions ... - - // - conditions.isOverMah = xcaConditions.isOverMah; - conditions.isOverMal = xcaConditions.isOverMal; - conditions.isOverMac = xcaConditions.isOverMac; - conditions.isUnderMah = xcaConditions.isUnderMah; - conditions.isUnderMal = xcaConditions.isUnderMal; - conditions.isUnderMac = xcaConditions.isUnderMac; - conditions.isKIBullish = xcaConditions.isKIBullish; - conditions.isKIBearish = xcaConditions.isKIBearish; - conditions.isKIRejectUp = xcaConditions.isKIRejectUp; - conditions.isTKIBullish = xcaConditions.isTKIBullish; - conditions.isTKIBearish = xcaConditions.isTKIBearish; - conditions.isSarBullish = xcaConditions.isSarBullish; - conditions.isSarBearish = xcaConditions.isSarBearish; - conditions.isTKIRejectUp = xcaConditions.isTKIRejectUp; - conditions.isPeakIsPivot = xcaConditions.isPeakIsPivot; - conditions.isValeIsPivot = xcaConditions.isValeIsPivot; - conditions.isCloseOverMah = xcaConditions.isCloseOverMah; - conditions.isCloseOverMal = xcaConditions.isCloseOverMal; - conditions.isCloseOverMac = xcaConditions.isCloseOverMac; - conditions.isVidyaBullish = xcaConditions.isVidyaBullish; - conditions.isVidyaBearish = xcaConditions.isVidyaBearish; - conditions.isKIRejectDown = xcaConditions.isKIRejectDown; - conditions.isPeakSameLast = xcaConditions.isPeakSameLast; - conditions.isPeakOverLast = xcaConditions.isPeakOverLast; - conditions.isValeSameLast = xcaConditions.isValeSameLast; - conditions.isValeOverLast = xcaConditions.isValeOverLast; - conditions.isTrendBullish = xcaConditions.isTrendBullish; - conditions.isTrendBearish = xcaConditions.isTrendBearish; - conditions.isCloseUnderMah = xcaConditions.isCloseUnderMah; - conditions.isCloseUnderMal = xcaConditions.isCloseUnderMal; - conditions.isCloseUnderMac = xcaConditions.isCloseUnderMac; - conditions.isTKIRejectDown = xcaConditions.isTKIRejectDown; - conditions.isPeakUnderLast = xcaConditions.isPeakUnderLast; - conditions.isValeUnderLast = xcaConditions.isValeUnderLast; - conditions.isTrendRejectUp = xcaConditions.isTrendRejectUp; - conditions.isCrossedOverMah = xcaConditions.isCrossedOverMah; - conditions.isCrossedOverMal = xcaConditions.isCrossedOverMal; - conditions.isCrossedOverMac = xcaConditions.isCrossedOverMac; - conditions.isCrossedUnderMah = xcaConditions.isCrossedUnderMah; - conditions.isCrossedUnderMal = xcaConditions.isCrossedUnderMal; - conditions.isCrossedUnderMac = xcaConditions.isCrossedUnderMac; - conditions.isTrendRejectDown = xcaConditions.isTrendRejectDown; - conditions.isSupportSameLast = xcaConditions.isSupportSameLast; - conditions.isSupportOverLast = xcaConditions.isSupportOverLast; - conditions.isSupportUnderLast = xcaConditions.isSupportUnderLast; - conditions.isSwingLowSameLast = xcaConditions.isSwingLowSameLast; - conditions.isSwingLowOverLast = xcaConditions.isSwingLowOverLast; - conditions.isSwingLowUnderLast = xcaConditions.isSwingLowUnderLast; - conditions.isSwingHighSameLast = xcaConditions.isSwingHighSameLast; - conditions.isSwingHighOverLast = xcaConditions.isSwingHighOverLast; - conditions.isSupportSameAsVale = xcaConditions.isSupportSameAsVale; - conditions.isMahBullishRejected = xcaConditions.isMahBullishRejected; - conditions.isMahBearishRejected = xcaConditions.isMahBearishRejected; - conditions.isMalBullishRejected = xcaConditions.isMalBullishRejected; - conditions.isMalBearishRejected = xcaConditions.isMalBearishRejected; - conditions.isMacBullishRejected = xcaConditions.isMacBullishRejected; - conditions.isMacBearishRejected = xcaConditions.isMacBearishRejected; - conditions.isLastSupportBreaked = xcaConditions.isLastSupportBreaked; - conditions.isResistanceSameLast = xcaConditions.isResistanceSameLast; - conditions.isResistanceOverLast = xcaConditions.isResistanceOverLast; - conditions.isSwingHighUnderLast = xcaConditions.isSwingHighUnderLast; - conditions.isSwingLowSameAsVale = xcaConditions.isSwingLowSameAsVale; - conditions.isCloseCrossedOverMah = xcaConditions.isCloseCrossedOverMah; - conditions.isCloseCrossedOverMal = xcaConditions.isCloseCrossedOverMal; - conditions.isCloseCrossedOverMac = xcaConditions.isCloseCrossedOverMac; - conditions.isLastSupportRejected = xcaConditions.isLastSupportRejected; - conditions.isResistanceUnderLast = xcaConditions.isResistanceUnderLast; - conditions.isKISwitchedToBullish = xcaConditions.isKISwitchedToBullish; - conditions.isKISwitchedToBearish = xcaConditions.isKISwitchedToBearish; - conditions.isLastSwingLowBreaked = xcaConditions.isLastSwingLowBreaked; - conditions.isSwingHighSameAsPeak = xcaConditions.isSwingHighSameAsPeak; - conditions.isPeakSwitchedToPivot = xcaConditions.isPeakSwitchedToPivot; - conditions.isValeSwitchedToPivot = xcaConditions.isValeSwitchedToPivot; - conditions.isCloseCrossedUnderMah = xcaConditions.isCloseCrossedUnderMah; - conditions.isCloseCrossedUnderMal = xcaConditions.isCloseCrossedUnderMal; - conditions.isCloseCrossedUnderMac = xcaConditions.isCloseCrossedUnderMac; - conditions.isTKISwitchedToBullish = xcaConditions.isTKISwitchedToBullish; - conditions.isTKISwitchedToBearish = xcaConditions.isTKISwitchedToBearish; - conditions.isLastSwingLowRejected = xcaConditions.isLastSwingLowRejected; - conditions.isSarSwitchedToBullish = xcaConditions.isSarSwitchedToBullish; - conditions.isSarSwitchedToBearish = xcaConditions.isSarSwitchedToBearish; - conditions.isLastSwingHighBreaked = xcaConditions.isLastSwingHighBreaked; - conditions.isResistanceSameAsPeak = xcaConditions.isResistanceSameAsPeak; - conditions.isPeakFinishedFromPivot = xcaConditions.isPeakFinishedFromPivot; - conditions.isValeFinishedFromPivot = xcaConditions.isValeFinishedFromPivot; - conditions.isLastSwingHighRejected = xcaConditions.isLastSwingHighRejected; - conditions.isLastResistanceBreaked = xcaConditions.isLastResistanceBreaked; - conditions.isSupportSameAsSwingLow = xcaConditions.isSupportSameAsSwingLow; - conditions.isKIFinishedFromBullish = xcaConditions.isKIFinishedFromBullish; - conditions.isKIFinishedFromBearish = xcaConditions.isKIFinishedFromBearish; - conditions.isTKIFinishedFromBullish = xcaConditions.isTKIFinishedFromBullish; - conditions.isTKIFinishedFromBearish = xcaConditions.isTKIFinishedFromBearish; - conditions.isSarFinishedFromBullish = xcaConditions.isSarFinishedFromBullish; - conditions.isSarFinishedFromBearish = xcaConditions.isSarFinishedFromBearish; - conditions.isVidyaSwitchedToBullish = xcaConditions.isVidyaSwitchedToBullish; - conditions.isVidyaSwitchedToBearish = xcaConditions.isVidyaSwitchedToBearish; - conditions.isLastResistanceRejected = xcaConditions.isLastResistanceRejected; - conditions.isTrendSwitchedToBullish = xcaConditions.isTrendSwitchedToBullish; - conditions.isTrendSwitchedToBearish = xcaConditions.isTrendSwitchedToBearish; - conditions.isVidyaFinishedFromBullish = xcaConditions.isVidyaFinishedFromBullish; - conditions.isVidyaFinishedFromBearish = xcaConditions.isVidyaFinishedFromBearish; - conditions.isTrendFinishedFromBullish = xcaConditions.isTrendFinishedFromBullish; - conditions.isTrendFinishedFromBearish = xcaConditions.isTrendFinishedFromBearish; - conditions.isResistanceSameAsSwingHigh = xcaConditions.isResistanceSameAsSwingHigh; - - // - // XOSCS ... - - // - // Buffers ... - - // - Copy( - xocsConditions.acBuffer, - conditions.acBuffer // - ); - - // - Copy( - xocsConditions.adBuffer, - conditions.adBuffer // - ); - - // - Copy( - xocsConditions.atrBuffer, - conditions.atrBuffer // - ); - - // - Copy( - xocsConditions.cciBuffer, - conditions.cciBuffer // - ); - - // - Copy( - xocsConditions.rsiBuffer, - conditions.rsiBuffer // - ); - - // - Copy( - xocsConditions.mfiBuffer, - conditions.mfiBuffer // - ); - - // - Copy( - xocsConditions.rviBuffer, - conditions.rviBuffer // - ); - - // - Copy( - xocsConditions.adxBuffer, - conditions.adxBuffer // - ); - - // - Copy( - xocsConditions.adxpBuffer, - conditions.adxpBuffer // - ); - - // - Copy( - xocsConditions.adxnBuffer, - conditions.adxnBuffer // - ); - - // - Copy( - xocsConditions.macdBuffer, - conditions.macdBuffer // - ); - - // - Copy( - xocsConditions.momentumBuffer, - conditions.momentumBuffer // - ); - - // - Copy( - xocsConditions.rviSignalBuffer, - conditions.rviSignalBuffer // - ); - - // - Copy( - xocsConditions.macdSignalBuffer, - conditions.macdSignalBuffer // - ); - - // - Copy( - xocsConditions.stochasticBuffer, - conditions.stochasticBuffer // - ); - - // - Copy( - xocsConditions.stochasticSignalBuffer, - conditions.stochasticSignalBuffer // - ); - - // - // Values ... - - // - conditions.adxThreshold = xocsConditions.adxThreshold; - conditions.cciOBLevel = xocsConditions.cciOBLevel; - conditions.cciOSLevel = xocsConditions.cciOSLevel; - conditions.cciReversalLevel = xocsConditions.cciReversalLevel; - conditions.rsiOBLevel = xocsConditions.rsiOBLevel; - conditions.rsiOSLevel = xocsConditions.rsiOSLevel; - conditions.rsiReversalLevel = xocsConditions.rsiReversalLevel; - conditions.mfiOBLevel = xocsConditions.mfiOBLevel; - conditions.mfiOSLevel = xocsConditions.mfiOSLevel; - conditions.mfiReversalLevel = xocsConditions.mfiReversalLevel; - conditions.rviBullishLevel = xocsConditions.rviBullishLevel; - conditions.rviBearishLevel = xocsConditions.rviBearishLevel; - conditions.macdBullishLevel = xocsConditions.macdBullishLevel; - conditions.macdBearishLevel = xocsConditions.macdBearishLevel; - conditions.momentumBullishLevel = xocsConditions.momentumBullishLevel; - conditions.momentumBearishLevel = xocsConditions.momentumBearishLevel; - conditions.stochasticOBLevel = xocsConditions.stochasticOBLevel; - conditions.stochasticOSLevel = xocsConditions.stochasticOSLevel; - conditions.stochasticReversalLevel = xocsConditions.stochasticReversalLevel; - - // - // Conditions ... - - // - conditions.isCCIOB = xocsConditions.isCCIOB; - conditions.isCCIOS = xocsConditions.isCCIOS; - conditions.isRSIOB = xocsConditions.isRSIOB; - conditions.isRSIOS = xocsConditions.isRSIOS; - conditions.isMFIOB = xocsConditions.isMFIOB; - conditions.isMFIOS = xocsConditions.isMFIOS; - conditions.isACBullish = xocsConditions.isACBullish; - conditions.isACBearish = xocsConditions.isACBearish; - conditions.isACOverMax = xocsConditions.isACOverMax; - conditions.isADOverMax = xocsConditions.isADOverMax; - conditions.isACUnderMin = xocsConditions.isACUnderMin; - conditions.isADUnderMin = xocsConditions.isADUnderMin; - conditions.isADXBullish = xocsConditions.isADXBullish; - conditions.isADXBearish = xocsConditions.isADXBearish; - conditions.isCCIBullish = xocsConditions.isCCIBullish; - conditions.isCCIBearish = xocsConditions.isCCIBearish; - conditions.isRSIBullish = xocsConditions.isRSIBullish; - conditions.isRSIBearish = xocsConditions.isRSIBearish; - conditions.isMFIBullish = xocsConditions.isMFIBullish; - conditions.isMFIBearish = xocsConditions.isMFIBearish; - conditions.isRVIBullish = xocsConditions.isRVIBullish; - conditions.isRVIBearish = xocsConditions.isRVIBearish; - conditions.isATROverLast = xocsConditions.isATROverLast; - conditions.isMACDBullish = xocsConditions.isMACDBullish; - conditions.isMACDBearish = xocsConditions.isMACDBearish; - conditions.isATRUnderLast = xocsConditions.isATRUnderLast; - conditions.isADBiggerLast = xocsConditions.isADBiggerLast; - conditions.isADLesserLast = xocsConditions.isADLesserLast; - conditions.isStochasticOB = xocsConditions.isStochasticOB; - conditions.isStochasticOS = xocsConditions.isStochasticOS; - conditions.isADXBiggerLast = xocsConditions.isADXBiggerLast; - conditions.isADXLesserLast = xocsConditions.isADXLesserLast; - conditions.isRVIOverSignal = xocsConditions.isRVIOverSignal; - conditions.isRVIUnderSignal = xocsConditions.isRVIUnderSignal; - conditions.isMACDOverSignal = xocsConditions.isMACDOverSignal; - conditions.isMACDUnderSignal = xocsConditions.isMACDUnderSignal; - conditions.isMomentumBullish = xocsConditions.isMomentumBullish; - conditions.isMomentumBearish = xocsConditions.isMomentumBearish; - conditions.isADXOverThreshold = xocsConditions.isADXOverThreshold; - conditions.isDXPBiggerThanDXN = xocsConditions.isDXPBiggerThanDXN; - conditions.isDXNBiggerThanDXP = xocsConditions.isDXNBiggerThanDXP; - conditions.isCCICrossedOverOB = xocsConditions.isCCICrossedOverOB; - conditions.isCCICrossedOverOS = xocsConditions.isCCICrossedOverOS; - conditions.isRSICrossedOverOB = xocsConditions.isRSICrossedOverOB; - conditions.isRSICrossedOverOS = xocsConditions.isRSICrossedOverOS; - conditions.isMFICrossedOverOB = xocsConditions.isMFICrossedOverOB; - conditions.isMFICrossedOverOS = xocsConditions.isMFICrossedOverOS; - conditions.isADXUnderThreshold = xocsConditions.isADXUnderThreshold; - conditions.isCCICrossedUnderOB = xocsConditions.isCCICrossedUnderOB; - conditions.isCCICrossedUnderOS = xocsConditions.isCCICrossedUnderOS; - conditions.isRSICrossedUnderOB = xocsConditions.isRSICrossedUnderOB; - conditions.isRSICrossedUnderOS = xocsConditions.isRSICrossedUnderOS; - conditions.isMFICrossedUnderOB = xocsConditions.isMFICrossedUnderOB; - conditions.isMFICrossedUnderOS = xocsConditions.isMFICrossedUnderOS; - conditions.isStochasticBullish = xocsConditions.isStochasticBullish; - conditions.isStochasticBearish = xocsConditions.isStochasticBearish; - conditions.isACSwitchedToBullish = xocsConditions.isACSwitchedToBullish; - conditions.isACSwitchedToBearish = xocsConditions.isACSwitchedToBearish; - conditions.isADXSwitchedToBullish = xocsConditions.isADXSwitchedToBullish; - conditions.isADXSwitchedToBearish = xocsConditions.isADXSwitchedToBearish; - conditions.isCCISwitchedToBullish = xocsConditions.isCCISwitchedToBullish; - conditions.isCCISwitchedToBearish = xocsConditions.isCCISwitchedToBearish; - conditions.isRSISwitchedToBullish = xocsConditions.isRSISwitchedToBullish; - conditions.isRSISwitchedToBearish = xocsConditions.isRSISwitchedToBearish; - conditions.isMFISwitchedToBullish = xocsConditions.isMFISwitchedToBullish; - conditions.isMFISwitchedToBearish = xocsConditions.isMFISwitchedToBearish; - conditions.isRVISwitchedToBullish = xocsConditions.isRVISwitchedToBullish; - conditions.isRVISwitchedToBearish = xocsConditions.isRVISwitchedToBearish; - conditions.isRVICrossedOverSignal = xocsConditions.isRVICrossedOverSignal; - conditions.isStochasticOverSignal = xocsConditions.isStochasticOverSignal; - conditions.isStochasticUnderSignal = xocsConditions.isStochasticUnderSignal; - conditions.isRVICrossedUnderSignal = xocsConditions.isRVICrossedUnderSignal; - conditions.isMACDSwitchedToBullish = xocsConditions.isMACDSwitchedToBullish; - conditions.isMACDSwitchedToBearish = xocsConditions.isMACDSwitchedToBearish; - conditions.isMACDCrossedOverSignal = xocsConditions.isMACDCrossedOverSignal; - conditions.isMACDCrossedUnderSignal = xocsConditions.isMACDCrossedUnderSignal; - conditions.isStochasticCrossedOverOB = xocsConditions.isStochasticCrossedOverOB; - conditions.isStochasticCrossedOverOS = xocsConditions.isStochasticCrossedOverOS; - conditions.isStochasticCrossedUnderOB = xocsConditions.isStochasticCrossedUnderOB; - conditions.isStochasticCrossedUnderOS = xocsConditions.isStochasticCrossedUnderOS; - conditions.isMomentumSwitchedToBullish = xocsConditions.isMomentumSwitchedToBullish; - conditions.isMomentumSwitchedToBearish = xocsConditions.isMomentumSwitchedToBearish; - conditions.isStochasticSwitchedToBullish = xocsConditions.isStochasticSwitchedToBullish; - conditions.isStochasticSwitchedToBearish = xocsConditions.isStochasticSwitchedToBearish; - conditions.isStochasticCrossedOverSignal = xocsConditions.isStochasticCrossedOverSignal; - conditions.isStochasticCrossedUnderSignal = xocsConditions.isStochasticCrossedUnderSignal; - - // - int bodiesCount = barAnalyser.GetPriceRange( - conditions.bodies, - zBar, - true, // Force Body ... - true, // Force Price Diff ... - loopback // - ); - int rangesCount = barAnalyser.GetPriceRange( - conditions.ranges, - zBar, - true, // Force Body ... - true, // Force Price Diff ... - loopback // - ); - - // - int velocitiesCount = - barAnalyser - .GetPriceVelocity( - conditions.velocities, - zBar, - X_PRICE_CLOSE, - loopback // - ); - - // - double bullishVolume = 0.0; - double bearishVolume = 0.0; - barAnalyser - .CalculateRangeVolume( - zBar, - bullishVolume, - bearishVolume, - loopback // - ); - conditions.scoreBullish = bullishVolume; - conditions.scoreBearish = bearishVolume; - - // - double bullishScore = 0.0; - double bearishScore = 0.0; - conditions.GenerateScore( - bullishScore, - bearishScore // - ); - conditions.volumeBullish = bullishScore; - conditions.volumeBearish = bearishScore; - - // - double priceChangeRate = - barAnalyser - .GetPriceChangeRate( - zBar, - X_PRICE_CLOSE, - loopback // - ); - conditions.priceChangeRate = priceChangeRate; - - // - // Cleanup Resource ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - fromBar.Clean(); - - // - xcaConditions.Clean(); - xocsConditions.Clean(); - x3maConditions.Clean(); - - // - Free(); - - // - return result; - } - - // - bool IsBlockBasedTriggerBar( - XBoxZone &ob, - XOHCL &swingBar, - XOHCL &breakerBar, - XOHCL &outSideBar, - ENUM_X_DIRECTION &dir, - int barIndex = 0, - int loopback = 40, - int swingLength = 3 // - ) - { - // - bool result = false; - - // - // Normalize Args ... - ob.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 30); - - // - // Initializing Current Bar ... - XOHCL bar; - result = bar.Init( - GetSymbol(), - GetPeriod(), - barIndex // - ); - if (!result) - { - // - ob.Clean(); - bar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // Detecting Newest Block ... - XOHCL iBar; - bool has = false; - for (int i = barIndex; i < barIndex + loopback; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - - // - continue; - } - - // - // Check to Find OB ... - has = barAnalyser.IsOB( - iBar, - ob, - false, - true // - ); - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - ob.Clean(); - iBar.Clean(); - } - - // - // Ensure We Have a Block ... - result = ob.IsValid(); - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // Set Direction ... - dir = ob.dir; - int toIDX = ob.ToIndex(); - int fromIDX = ob.FromIndex(); - bool isBullish = IsBullish(dir); - bool isBearish = IsBearish(dir); - - // - // Ensure a Swing Breaked in Block Formation ... - // for Bullish we have to Breake a Swing High ... - // for Bearish we have to Detect a Swing Low ... - // this Breaktion must appear after Block ... - ENUM_X_DIRECTION swingDir = X_DIRECTION_NONE; - for (int i = barIndex + loopback; i > barIndex; i--) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - swingBar.Clean(); - swingDir = X_DIRECTION_NONE; - - // - continue; - } - - // - // Detecting Swing ... - has = barAnalyser.IsSwing( - iBar, - swingDir // - ); - has = - has && - iBar.GetPreviousBar(swingBar); - if (!has) - { - // - iBar.Clean(); - swingBar.Clean(); - swingDir = X_DIRECTION_NONE; - - // - continue; - } - - // - // Validate Founded Swing ... - - // - bool isValidSwingLow = - isBearish && - IsBullish(swingDir); - - // - bool isValidSwingHigh = - isBullish && - IsBearish(swingDir); - - // - has = - isValidSwingLow || - isValidSwingHigh; - if (!has) - { - // - iBar.Clean(); - swingBar.Clean(); - swingDir = X_DIRECTION_NONE; - - // - continue; - } - - // - // Validating Swing Place ... - - // - bool isSwingLowHasValidPlace = - isBearish && - swingBar.low < ob.lower; - - // - bool isSwingHighHasValidPlace = - isBullish && - swingBar.high > ob.upper; - - // - has = - isSwingLowHasValidPlace || - isSwingHighHasValidPlace; - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - iBar.Clean(); - swingBar.Clean(); - swingDir = X_DIRECTION_NONE; - } - - // - result = - swingBar.IsValid() && - HasDirection(swingDir); - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // now We have Proper Swing ... - // Validate Swing Breaktion ... - double breakPrice = - IsBullish(swingDir) - ? swingBar.low - : swingBar.high; - ENUM_X_DIRECTION breakedDir = - IsBullish(swingDir) - ? X_DIRECTION_BEARISH - : X_DIRECTION_BULLISH; - for (int i = swingBar.Index(); i > barIndex; i--) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - breakerBar.Clean(); - - // - continue; - } - - // - // Check for Breakes ... - has = iBar.IsBreaked( - breakPrice, - breakedDir // - ); - if (!has) - { - // - iBar.Clean(); - breakerBar.Clean(); - - // - continue; - } - - // - // Validate Swing Break must be happens - // after Block Formation ... - has = iBar.time > ob.to; - if (has) - { - // - breakerBar = iBar; - - // - iBar.Clean(); - - // - break; - } - - // - iBar.Clean(); - breakerBar.Clean(); - } - - // - result = breakerBar.IsValid(); - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // now we have a Valid Bloc ... - // which Breakes a Valid Swing ... - - // - // find at least on out side of Block Bar ... - for (int i = toIDX; i > barIndex; i--) - { - // - // Initialize iBar ... - has = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - outSideBar.Clean(); - - // - continue; - } - - // - bool isBullishOutside = - isBullish && - iBar.high > ob.upper; - - // - bool isBearishOutside = - isBearish && - iBar.low < ob.lower; - - // - has = - isBullishOutside || - isBearishOutside; - if (has) - { - // - outSideBar = iBar; - - // - iBar.Clean(); - - // - break; - } - - // - iBar.Clean(); - outSideBar.Clean(); - } - - // - result = outSideBar.IsValid(); - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // we Are Looking for Bar inside Block ... - - // - bool isBullishInside = - isBullish && - bar.low < ob.upper && - bar.low > ob.lower; - - // - bool isBearishInside = - isBearish && - bar.high > ob.lower && - bar.high < ob.upper; - - // - result = isBullishInside || - isBearishInside; - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - // Since we Ensure have an Inside Block Bar here ... - // must to detect a Bar Pattern verification for Triggering ... - - // - // Check Bar Pattern for Position ... - ENUM_X_DIRECTION patternDir; - - // - // Hammer ... - bool isHammer = barAnalyser.IsHammer( - bar, - patternDir // - ); - bool isBullishHammer = - isHammer && - IsBullish(patternDir); - bool isBearishHammer = - isHammer && - IsBearish(patternDir); - - // - // Reject ... - bool isReject = barAnalyser.IsRejected( - bar, - patternDir, - false, // Force Bar type ... - true // Force Fibo Pressure ... - ); - bool isBullishReject = - isReject && - IsBullish(patternDir); - bool isBearishReject = - isReject && - IsBearish(patternDir); - - // - // Engulf ... - bool isEngulf = barAnalyser.IsEngulfed( - bar, - patternDir // - ); - bool isBullishEngulf = - isEngulf && - IsBullish(patternDir); - bool isBearishEngulf = - isEngulf && - IsBearish(patternDir); - - // - bool isBarBullishPowered = - isBullishHammer || - isBullishReject || - isBullishEngulf; - - // - bool isBarBearishPowered = - isBearishHammer || - isBearishReject || - isBearishEngulf; - - // - // Summarizing Result ... - - // - bool isBullishTriggered = - isBullish && - isBullishInside && - isBarBullishPowered; - - // - bool isBearishTriggered = - isBearish && - isBearishInside && - isBarBearishPowered; - - // - result = isBullishTriggered || - isBearishTriggered; - - // - if (!result) - { - // - ob.Clean(); - bar.Clean(); - iBar.Clean(); - swingBar.Clean(); - breakerBar.Clean(); - outSideBar.Clean(); - dir = X_DIRECTION_NONE; - - // - return result; - } - - // - bar.Clean(); - - // - return result; - } - - // - // Protected ... - protected: - // - // Private ... - private: - // - // Props ... - - // - string mSymbol; // Trading Symbol - ENUM_TIMEFRAMES mPeriod; // Trading Period - - // - // Inputs ... - XCAEAInputs mInputs; - - // - // Handlers ... - int acHandler; - int adHandler; - int adxHandler; - int atrHandler; - int cciHandler; - int rsiHandler; - int mfiHandler; - int rviHandler; - int macdHandler; - int momentumHandler; - int stochasticHandler; -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Libraries/xcaea.signaller.lib.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Libraries/xcaea.signaller.lib.mq5 deleted file mode 100644 index 58480f6b..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Libraries/xcaea.signaller.lib.mq5 +++ /dev/null @@ -1,2927 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCAEASignaller Lib -// Description: Library for XCAEA Signaller ... -// -// -// 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 Library for XCAEA Signaller" -#property strict - -// -// Imports ... -#include "../../Libraries/x-saherelm.common.lib.mq5" -#include "../../Libraries/x-saherelm.x-poi.lib.mq5" -#include "../../Libraries/x-saherelm.x-trade.lib.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" -#include "../Classes/xcaea.x-poi.drawer.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Enumeration ... - -// -// Guard Actions ... -enum ENUM_GUARD_ACTIONS -{ - X_GUARD_ACTION_NONE, // Nothing to Do - X_GUARD_ACTION_CLOSE, // Close Specified Position - X_GUARD_ACTION_CLOSE_ALL, // Close All Positions - X_GUARD_ACTION_CLOSE_LONGS, // Close All Long Positions - X_GUARD_ACTION_CLOSE_SHORTS, // Close All Short Position - X_GUARD_ACTION_PARTIAL_CLOSE, // Partial Close Specified Position - X_GUARD_ACTION_TRAIL_STOP, // Trail Stop of Specified Position - X_GUARD_ACTION_TRAIL_TARGET, // Trail Target of Specified Position - X_GUARD_ACTION_HEDGE, // Hedge Specified Positions -}; - -// -// Definitions ... - -// -// Conditions Struct ... -struct XCAEAStrategyConditions -{ - // - // Props ... - - // - string symbol; - ENUM_TIMEFRAMES period; - - // - // Setup Props ... - - // - double sl; - double tp; - double pivot; - double point; - double entry; - double reward; - string provider; - - // - XTarget targets[]; - - // - datetime time; - datetime setupTime; - datetime triggerTime; - - // - ENUM_X_DIRECTION dir; - XBoxZone decisionZone; - ENUM_X_POSITION_TYPES type; - XCAEAConditions conditions; - - // - // Constructor ... - XCAEAStrategyConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - sl = 0; - tp = 0; - pivot = 0; - point = 0; - entry = 0; - reward = 0; - - // - symbol = NULL; - period = NULL; - provider = NULL; - - // - time = NULL; - setupTime = NULL; - triggerTime = NULL; - - // - Clean(targets); - - // - conditions.Clean(); - decisionZone.Clean(); - - // - dir = X_DIRECTION_NONE; - type = X_POSITION_TYPE_NONE; - - // - ZeroMemory(this); - } - - // - // Signalling ... - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = IsSpecifiedValid(symbol) && - IsSpecifiedValid(period) && - IsSpecifiedValid(time); - - // - return result; - } - - /** - * Check Conditions Has Valid Bullish Signal ... - * - * @return ( bool ) - */ - bool HasBullishSignal() - { - // - bool result = false; - - // - result = - (sl > 0 || - tp > 0) && - IsValid() && - HasDirection(dir); - if (!result) - { - return result; - } - - // - result = - IsBullish(dir); - - // - return result; - } - - /** - * Check Conditions Has Valid Bearish Signal ... - * - * @return ( bool ) - */ - bool HasBearishSignal() - { - // - bool result = false; - - // - result = - (sl > 0 || - tp > 0) && - IsValid() && - HasDirection(dir); - if (!result) - { - return result; - } - - // - result = - IsBearish(dir); - - // - return result; - } - - // - // Setting Up and Triggering Up ... - - /** - * Check Condition is Setting Up ... - * - * @param dir: ENUM_X_DIRECTION member, Setting Up Direction ... - * - * @return ( bool ) - */ - bool IsSetuped() - { - // - bool result = false; - - // - result = IsValid(setupTime) && - HasDirection(dir); - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Calculate Setup Age ... - * - * @return ( int ) - */ - int GetSetupAge() - { - // - int result = 0; - - // - if (!IsSetuped()) - { - return result; - } - - // - result = (int)(TimeCurrent() - setupTime) / PeriodSeconds(period); - - // - return result; - } - - /** - * Detect How we Can Trigger Signal ... - * - * @return ( bool ) - */ - bool CanTrigger() - { - // - bool result = false; - - // - result = - // - sl > 0 && - IsValid(symbol) && - IsValid(period) && - IsValid(triggerTime) && - type != X_POSITION_TYPE_ALL && - type != X_POSITION_TYPE_NONE - // - ; - - // - return result; - } - - // -}; - -// -// Model a Guard Action ... -struct XCAEAGuard -{ - // - // Props ... - ENUM_GUARD_ACTIONS action; - datetime time; - - // - string symbol; - string provider; - - // - // Specified Position ... - ulong ticket; - - // - // Partial Close ... - double volumeMultiplier; - - // - // SL Trial ... - double sl; - - // - // TP Trial ... - double tp; - - // - // Constructor ... - XCAEAGuard() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - time = NULL; - action = X_GUARD_ACTION_NONE; - - // - symbol = NULL; - provider = NULL; - - // - ticket = 0; - - // - volumeMultiplier = 0; - - // - sl = 0; - tp = 0; - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(time) && - IsValid(symbol) && - IsValid(provider) && - action != X_GUARD_ACTION_NONE - // - ; - if (!result) - { - return result; - } - - // - // Validate Model Based On Specified Guard Actions ... - - // - return result; - } -}; - -/** - * Add Guard to Collection ... - * - * @param guard: XCAEAGuard instance ... - * @param guards: XCAEAGuard instance Collection ... - * - * @return ( int ) - */ -int AddGuard( - XCAEAGuard &guard, - XCAEAGuard &guards[] // -) -{ - // - int result = 0; - - // - if (!guard.IsValid()) - { - return result; - } - - // - AddRef( - guard, - guards // - ); - - // - result = ArraySize(guards); - - // - return result; -} - -// -enum ENUM_XCAEA_LQ_TYPES -{ - XCAEA_LQ_TYPE_NONE = 0, - XCAEA_LQ_TYPE_PEAK = 1, - XCAEA_LQ_TYPE_VALE = 2, -}; - -struct XCAEALQSweep -{ - // - // Props ... - int length; - datetime to; - string symbol; - datetime from; - double sweeped; - double reverse; - ENUM_TIMEFRAMES period; - ENUM_XCAEA_LQ_TYPES type; - - // - // Constructor ... - XCAEALQSweep() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - to = NULL; - length = 0; - from = NULL; - sweeped = 0; - reverse = 0; - symbol = NULL; - period = NULL; - type = XCAEA_LQ_TYPE_NONE; - } - - // - // Validation ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 0 && - IsValid(to) && - sweeped > 0 && - reverse > 0 && - IsValid(from) && - IsValid(symbol) && - IsValid(period) && - type != XCAEA_LQ_TYPE_NONE - // - ; - - // - return result; - } - - // - string GetTag() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - result = symbol + - ToString(period) + - "XLQ" + - (type == XCAEA_LQ_TYPE_PEAK ? "Peak" : "Vale") + - ToString(sweeped); - - // - return result; - } -}; - -// -// Tools ... - -// -// Detect Decision Zone ... -bool DetectDecisionZone( - XCXCAEAHelper *helper, - XCXCAEAPOIDrawer *drawer, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - XBoxZone &unavailables[], - XCAEAConditions &conditions, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - box.Clean(); - conditions.Clean(); - dir = X_DIRECTION_NONE; - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 5); - - // - // Retrieve Some Requirements ... - string symbol = helper.GetSymbol(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - double points = GetPoints(symbol); - - // - // Retrieve Conditions for Processing ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - box.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Define IDXses ... - int zIDX = barIndex; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - XOHCL p4Bar; - result = zBar.Init( - symbol, - period, - zIDX // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - pBar.GetPreviousBar(p2Bar); - result = - result && - p2Bar.GetPreviousBar(p3Bar); - result = - result && - p3Bar.GetPreviousBar(p4Bar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - box.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Bars Conditions ... - - // - // Score ... - - // - double bullishScore = 0; - double bearishScore = 0; - conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - bool isScoreBullish = - bullishScore > bearishScore; - - // - bool isScoreBearish = - bearishScore > bullishScore; - - // - bool isScoreNeutural = MathAbs(bullishScore - bearishScore) == 0; - - // - // Calculating Range Volumes ... - - // - double bullishVolume = 0; - double bearishVolume = 0; - helper.barAnalyser.CalculateRangeVolume( - cBar, - bullishVolume, - bearishVolume, - loopback // - ); - - // - bool isVolumeNeutural = MathAbs(bullishVolume - bearishVolume) == 0; - - // - // Checking OB ... - XBoxZone ob; - bool isOB = helper - .barAnalyser - .IsOB( - cBar, - ob, - false, // Force FVG Bar Type - true // Force Two Bar Start ... - ); - bool isBullishOB = - isOB && - ob.IsBullish(); - bool isBearishOB = - isOB && - ob.IsBearish(); - - // - // Reading Values ... - - // - // SAR ... - double zSar = conditions.sarBuffer[zIDX]; - double cSar = conditions.sarBuffer[cIDX]; - double pSar = conditions.sarBuffer[pIDX]; - double p2Sar = conditions.sarBuffer[p2IDX]; - double p3Sar = conditions.sarBuffer[p3IDX]; - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - double p3Peak = conditions.peakBuffer[p3IDX]; - double p4Peak = conditions.peakBuffer[p4IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - double p3Vale = conditions.valeBuffer[p3IDX]; - double p4Vale = conditions.valeBuffer[p4IDX]; - - // - // SWING Low ... - double zSWL = conditions.swingLowBuffer[zIDX]; - double cSWL = conditions.swingLowBuffer[cIDX]; - double pSWL = conditions.swingLowBuffer[pIDX]; - double p2SWL = conditions.swingLowBuffer[p2IDX]; - double p3SWL = conditions.swingLowBuffer[p3IDX]; - - // - // SWING High ... - double zSWH = conditions.swingHighBuffer[zIDX]; - double cSWH = conditions.swingHighBuffer[cIDX]; - double pSWH = conditions.swingHighBuffer[pIDX]; - double p2SWH = conditions.swingHighBuffer[p2IDX]; - double p3SWH = conditions.swingHighBuffer[p3IDX]; - - // - // SUPPORT ... - double zSupport = conditions.supportBuffer[zIDX]; - double cSupport = conditions.supportBuffer[cIDX]; - double pSupport = conditions.supportBuffer[pIDX]; - double p2Support = conditions.supportBuffer[p2IDX]; - double p3Support = conditions.supportBuffer[p3IDX]; - - // - // RESISTANCE ... - double zResistance = conditions.resistanceBuffer[zIDX]; - double cResistance = conditions.resistanceBuffer[cIDX]; - double pResistance = conditions.resistanceBuffer[pIDX]; - double p2Resistance = conditions.resistanceBuffer[p2IDX]; - double p3Resistance = conditions.resistanceBuffer[p3IDX]; - - // - // MAH ... - double zMAH = conditions.mahBuffer[zIDX]; - double cMAH = conditions.mahBuffer[cIDX]; - double pMAH = conditions.mahBuffer[pIDX]; - double p2MAH = conditions.mahBuffer[p2IDX]; - double p3MAH = conditions.mahBuffer[p3IDX]; - - // - // MAL ... - double zMAL = conditions.malBuffer[zIDX]; - double cMAL = conditions.malBuffer[cIDX]; - double pMAL = conditions.malBuffer[pIDX]; - double p2MAL = conditions.malBuffer[p2IDX]; - double p3MAL = conditions.malBuffer[p3IDX]; - - // - // MAC ... - double zMAC = conditions.macBuffer[zIDX]; - double cMAC = conditions.macBuffer[cIDX]; - double pMAC = conditions.macBuffer[pIDX]; - double p2MAC = conditions.macBuffer[p2IDX]; - double p3MAC = conditions.macBuffer[p3IDX]; - - // - // FIBO Level 1 ... - double zFib1 = conditions.fiboLevel1Buffer[zIDX]; - double cFib1 = conditions.fiboLevel1Buffer[cIDX]; - double pFib1 = conditions.fiboLevel1Buffer[pIDX]; - double p2Fib1 = conditions.fiboLevel1Buffer[p2IDX]; - double p3Fib1 = conditions.fiboLevel1Buffer[p3IDX]; - - // - // FIBO Level 2 ... - double zFib2 = conditions.fiboLevel2Buffer[zIDX]; - double cFib2 = conditions.fiboLevel2Buffer[cIDX]; - double pFib2 = conditions.fiboLevel2Buffer[pIDX]; - double p2Fib2 = conditions.fiboLevel2Buffer[p2IDX]; - double p3Fib2 = conditions.fiboLevel2Buffer[p3IDX]; - - // - // FIBO Level 3 ... - double zFib3 = conditions.fiboLevel3Buffer[zIDX]; - double cFib3 = conditions.fiboLevel3Buffer[cIDX]; - double pFib3 = conditions.fiboLevel3Buffer[pIDX]; - double p2Fib3 = conditions.fiboLevel3Buffer[p2IDX]; - double p3Fib3 = conditions.fiboLevel3Buffer[p3IDX]; - - // - // FIBO Level 4 ... - double zFib4 = conditions.fiboLevel4Buffer[zIDX]; - double cFib4 = conditions.fiboLevel4Buffer[cIDX]; - double pFib4 = conditions.fiboLevel4Buffer[pIDX]; - double p2Fib4 = conditions.fiboLevel4Buffer[p2IDX]; - double p3Fib4 = conditions.fiboLevel4Buffer[p3IDX]; - - // - // FIBO Level 5 ... - double zFib5 = conditions.fiboLevel5Buffer[zIDX]; - double cFib5 = conditions.fiboLevel5Buffer[cIDX]; - double pFib5 = conditions.fiboLevel5Buffer[pIDX]; - double p2Fib5 = conditions.fiboLevel5Buffer[p2IDX]; - double p3Fib5 = conditions.fiboLevel5Buffer[p3IDX]; - - // - // FAST ... - double zFast = conditions.fastBuffer[zIDX]; - double cFast = conditions.fastBuffer[cIDX]; - double pFast = conditions.fastBuffer[pIDX]; - double p2Fast = conditions.fastBuffer[p2IDX]; - double p3Fast = conditions.fastBuffer[p3IDX]; - - // - // FAST State ... - double zFastState = conditions.fastStateBuffer[zIDX]; - double cFastState = conditions.fastStateBuffer[cIDX]; - double pFastState = conditions.fastStateBuffer[pIDX]; - double p2FastState = conditions.fastStateBuffer[p2IDX]; - double p3FastState = conditions.fastStateBuffer[p3IDX]; - - // - // RSI ... - double zRSI = conditions.rsiBuffer[zIDX]; - double cRSI = conditions.rsiBuffer[cIDX]; - double pRSI = conditions.rsiBuffer[pIDX]; - double p2RSI = conditions.rsiBuffer[p2IDX]; - double p3RSI = conditions.rsiBuffer[p3IDX]; - - // - // Create Custom Conditions ... - - // - // Bar and Fibo Conditions ... - - // - // Bearish ... - - // - // Strong Reversal ... - bool isZBarOnFiboStrongBearish = zBar.low > zFib5; - bool isCBarOnFiboStrongBearish = cBar.low > cFib5; - bool isPBarOnFiboStrongBearish = pBar.low > pFib5; - bool isP2BarOnFiboStrongBearish = p2Bar.low > p2Fib5; - bool isP3BarOnFiboStrongBearish = p3Bar.low > p3Fib5; - - // - // Golden Zone Reversal ... - bool isZBarOnFiboGoldenBearish = zBar.low > zFib3 && - zBar.high < zFib4; - bool isCBarOnFiboGoldenBearish = cBar.low > cFib3 && - cBar.high < cFib4; - bool isPBarOnFiboGoldenBearish = pBar.low > pFib3 && - pBar.high < pFib4; - bool isP2BarOnFiboGoldenBearish = p2Bar.low > p2Fib3 && - p2Bar.high < p2Fib4; - bool isP3BarOnFiboGoldenBearish = p3Bar.low > p3Fib3 && - p3Bar.high < p3Fib4; - - // - // Bullish ... - - // - // Strong Reversal ... - bool isZBarOnFiboStrongBullish = zBar.high < zFib1; - bool isCBarOnFiboStrongBullish = cBar.high < cFib1; - bool isPBarOnFiboStrongBullish = pBar.high < pFib1; - bool isP2BarOnFiboStrongBullish = p2Bar.high < p2Fib1; - bool isP3BarOnFiboStrongBullish = p3Bar.high < p3Fib1; - - // - // Golden Zone Reversal ... - bool isZBarOnFiboGoldenBullish = zBar.low > zFib2 && - zBar.high < zFib3; - bool isCBarOnFiboGoldenBullish = cBar.low > cFib2 && - cBar.high < cFib3; - bool isPBarOnFiboGoldenBullish = pBar.low > pFib2 && - pBar.high < pFib3; - bool isP2BarOnFiboGoldenBullish = p2Bar.low > p2Fib2 && - p2Bar.high < p2Fib3; - bool isP3BarOnFiboGoldenBullish = p3Bar.low > p3Fib2 && - p3Bar.high < p3Fib3; - - // - // Score and Volume Conditions ... - - // - bool isScoreVolumeNeutural = isScoreNeutural || - isVolumeNeutural; - - // - bool isScoreVolumeNeuturalInFiboStrongBullish = - isScoreNeutural && - isCBarOnFiboStrongBullish; - - // - bool isScoreVolumeNeuturalInFiboGoldenBullish = - isScoreNeutural && - isCBarOnFiboGoldenBullish; - - // - bool isScoreVolumeNeuturalInFiboStrongBearish = - isScoreNeutural && - isCBarOnFiboStrongBearish; - - // - bool isScoreVolumeNeuturalInFiboGoldenBearish = - isScoreNeutural && - isCBarOnFiboGoldenBearish; - - // - bool isScoreVolumeNeuturalBullishPowered = - isScoreVolumeNeuturalInFiboStrongBullish || - isScoreVolumeNeuturalInFiboGoldenBullish; - - // - bool isScoreVolumeNeuturalBearishPowered = - isScoreVolumeNeuturalInFiboStrongBearish || - isScoreVolumeNeuturalInFiboGoldenBearish; - - // - // PEAK and VALES ... - - // - // PEAK Pivot ... - bool isZIsPeakPivot = - zPeak == cPeak && - zPeak == zSWH && - zPeak == zResistance && - isZBarOnFiboStrongBearish; - bool isCIsPeakPivot = - cPeak == pPeak && - cPeak == cSWH && - cPeak == cResistance && - isCBarOnFiboStrongBearish; - bool isPIsPeakPivot = - pPeak == p2Peak && - pPeak == pSWH && - pPeak == pResistance && - isPBarOnFiboStrongBearish; - bool isP2IsPeakPivot = - p2Peak == p3Peak && - p2Peak == p2SWH && - p2Peak == p2Resistance && - isP2BarOnFiboStrongBearish; - bool isP3IsPeakPivot = - p3Peak == p4Peak && - p3Peak == p3SWH && - p3Peak == p3Resistance && - isP3BarOnFiboStrongBearish; - - // - // VALE Pivot ... - bool isZIsValePivot = - zVale == cVale && - zVale == zSWL && - zVale == zSupport && - isZBarOnFiboStrongBullish; - bool isCIsValePivot = - cVale == pVale && - cVale == cSWL && - cVale == cSupport && - isCBarOnFiboStrongBullish; - bool isPIsValePivot = - pVale == p2Vale && - pVale == pSWL && - pVale == pSupport && - isPBarOnFiboStrongBullish; - bool isP2IsValePivot = - p2Vale == p3Vale && - p2Vale == p2SWL && - p2Vale == p2Support && - isP2BarOnFiboStrongBullish; - bool isP3IsValePivot = - p3Vale == p4Vale && - p3Vale == p3SWL && - p3Vale == p3Support && - isP3BarOnFiboStrongBullish; - - // - // FIBO Section Change Detection ... - bool isFiboSectionChanged = - // - (cFib1 != pFib1 && - cFib2 != pFib2 && - cFib3 != pFib3 && - cFib4 != pFib4 && - cFib5 != pFib5) - // - && - // - (conditions.isPeakUnderLast || - conditions.isValeOverLast || - conditions.isSwingLowOverLast || - conditions.isSwingHighUnderLast) - // - ; - - // - // SAR Change ... - - // - bool isSarSwitchedInFiboStrongBullish = - isCBarOnFiboStrongBullish && - conditions.isSarSwitchedToBullish; - - // - bool isSarSwitchedInFiboGoldenBullish = - isCBarOnFiboGoldenBullish && - conditions.isSarSwitchedToBullish; - - // - bool isSarSwitchedInFiboStrongBearish = - isCBarOnFiboStrongBearish && - conditions.isSarSwitchedToBearish; - - // - bool isSarSwitchedInFiboGoldenBearish = - isCBarOnFiboGoldenBearish && - conditions.isSarSwitchedToBearish; - - // - bool isSarSwitchedToBullish = - cFastState > 0 && - isSarSwitchedInFiboStrongBullish; - - // - bool isSarSwitchedToBearish = - cFastState < 0 && - isSarSwitchedInFiboStrongBearish; - - // - // RSI Conditions ... - - // - bool isRSICrossedOverOS = - p3RSI < conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel; - - // - bool isRSICrossedUnderOB = - p3RSI > conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel; - - // - // Custom Senarios ... - - // - bool isCond1Bullish = - // - isBullishOB - // - ; - - // - bool isCond1Bearish = - // - isBearishOB - // - ; - - // - bool isCond1 = - isCond1Bullish || - isCond1Bearish; - if (isCond1) - { - // - ENUM_X_DIRECTION iCond1Dir = - isCond1Bullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - int timeOffset = (int)cBar.time; - string iName = ToString(iCond1Dir) + "_COND1_" + ToString(timeOffset); - color iColor = isCond1Bullish - ? clrAqua - : clrMagenta; - ENUM_LINE_STYLE iStyle = STYLE_DOT; - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - cBar.time // - ); - if (has) - { - // - iObj.Color(iColor); - iObj.Style(iStyle); - } - - // - // Create Signal Box Based on Cond1 ... - - // - double upper = - isCond1Bullish - ? cBar.FindHighest(5, MODE_HIGH) - : MathMax(cPeak, cSWH); - - // - double lower = - isCond1Bullish - ? MathMin(cVale, cSWL) - : cBar.FindLowest(5, MODE_LOW); - - // - int toIDX = cBar.Index(); - int fromIDX = cBar.Index() + 5; - - // - datetime toTime = GetBarTime( - symbol, - period, - toIDX // - ); - datetime fromTime = GetBarTime( - symbol, - period, - fromIDX // - ); - - // - XBoxZone iBox; - - // - iBox.to = toTime; - iBox.upper = upper; - iBox.lower = lower; - iBox.type = "COND1"; - iBox.symbol = symbol; - iBox.period = period; - iBox.dir = iCond1Dir; - iBox.from = fromTime; - - // - has = iBox.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = helper - .poiDrawer - .DrawBox( - iBox, - iObj // - ); - if (has) - { - } - } - - // - box = iBox; - dir = iBox.dir; - - // - iBox.Clean(); - - // - // Print("Conditions Finder ..."); - } - - // - // bool isCond2 = isFiboSectionChanged; - // if (isCond2) - // { - // // - // Print("Decision Zone Full Cond1"); - // } - - // - // Summarise Result ... - - // - bool isBullish = - false || - isCond1Bullish; - - // - bool isBearish = - false || - isCond1Bearish; - - // - result = isBullish || - isBearish; - if (result) - { - // - // Check UnAvailables ... - int idx = -1; - has = FindBoxIndex( - idx, - box, - unavailables // - ); - if (has) - { - // - box.Clean(); - conditions.Clean(); - dir = X_DIRECTION_NONE; - } - - // - // Check Box is Prepared or Not ... - result = box.IsValid(); - } - - // - // Cleaning Up ... - - // - ob.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - if (!result) - { - // - box.Clean(); - conditions.Clean(); - dir = X_DIRECTION_NONE; - } - - // - return result; -} - -// -// Trigger Conditions ... - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCondTEMP( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - bool allowDraws, - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Parse Conditions ... - - // - // Summarizing ... - - // - bool canTriggerLong = - false; - - // - bool canTriggerShort = - false; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - // Trigger Direction ... - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Trigger Stop Loss ... - sl = 0; - - // - // Trigger Targets ... - } - - // - // Cleanup Resources ... - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCond0( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - bool allowDraws, - CArrayObj *drawns, - int barIndex = 0, - int loopback = 5, - double scorePassMultiplier = 1 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Scores ... - double bullScores[]; - double bearScores[]; - - // - // Volumes ... - double bullVolumes[]; - double bearVolumes[]; - - // - // Create a Loop through Loopack ... - XOHCL iBar; - bool has = false; - int start = barIndex; - XCAEAConditions iConditions; - int end = barIndex + loopback; - for (int i = end; i >= start; i--) - { - // - // Retrieve Bar ... - has = iBar.Init( - symbol, - decisionZone.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Conditions ... - has = helper.GetConditions( - iConditions, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Scores ... - double iBullScore = 0; - double iBearScore = 0; - iConditions - .GenerateScore( - iBullScore, - iBearScore // - ); - Add( - iBullScore, - bullScores // - ); - Add( - iBearScore, - bearScores // - ); - - // - // Retrieve Volumes ... - double iBullVolume = 0; - double iBearVolume = 0; - helper - .barAnalyser - .CalculateRangeVolume( - iBar, - iBullVolume, - iBearVolume, - 2 // Loopback ... - ); - Add( - iBullVolume, - bullVolumes // - ); - Add( - iBearVolume, - bearVolumes // - ); - - // - iBar.Clean(); - iConditions.Clean(); - } - - // - // Calculating Requirements ... - - // - // Scores ... - - // - // Bullish ... - double bullScore = GetSum(bullScores); - double bullScoreMax = GetMax(bullScores); - double bullScoreMin = GetMin(bullScores); - - // - // Bearish ... - double bearScore = GetSum(bearScores); - double bearScoreMax = GetMax(bearScores); - double bearScoreMin = GetMin(bearScores); - - // - // Volumes ... - - // - // Bullish ... - double bullVolume = GetSum(bullVolumes); - double bullVolumeMax = GetMax(bullVolumes); - double bullVolumeMin = GetMin(bullVolumes); - - // - // Bearish ... - double bearVolume = GetSum(bearVolumes); - double bearVolumeMax = GetMax(bearVolumes); - double bearVolumeMin = GetMin(bearVolumes); - - // - // Parse Conditions ... - - // - bool isBullishPassed = - isBullish && - bullScore >= (scorePassMultiplier * bearScore) && - bullVolume >= (scorePassMultiplier * bearVolume); - - // - bool isBearishPassed = - isBearish && - bearScore >= (scorePassMultiplier * bullScore) && - bearVolume >= (scorePassMultiplier * bullVolume); - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullishPassed; - - // - bool canTriggerShort = - isBearishPassed; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - // Trigger Direction ... - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Trigger Stop Loss ... - sl = canTriggerLong - ? decisionZone.lower - : decisionZone.upper; - - // - // Trigger Targets ... - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - Clean(bullScores); - Clean(bearScores); - Clean(bullVolumes); - Clean(bearVolumes); - iConditions.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCond1( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - bool allowDraws, - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - bool has = false; - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - int toIDX = decisionZone.ToIndex(); - int fromIDX = decisionZone.FromIndex(); - - // - // Reading Bars ... - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - result = zBar.Init( - symbol, - period, - barIndex // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - pBar.GetPreviousBar(p2Bar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - // Reading Bar's Conditions ... - XCAEAConditions iConditions; - result = helper.GetConditions( - iConditions, - barIndex, - loopback // - ); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - iConditions.Clean(); - - // - return result; - } - - // - // Reading Conditions Values ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - - // - // PEAK ... - double zPeak = iConditions.peakBuffer[zIDX]; - double cPeak = iConditions.peakBuffer[cIDX]; - double pPeak = iConditions.peakBuffer[pIDX]; - double p2Peak = iConditions.peakBuffer[p2IDX]; - double p3Peak = iConditions.peakBuffer[p3IDX]; - - // - // VALE ... - double zVale = iConditions.valeBuffer[zIDX]; - double cVale = iConditions.valeBuffer[cIDX]; - double pVale = iConditions.valeBuffer[pIDX]; - double p2Vale = iConditions.valeBuffer[p2IDX]; - double p3Vale = iConditions.valeBuffer[p3IDX]; - - // - // SWH ... - double zSWH = iConditions.swingHighBuffer[zIDX]; - double cSWH = iConditions.swingHighBuffer[cIDX]; - double pSWH = iConditions.swingHighBuffer[pIDX]; - double p2SWH = iConditions.swingHighBuffer[p2IDX]; - double p3SWH = iConditions.swingHighBuffer[p3IDX]; - - // - // SWL ... - double zSWL = iConditions.swingLowBuffer[zIDX]; - double cSWL = iConditions.swingLowBuffer[cIDX]; - double pSWL = iConditions.swingLowBuffer[pIDX]; - double p2SWL = iConditions.swingLowBuffer[p2IDX]; - double p3SWL = iConditions.swingLowBuffer[p3IDX]; - - // - // Required Conditions ... - - // - bool isPeakBraked = - zPeak == cPeak && - cPeak == pPeak && - (pPeak > p2Peak || - pPeak > p3Peak); - - // - bool isValeBraked = - zVale == cVale && - cVale == pVale && - (pVale < p2Vale || - pVale < p3Vale); - - // - bool isSWHBraked = - zSWH == cSWH && - cSWH == pSWH && - (pSWH > p2SWH || - pSWH > p3SWH); - - // - bool isSWLBraked = - zSWL == cSWL && - cSWL == pSWL && - (pSWL < p2SWL || - pSWL < p3SWL); - - // - // Select Activated Pivot ... - XBoxZone selectedPivot; - bool hasPivots = HasChild(decisionPivots); - int pivotsCount = ArraySize(decisionPivots); - if (hasPivots) - { - // - for (int i = 0; i < pivotsCount; i++) - { - // - // Detect Type of Pivot ... - ENUM_XCA_PIVOTS iType = GetPivotType(decisionPivots[i]); - - // - // Check Rejection of Block ... - - // - bool isBullishBraked = - isBullish && - (isSWLBraked && - isValeBraked) && - iType == XCA_OB_BULL && - decisionPivots[i].IsBullish() && - zVale < decisionPivots[i].upper && - zVale > decisionPivots[i].lower; - - // - bool isBearishBraked = - isBearish && - (isSWHBraked && - isPeakBraked) && - iType == XCA_OB_BEAR && - decisionPivots[i].IsBearish() && - zPeak < decisionPivots[i].upper && - zPeak > decisionPivots[i].lower; - - // - has = isBullishBraked || - isBearishBraked; - if (has) - { - // - selectedPivot = decisionPivots[i]; - break; - } - } - } - bool hasSelectedPivot = selectedPivot.IsValid(); - - // - // Draw Selected Pivot ... - if (allowDraws && - hasSelectedPivot) - { - // - // Draw Pivot ... - XCBoxObject *iObj; - - // - has = helper.poiDrawer.DrawBox( - selectedPivot, - iObj // - ); - if (has) - { - // - color iColor = - isBullish - ? clrAqua - : clrMagenta; - - // - iObj.BoxWidth(2); - iObj.BoxColor(iColor); - iObj.BoxStyle(STYLE_SOLID); - - // - drawns.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Parse Conditions ... - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullish && - hasSelectedPivot && - selectedPivot.IsBullish(); - - // - bool canTriggerShort = - isBearish && - hasSelectedPivot && - selectedPivot.IsBearish(); - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - // Trigger Direction ... - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Trigger Stop Loss ... - sl = isBullish - ? selectedPivot.lower - : selectedPivot.upper; - - // - // Trigger Targets ... - XTarget iTarget; - if (canTriggerLong && - zBar.close < decisionZone.upper) - { - // - iTarget.doRF = true; - iTarget.target = decisionZone.upper; - } - if (canTriggerShort && - zBar.close > decisionZone.lower) - { - // - iTarget.doRF = true; - iTarget.target = decisionZone.lower; - } - - // - if (iTarget.IsValid()) - { - // - AddRef( - iTarget, - targets // - ); - } - iTarget.Clean(); - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - iConditions.Clean(); - selectedPivot.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCond2( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - bool allowDraws, - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - bool has = false; - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int p2Index = pIndex + 1; - - // - // Extract Bars ... - XOHCL zBar; - XOHCL cBar; - result = zBar.Init( - symbol, - period, - cIndex // - ); - result = - result && - zBar.GetPreviousBar(cBar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - - // - return result; - } - - // - // Select Activated Pivot ... - XBoxZone selectedPivot; - bool hasPivots = HasChild(decisionPivots); - int pivotsCount = ArraySize(decisionPivots); - if (hasPivots) - { - // - for (int i = 0; i < pivotsCount; i++) - { - // - // Detect Type of Pivot ... - ENUM_XCA_PIVOTS iType = GetPivotType(decisionPivots[i]); - - // - // Check Rejection of Block ... - has = - isBullish - ? cBar.IsBullish() && - iType == XCA_OB_BULL && - decisionPivots[i].IsBullish() && - cBar.low < decisionPivots[i].upper && - cBar.low > decisionPivots[i].lower && - cBar.close > decisionPivots[i].upper - : cBar.IsBearish() && - iType == XCA_OB_BEAR && - decisionPivots[i].IsBearish() && - cBar.high > decisionPivots[i].lower && - cBar.high < decisionPivots[i].upper && - cBar.close < decisionPivots[i].lower; - if (has) - { - selectedPivot = decisionPivots[i]; - } - } - } - bool hasSelectedPivot = selectedPivot.IsValid(); - - // - // Draw Selected Pivot ... - if (allowDraws && - hasSelectedPivot) - { - // - // Draw Pivot ... - XCBoxObject *iObj; - - // - has = helper.poiDrawer.DrawBox( - selectedPivot, - iObj // - ); - if (has) - { - // - color iColor = - isBullish - ? clrAqua - : clrMagenta; - - // - iObj.BoxWidth(2); - iObj.BoxColor(iColor); - iObj.BoxStyle(STYLE_SOLID); - - // - drawns.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullish && - hasSelectedPivot && - selectedPivot.IsBullish(); - - // - bool canTriggerShort = - isBearish && - hasSelectedPivot && - selectedPivot.IsBearish(); - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - // Trigger Direction ... - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Trigger Stop Loss ... - sl = canTriggerLong - ? selectedPivot.lower - : selectedPivot.upper; - - // - // Trigger Targets ... - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - selectedPivot.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -// Block Based Triggering ... -bool CanTriggerCond3( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - bool allowDraws, - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Parse Conditions ... - - // - // Summarizing ... - - // - bool canTriggerLong = - false; - - // - bool canTriggerShort = - false; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - // Trigger Direction ... - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Trigger Stop Loss ... - sl = 0; - - // - // Trigger Targets ... - } - - // - // Cleanup Resources ... - - // - return result; -} - -// -// Helper Functions ... - -// -// Check a Box is Breaked or Not ... -bool IsBoxBreaked( - XCXCAEAHelper *helper, - XBoxZone &box, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Args ... - result = - box.IsValid() && - helper != NULL; - if (!result) - { - // - // Assume Box Invalid and Breaked - // When Args not Valid ... - result = true; - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - // Assume Box Invalid and Breaked - // When Args not Valid ... - result = true; - - // - return result; - } - - // - // Check Box is Breaked or not ... - // a Box Assume Breakes when at least 3 Bars Close over / under applied Price ... - - // - double appliedPrice = - isBullish - ? box.lower - : box.upper; - - // - bool isBullishBreaked = - isBullish && - cBar.close < appliedPrice && - pBar.close < appliedPrice && - p2Bar.close < appliedPrice; - - // - bool isBearishBreaked = - isBearish && - cBar.close > appliedPrice && - pBar.close > appliedPrice && - p2Bar.close > appliedPrice; - - // - result = isBullishBreaked || - isBearishBreaked; - - // - // Cleanup Resources ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -// Detect Fake Breakout ... -bool IsBoxFakedBreakout( - XCXCAEAHelper *helper, - XBoxZone &box, - XBoxZone &validatorFVG, - ENUM_X_DIRECTION forDir, - int barIndex = 0, - int loopback = 100, - bool forceFVGValidating = false, - bool forceFVGBarType = false // -) -{ - // - bool result = false; - - // - validatorFVG.Clean(); - - // - // Normalizing Args ... - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 10); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL && - (HasDirection(forDir)); - if (!result) - { - return result; - } - - // - double points = GetPoints(box.symbol); - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Bar Conditions ... - - // - ENUM_X_DIRECTION barDir; - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - barDir // - ); - bool isCBarBullishEngulfed = - isCBarEngulfed && - IsBullish(barDir); - bool isCBarBearishEngulfed = - isCBarEngulfed && - IsBearish(barDir); - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - barDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isCBarBullishRejected = - isCBarRejected && - IsBullish(barDir); - bool isCBarBearishRejected = - isCBarRejected && - IsBearish(barDir); - - // - bool isCBarHasBullishPower = isCBarBullishRejected || - isCBarBullishEngulfed; - - // - bool isCBarHasBearishPower = isCBarBearishRejected || - isCBarBearishEngulfed; - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - bool lookForBullish = IsBullish(forDir); - bool lookForBearish = IsBearish(forDir); - - // - // Calculate each Direction Breake Price ... - double bullishAppliedPrice = box.lower; - double bearishAppliedPrice = box.upper; - - // - bool isCBarPressedForBullish = - // - isCBarHasBullishPower && - cBar.low < bullishAppliedPrice && - cBar.close > bullishAppliedPrice - // - ; - - // - bool isCBarPressedForBearish = - // - isCBarHasBearishPower && - cBar.high > bearishAppliedPrice && - cBar.close < bearishAppliedPrice - // - ; - - // - bool isPBarBreakedBullishAppliedPrice = - pBar.low < bullishAppliedPrice && - pBar.high > bullishAppliedPrice; - - // - bool isPBarBreakedBearishAppliedPrice = - pBar.low < bearishAppliedPrice && - pBar.high > bearishAppliedPrice; - - // - bool isP2BarBreakedBullishAppliedPrice = - p2Bar.low < bullishAppliedPrice && - p2Bar.high > bullishAppliedPrice; - - // - bool isP2BarBreakedBearishAppliedPrice = - p2Bar.low < bearishAppliedPrice && - p2Bar.high > bearishAppliedPrice; - - // - bool isBullishAppliedPriceBreaked = - isPBarBreakedBullishAppliedPrice || - isP2BarBreakedBullishAppliedPrice; - - // - bool isBearishAppliedPriceBreaked = - isPBarBreakedBearishAppliedPrice || - isP2BarBreakedBearishAppliedPrice; - - // - bool isBullishFakeBreakedOut = - lookForBullish && - isCBarPressedForBullish && - isBullishAppliedPriceBreaked; - - // - bool isBearishFakeBreakedOut = - lookForBearish && - isCBarPressedForBearish && - isBearishAppliedPriceBreaked; - - // - result = isBullishFakeBreakedOut || - isBearishFakeBreakedOut; - - // - // Validating Using FVG if necessary ... - if (forceFVGValidating) - { - // - // Detecting All FVGs Which Placed in Box till Loopback ... - XBoxZone fvg; - - // - XOHCL iBar; - bool has = false; - int start = cBar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - // Initialize Bar ... - has = iBar.Init( - cBar.symbol, - cBar.period, - i // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check FVG ... - has = helper - .barAnalyser - .IsFVG( - iBar, - fvg, - forceFVGBarType // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - bool isBullishFVG = - fvg.IsBullish() && - isBullishFakeBreakedOut; - - // - bool isBearishFVG = - fvg.IsBearish() && - isBearishFakeBreakedOut; - - // - // Checking FVG Dir ... - has = isBullishFVG || - isBearishFVG; - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check CBar Must Inside FVG ... - - // - bool isFVGBullishBreaked = - isBullishFVG && - cBar.low < fvg.upper && - cBar.close > fvg.upper && - isBullishFakeBreakedOut; - - // - bool isFVGBearishBreaked = - isBearishFVG && - cBar.high > fvg.lower && - cBar.close < fvg.lower && - isBearishFakeBreakedOut; - - // - has = - isFVGBullishBreaked || - isFVGBearishBreaked; - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - result = - result && - fvg.IsValid(); - if (result) - { - // - fvg.to = cBar.time; - - // - // Check FVG Size ... - double fvgRange = fvg.upper - fvg.lower; - bool canApplyLastBar = fvgRange < (5 * points); - if (canApplyLastBar) - { - // - // Retrieve FVG Start Bar ... - XOHCL fvgStartBar; - has = fvgStartBar.Init( - cBar.symbol, - cBar.period, - cBar.Index() + 3 // - ); - if (has) - { - // - if (fvg.IsBullish()) - { - fvg.lower = fvgStartBar.low; - } - else - { - fvg.upper = fvgStartBar.high; - } - } - - // - fvgStartBar.Clean(); - } - - // - validatorFVG = fvg; - - // - XCBoxObject *iObj; - has = helper.poiDrawer.DrawBox( - fvg, - iObj // - ); - ZeroMemory(iObj); - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - // Cleanup Resources ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -// Detect Activated FVG ... -bool IsBoxHasActivatedFVG( - XCXCAEAHelper *helper, - XBoxZone &box, - XBoxZone &fvg, - int barIndex = 0, - int loopback = 10, - bool forceFVGBarType = false // -) -{ - // - bool result = false; - - // - fvg.Clean(); - - // - // Normalize Args ... - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 10); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - double points = GetPoints(box.symbol); - - // - // Retrieve Conditions ... - XCAEAConditions conditions; - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Find FVG ... - - // - XOHCL iBar; - bool has = false; - int start = cBar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - // Initialize Bar ... - has = iBar.Init( - cBar.symbol, - cBar.period, - i // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - }; - - // - // Check FVG ... - has = helper - .barAnalyser - .IsFVG( - iBar, - fvg, - forceFVGBarType // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Validate FVG ... - has = - // - fvg.IsValid() && - fvg.dir == box.dir && - fvg.from > box.from && - fvg.upper <= box.upper && - fvg.lower >= box.lower - // - ; - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check CBar FVG Validations ... - - // - bool isCBarBullishRejected = - isBullish && - cBar.low < fvg.upper && - cBar.close > fvg.upper; - - // - bool isCBarBearishRejected = - isBearish && - cBar.high > fvg.lower && - cBar.close < fvg.lower; - - // - has = isCBarBullishRejected || - isCBarBearishRejected; - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - result = fvg.IsValid(); - if (result) - { - // - fvg.to = cBar.time; - - // - // Check FVG Size ... - double fvgRange = fvg.upper - fvg.lower; - bool canApplyLastBar = true; - // fvgRange < (5 * points); - if (canApplyLastBar) - { - // - // Retrieve FVG Start Bar ... - XOHCL fvgStartBar; - has = fvgStartBar.Init( - cBar.symbol, - cBar.period, - cBar.Index() + 4 // - ); - if (has) - { - // - if (fvg.IsBullish()) - { - fvg.lower = fvgStartBar.low; - } - else - { - fvg.upper = fvgStartBar.high; - } - } - - // - fvgStartBar.Clean(); - } - - // - XCBoxObject *iObj; - helper.poiDrawer.DrawBox( - fvg, - iObj // - ); - ZeroMemory(iObj); - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - conditions.Clean(); - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/XCAEA/Signals/xcaea.signaller.class.mq5 b/Documents/BKP/XCAEA_BKP/XCAEA/Signals/xcaea.signaller.class.mq5 deleted file mode 100644 index f6de1fea..00000000 --- a/Documents/BKP/XCAEA_BKP/XCAEA/Signals/xcaea.signaller.class.mq5 +++ /dev/null @@ -1,1533 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCAEASignaller ... -// Description: Class for XCAEA Signaller ... -// -// -// 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 XCAEA Signaller" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.base.class.mq5" -#include "../../Classes/x-saherelm.x-cobject.class.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" -#include "../Classes/xcaea.x-poi.drawer.class.mq5" -#include "../Helpers/xcaea.helper.mq5" -#include "../Libraries/xcaea.signaller.lib.mq5" - -// -// Definitions ... - -class XCXCAEASignaller : XCBase -{ - // - // Public ... - public: - // - // Props ... - bool useGuards; - bool allowDraws; - XCAEAInputs inputs; - bool allowDrawPOIs; - XBarTracker barTraker; - XCXCAEAHelper *helper; - int maxAllowedSetupAge; - XBoxZone unavailables[]; - XCXCAEAPOIDrawer *drawer; - XCXCAEAHelper *analyseHelper; - XCXCAEAPOIDetector *detector; - XCAEAStrategyConditions mConditions; - bool allowAnalyseDecisionZoneSignalling; - bool allowTriggerBlockDecisionZoneSignalling; - XCAEAStrategyConditions mConditionsCollection[]; - - // - // Constructor ... - XCXCAEASignaller( - string _symbol, - ENUM_TIMEFRAMES _period, - ENUM_TIMEFRAMES _analysePeriod // - ) - { - // - symbol = _symbol; - period = _period; - analysePeriod = _analysePeriod; - - // - Init(); - } - - // - // Deconstructor ... - ~XCXCAEASignaller() - { - DeInit(); - } - - // - // Properties ... - - /** - * Initialize ... - */ - void Init() - { - // - // Configure Signaller Handler ... - useGuards = false; - allowDraws = true; - allowDrawPOIs = false; - maxAllowedSetupAge = 576; - - // - // Signallings ... - allowAnalyseDecisionZoneSignalling = false; - allowTriggerBlockDecisionZoneSignalling = true; - - // - // Initial Bar Tracker ... - barTraker.Init( - symbol, - period // - ); - - // - // Initial Indicators ... - InitHelper(); - - // - // Initial POI Detector and Drawer ... - InitDetectorAndDrawer(); - - // - } - - /** - * DeInitialize ... - */ - void DeInit() - { - // - inputs.Clean(); - - // - // Cleaning Draws ... - drawer.Clear(); - - // - ZeroMemory(drawer); - ZeroMemory(helper); - ZeroMemory(detector); - ZeroMemory(analyseHelper); - - // - Clean(unavailables); - - // - mConditions.Clean(); - Clean(mConditionsCollection); - - // - mObjects.Clear(); - mBarObjects.Clear(); - - // - barTraker.Clean(); - } - - // - string GetSymbol() - { - return symbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return period; - } - - // - // Signaller Tools ... - - /** - * Detect Setup Conditions based on Signalling ... - * - * @param maxAllowedSLDistanceInPoint: int, Max Allowed SL Distance in Points (if Bigger thn Zero Provided) ... - * - * @return ( bool ) - */ - bool DetectSignalSetup( - double tpReward = 3 // - ) - { - // - bool result = false; - - // - // Normalize Args ... - tpReward = NormalizeDouble(tpReward, 1); - - // - // Check Bar Processing ... - if (!barTraker.CanProcessBar()) - { - return result; - } - - // - int idx = -1; - int count = 0; - int zIndex = 0; - bool has = false; - int loopback = 10; - int cIndex = zIndex + 1; - bool isBullish = false; - bool isBearish = false; - - // - XOHCL zBar; - result = zBar.Init( - symbol, - period, - zIndex // - ); - if (!result) - { - // - zBar.Clean(); - - // - return result; - } - datetime cTime = zBar.time; - - // - // Detect Pivots ... - detector.Detect(zIndex); - - // - // Validate Pivots ... - detector.Validate( - unavailables, - zIndex // - ); - - // - // Draw Pivots ... - if (allowDraws && - allowDrawPOIs) - { - drawer.Draw(cTime); - } - - // - // Setup Conditions ... - XBoxZone decisionZone; - XCAEAConditions conditions; - bool hasDecisionZone = false; - ENUM_X_DIRECTION decisionZoneDir = X_DIRECTION_NONE; - - // - // Check Decision Zone Detection Based On Several Signalling ... - - // - // Analyse DecisionZone ... - // In this Used Case we fond an Analyse TF OB - // then waits for trigger on it ... - if (allowAnalyseDecisionZoneSignalling) - { - // - // Checking Signal's Decision Zone ... - // On Analyse Time Frame ... - hasDecisionZone = DetectDecisionZone( - analyseHelper, - drawer, - decisionZone, - decisionZoneDir, - unavailables, - conditions, - zIndex, - loopback // - ); - - // - // Here we Can Validate Decision Zone ... - if (hasDecisionZone) - { - } - } - - // - // TriggerBlock Decision Zone ... - // In this Used Case we found a Tigger Block and use it - // for Triggering ... - if (!hasDecisionZone && - allowTriggerBlockDecisionZoneSignalling) - { - // - int pushers = 0; - - // - // We Can Detect Multiple Decision Zones ... - XBoxZone tmpZone; - XCAEATriggerBlockConfiguration config; - - // - bool allowTwoFilters = false; - bool allowThreeFilters = false; - - // - bool hasFullFiltered = false; - bool hasSarRsiAdxFiltered = false; - bool hasSarRsiTrendFiltered = false; - bool hasSarAdxTrendFiltered = false; - bool hasRsiAdxTrendFiltered = false; - - // - bool hasSarRsiFiltered = false; - bool hasSarAdxFiltered = false; - bool hasRsiAdxFiltered = false; - bool hasSarTrendFiltered = false; - bool hasRsiTrendFiltered = false; - bool hasAdxTrendFiltered = false; - - // - // Full Filteres ... - config.ConfigureFullFilter(); - hasFullFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasFullFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - // Check Three Filters ... - if (allowThreeFilters) - { - // - tmpZone.Clean(); - config.ConfigureSarRsiAdxFilter(); - hasSarRsiAdxFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarRsiAdxFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureSarRsiTrendFilter(); - hasSarRsiTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarRsiTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureSarAdxTrendFilter(); - hasSarAdxTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarAdxTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureRsiAdxTrendFilter(); - hasRsiAdxTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasRsiAdxTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - } - - // - // Check two Filters ... - if (allowTwoFilters) - { - // - tmpZone.Clean(); - config.ConfigureSarRsiFilter(); - hasSarRsiFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarRsiFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureSarAdxFilter(); - hasSarAdxFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarAdxFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureSarTrendFilter(); - hasSarTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasSarTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureRsiAdxFilter(); - hasRsiAdxFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasRsiAdxFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureRsiTrendFilter(); - hasRsiTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasRsiTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - - // - tmpZone.Clean(); - config.ConfigureAdxTrendFilter(); - hasAdxTrendFiltered = DetectTriggerBlock( - tmpZone, - conditions, - helper, - config, - zIndex, - loopback // - ); - if (hasAdxTrendFiltered) - { - // - pushers++; - - // - if (!decisionZone.IsValid()) - { - decisionZone = tmpZone; - } - } - } - - // - hasDecisionZone = - hasSarRsiFiltered || - hasSarAdxFiltered || - hasRsiAdxFiltered || - hasSarTrendFiltered || - hasRsiTrendFiltered || - hasAdxTrendFiltered || - hasSarRsiAdxFiltered || - hasSarRsiTrendFiltered || - hasSarAdxTrendFiltered || - hasRsiAdxTrendFiltered; - - // - if (hasDecisionZone) - { - // - drawer.DrawBox( - decisionZone, - cTime, - false, // Draw Middle ... - true // Ignore Type ... - ); - - // - Print(ToString(decisionZone.dir) + " Trigger Block Detected (" + ToString(pushers) + ") ..."); - } - - // - tmpZone.Clean(); - } - - // - // Make Signal Box UnAvailable ... - if (hasDecisionZone) - { - // - decisionZoneDir = decisionZone.dir; - - // - AddRef( - decisionZone, - unavailables // - ); - } - - // - isBullish = hasDecisionZone && - IsBullish(decisionZoneDir); - - // - isBearish = hasDecisionZone && - IsBearish(decisionZoneDir); - - // - result = isBullish || - isBearish; - if (result) - { - // - // Do What we Want ... - barTraker.Waits(); - - // - double pivot = isBullish - ? decisionZone.lower - : decisionZone.upper; - - // - double point = isBullish - ? decisionZone.upper - : decisionZone.lower; - - // - // Prepare Conditions ... - mConditions.point = point; - mConditions.pivot = pivot; - mConditions.symbol = symbol; - mConditions.period = period; - mConditions.time = zBar.time; - mConditions.reward = tpReward; - mConditions.provider = "XCAEA"; - mConditions.setupTime = zBar.time; - mConditions.dir = decisionZoneDir; - mConditions.conditions = conditions; - mConditions.decisionZone = decisionZone; - } - - // - // Cleanup Resource ... - - // - zBar.Clean(); - conditions.Clean(); - decisionZone.Clean(); - - // - return result; - } - - /** - * Detect Trigger Conditions for Specified Signal ... - * - * @param conditions: XCAEAStrategyConditions instance Reference, Specified Signal Conditions ... - * @param maxAllowedSetupAge: specified Setup Age for Expiration (if bigger than Zero) ... - * - * @return ( bool ) - */ - bool DetectSignalTrigger( - XCAEAStrategyConditions &conditions, - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize Args ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Setup ... - result = conditions.IsSetuped(); - if (!result) - { - return result; - } - - // - // Reading Requirements ... - - // - int loopback = 10; - double ask = GetAsk(symbol); - double bid = GetBid(symbol); - datetime cTime = TimeCurrent(); - double points = GetPoints(symbol); - datetime setupTime = conditions.setupTime; - ENUM_X_DIRECTION setupDir = conditions.dir; - - // - bool isBullish = IsBullish(setupDir); - bool isBearish = IsBearish(setupDir); - - // - // Extract Current Bar Conditions ... - helper.GetConditions( - conditions.conditions, - barIndex, - loopback // - ); - - // - // Check Signal Validation ... - // IMPORTANT: since all Validations done in SetUp Process ... - // here we only Execute Signal ... - - // - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - bool has = false; - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int p2Index = pIndex + 1; - - // - // Checking Trigger Conditions ... - double sl = 0; - double tp = 0; - XTarget targets[]; - ENUM_X_DIRECTION triggerDir = X_DIRECTION_NONE; - int toIDX = conditions.decisionZone.ToIndex(); - int fromIDX = conditions.decisionZone.FromIndex(); - - // - bool isAnalyseSignalled = - conditions.decisionZone.period == analyseHelper.GetPeriod(); - - // - ENUM_XCAEA_TIGGER_TYPE decisionZoneType = GetType(conditions.decisionZone.type); - bool isTriggerBlockSignalled = IsValid(decisionZoneType); - - // - // Looking for Analyse Helper Triggers ... - if (isAnalyseSignalled && - allowAnalyseDecisionZoneSignalling) - { - // - // Trigger Analyse Signal ... - - // - // Check Box Size ... - double maxAllowedBoxRange = 400; - double range = conditions.decisionZone.GetRange(); - bool isTooLarge = range > (maxAllowedBoxRange * points); - double decisionMiddlePrice = conditions.decisionZone.GetMid(); - - // - // Detect Required Pivots ... - XBoxZone decisionPivots[]; - ENUM_XCA_PIVOTS allowedTypes[]; - if (isBullish) - { - // - Add( - XCA_OB_BULL, - allowedTypes // - ); - } - else - { - // - Add( - XCA_OB_BEAR, - allowedTypes // - ); - } - Add( - XCA_PEAK, - allowedTypes // - ); - Add( - XCA_VALE, - allowedTypes // - ); - int decisionPivotsCount = detector.FillPivots( - conditions.decisionZone, - decisionPivots, - unavailables, - allowedTypes, - cTime // - ); - - // - // Draw Pivots of Decision Zone only when - // it's Too Large ... - if (false && - allowDraws && - isTooLarge && - HasChild(decisionPivots)) - { - // - for (int i = 0; i < decisionPivotsCount; i++) - { - // - drawer.DrawBox( - decisionPivots[i], - cTime, - false, // Draw Middle ... - true // Ignore Type ... - ); - } - } - - // - // Define a Temparory Objects - // Array instance for Holding Drawn Objects ... - CArrayObj *iObjects; - iObjects = new CArrayObj(); - - // - // Check Different Trigger Conditions ... - - // - // Checking Trigger Cond 0 ... - bool canTriggerCond0 = false; - - // - // Checking Trigger Cond 1 ... - bool canTriggerCond1 = false; - if (isTooLarge) - { - // - canTriggerCond1 = CanTriggerCond1( - helper, - conditions.decisionZone, - decisionPivots, - triggerDir, - sl, - targets, - allowDraws, - iObjects, - barIndex // - ); - } - - // - // Checking Trigger Cond 2 ... - bool canTriggerCond2 = false; - if (!isTooLarge) - { - // - canTriggerCond2 = CanTriggerCond2( - helper, - conditions.decisionZone, - decisionPivots, - triggerDir, - sl, - targets, - allowDraws, - iObjects, - barIndex // - ); - } - - // - // Checking Trigger Cond 3 ... - bool canTriggerCond3 = false; - - // - // Adding Drawn Objects to Drawn Stores ... - for (int i = 0; i < iObjects.Total(); i++) - { - mObjects.Add(iObjects.At(i)); - } - - // - // Summarizing Result ... - result = - canTriggerCond0 || - canTriggerCond1 || - canTriggerCond2 || - canTriggerCond3; - } - else if (isTriggerBlockSignalled && - allowTriggerBlockDecisionZoneSignalling) - { - // - // Trigger TRIGGER Block Signal ... - - // - // since we have to Trigger all TRIGGER Block's Signals - // exactly on Setting ups ... - result = isBullish || - isBearish; - if (result) - { - // - triggerDir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - sl = - isBullish - ? conditions.decisionZone.lower - : conditions.decisionZone.upper; - - // - conditions.reward = 2; - } - } - - // - isBullish = result && - IsBullish(triggerDir); - isBearish = result && - IsBearish(triggerDir); - - // - // Configure Conditions for Preparing Signal ... - if (result) - { - // - // Draw Decision Zone ... - if (allowDraws) - { - // - drawer.DrawBox( - conditions.decisionZone, - cTime, - true, // Draw Middle Line ... - true // Ignore Type ... - ); - } - - // - // Reconfigure Position TP/SL Entry and etc ... - - // - double entry = GetEntry( - conditions.symbol, - triggerDir // - ); - conditions.entry = entry; - - // - double spred = GetSpread(conditions.symbol); - - // - double risk = MathAbs(entry - sl) + spred; - double reward = (risk * conditions.reward); - tp = - isBullish - ? entry + reward - : entry - reward; - - // - conditions.sl = sl; - conditions.tp = tp; - conditions.dir = triggerDir; - conditions.triggerTime = cTime; - conditions.type = isBullish - ? X_POSITION_TYPE_LONG - : X_POSITION_TYPE_SHORT; - - // - // Preparing Targets ... - XTarget iTarget; - double iPrice = 0; - double iReward = 0; - - // - // Partial Close 25% of Volume in R2R 1 ... - iReward = risk * 1; - iPrice = - isBullish - ? entry + iReward - : entry - iReward; - iPrice = NormalizePrice(iPrice, conditions.symbol); - iTarget.target = iPrice; - iTarget.volumeMultiplier = 0.25; - AddRef( - iTarget, - targets // - ); - - // - // Partial Close 25% of Volume in R2R 2 ... - iReward = risk * 1.90; - iPrice = - isBullish - ? entry + iReward - : entry - iReward; - iPrice = NormalizePrice(iPrice, conditions.symbol); - iTarget.target = iPrice; - iTarget.volumeMultiplier = 0.25; - AddRef( - iTarget, - targets // - ); - - // - // Risk Free in R2R 3 ... - iReward = risk * 2.90; - iPrice = - isBullish - ? entry + iReward - : entry - iReward; - iPrice = NormalizePrice(iPrice, conditions.symbol); - // iTarget.doRF = true; - iTarget.volumeMultiplier = 0.25; - iTarget.target = iPrice; - AddRef( - iTarget, - targets // - ); - - // - // Handling Targets ... - bool hasTargets = HasChild(targets); - if (hasTargets) - { - // - Copy( - targets, - conditions.targets // - ); - } - - // - } - - // - // Validating Conditions if not Triggered ... - if (!result) - { - // - // Check Box Age ... - int age = conditions.GetSetupAge(); - bool has = age <= maxAllowedSetupAge; - if (!has) - { - conditions.Clean(); - } - - // - // Checking Decision Zone Validation ... - bool isValid = conditions.decisionZone.IsValid(); - if (!isValid) - { - conditions.Clean(); - } - - // - // Check Box Price ... - has = IsBoxBreaked( - helper, - conditions.decisionZone, - barIndex // - ); - if (has) - { - conditions.Clean(); - } - } - - // - // Cleanup ... - - // - return result; - } - - /** - * Detect Guards bsed on Signalling Class ... - * - * @param guards: XCAEAGuard instance Collection, Holds Provided Guards ... - * @param positions: XPosition instance Collection, Provides Signalling Based Positions for Apply Guards on them ... - * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... - * - * @return ( bool ) - */ - bool DetectGuards( - XCAEAGuard &guards[], - const XPosition &positions[] // - ) - { - // - bool result = false; - - // - // TODO: Implement this ... - - // - return result; - } - - /** - * Add Conditions to Conditions Collection if not Exists ... - * - * @param maxAllowed: int, Specified Max Allowed Holding Conditions ... - * - * @return ( int ) - */ - int AddConditionsIfNotExists( - int maxAllowed = 10 // - ) - { - // - int result = 0; - - // - bool isSetuped = IsValid(mConditions.setupTime) && - HasDirection(mConditions.dir); - if (!isSetuped) - { - return result; - } - - // - int count = ArraySize(mConditionsCollection); - if (IsValidSize(count)) - { - // - // Copy Original Items ... - XCAEAStrategyConditions tmpItems[]; - Copy( - mConditionsCollection, - tmpItems // - ); - - // - // Prese Item Data ... - bool isBullish = IsBullish(mConditions.dir); - - // - for (int i = 0; i < count; i++) - { - // - XCAEAStrategyConditions iItem = tmpItems[i]; - - // - bool canRemove = mConditions.dir == iItem.dir && - mConditions.pivot == iItem.pivot; - if (canRemove) - { - // - ArrayRemove( - mConditionsCollection, - i, - 1 // - ); - } - } - - // - Clean(tmpItems); - } - - // - AddRef( - mConditions, - mConditionsCollection // - ); - - // - // Remove Olds ... - CleanupArray( - mConditionsCollection, - maxAllowed // - ); - - // - result = ArraySize(mConditionsCollection); - - // - return result; - } - - // - // Protected ... - protected: - // - - // - // Private ... - private: - // - // Props ... - string symbol; - ENUM_TIMEFRAMES period; - ENUM_TIMEFRAMES analysePeriod; - - // - CArrayObj mObjects; - CArrayObj mBarObjects; - - // - void InitHelper() - { - // - inputs.Default(); - - // - // Configure Indicators ... - - // - // XCC ... - inputs.ccInputs.showCandles = true; - - // - // XCT ... - inputs.ctInputs.showCandleTime = true; - - // - // X3MA ... - - // - inputs.x3maInputs.applyColor = true; - - // - inputs.x3maInputs.fastLength = 5; - - // - inputs.x3maInputs.showFast = false; - inputs.x3maInputs.showSlow = false; - inputs.x3maInputs.showMedium = false; - - // - // XCA ... - - // - // inputs.caInputs.sarStep = 0.001; - // inputs.caInputs.sarMax = 0.05; - - // - inputs.caInputs.supResSmoothingLength = 7; - inputs.caInputs.supResSmoothingMode = X_MA_MODE_NONE; - - // - inputs.caInputs.showKI = false; - inputs.caInputs.showTKI = false; - inputs.caInputs.showMAH = false; - inputs.caInputs.showMAL = false; - inputs.caInputs.showMAC = false; - inputs.caInputs.showSar = false; - inputs.caInputs.showVidya = false; - inputs.caInputs.showTrend = false; - inputs.caInputs.showSwings = false; - inputs.caInputs.showFiboLevel1 = false; - inputs.caInputs.showFiboLevel2 = false; - inputs.caInputs.showFiboLevel3 = false; - inputs.caInputs.showFiboLevel4 = false; - inputs.caInputs.showFiboLevel5 = false; - inputs.caInputs.showPeaksAndVales = false; - inputs.caInputs.showPeakAndValeGolden = false; - inputs.caInputs.showSupportAndResistance = false; - - // - // XOSCS ... - // inputs.oscsInputs.rsiLength = 5; - // inputs.oscsInputs.rsiOBLevel = 90; - // inputs.oscsInputs.rsiOSLevel = 10; - // inputs.oscsInputs.cciLength = 7; - // inputs.oscsInputs.cciOBLevel = 130; - // inputs.oscsInputs.cciOSLevel = -130; - // inputs.oscsInputs.mfiLength = 5; - // inputs.oscsInputs.rviLength = 5; - - // - // Oscillators Views ... - inputs.showRSI = false; - inputs.showCCI = false; - inputs.showMFI = false; - inputs.showRVI = false; - inputs.showADX = false; - inputs.showMACD = false; - - // - // - // - - // - // XCAEA Helper ... - helper = new XCXCAEAHelper(); - helper.Init( - symbol, - period, - inputs // - ); - - // - // XCAEA Analyse Helper ... - analyseHelper = new XCXCAEAHelper(); - analyseHelper.Init( - symbol, - analysePeriod, - inputs // - ); - } - - // - void InitDetectorAndDrawer() - { - // - // Initialize and Configure Detector ... - detector = new XCXCAEAPOIDetector(helper); - - // - // Common Configurations ... - detector.maxAllowedPivots = 0; - detector.pivotVerifications = 5; - detector.ticksDividerInPoints = 15; - detector.pivotDetectionLoopbac = 200; - - // - // Configure Detector ... - - // - // SWING ... - - // - detector.maxAllowedSwingLifetime = 0; - - // - detector.detectSWLPivots = false; - detector.detectSWHPivots = false; - - // - // PV ... - - // - detector.maxAllowedPVLifetime = 0; - detector.applySwingsOnPVPivots = false; - detector.selectRejectedPVPivots = false; - detector.selectEngulfedPVPivots = false; - detector.applySupportAndResistanceOnPVPivots = false; - - // - detector.detectPeakPivots = true; - detector.detectValePivots = true; - - // - // OB ... - detector.maxAllowedOBLifetime = 0; - - // - detector.detectOBBullishPivots = true; - detector.detectOBBearishPivots = true; - - // - // FVG ... - - // - detector.selectSameBarFVGs = false; - detector.maxAllowedFVGLifetime = 0; - detector.validateFVGUsingPV = false; - detector.applyPVToFVGBoundary = false; - detector.selectRejectedFVGPivots = false; - detector.selectEngulfedFVGPivots = false; - detector.validateFVGUsingManalyser = false; - detector.applyLastBarToFVGBoundary = false; - detector.selectOnlyFVGWhichHasIndirectionalLastBar = false; - - // - detector.detectFVGBullishPivots = false; - detector.detectFVGBearishPivots = false; - - // - // TREND ... - - // - detector.maxAllowedTrendLifetime = 0; - detector.detectTrendBullishPivots = false; - detector.detectTrendBearishPivots = false; - - // - // DRAWER ... - - // - // Initialize and Configure Drawer ... - drawer = new XCXCAEAPOIDrawer(detector); - - // - drawer.ignoreUpdateOSCTos = true; - - // - // Configure Drawer ... - drawer.drawSWHPivots = false; - drawer.drawSWLPivots = false; - drawer.drawPeakPivots = true; - drawer.drawValePivots = true; - drawer.drawOBBullishPivots = false; - drawer.drawOBBearishPivots = false; - drawer.drawFVGBullishPivots = false; - drawer.drawFVGBearishPivots = false; - drawer.drawTrendBullishPivots = false; - drawer.drawTrendBearishPivots = false; - - // - // Configure Styles ... - - // - // SWING ... - - // - // SWH ... - XCAPivotStyle swhStyle; - swhStyle.width = 2; - swhStyle.clr = clrMagenta; - swhStyle.style = STYLE_SOLID; - drawer.swhPivotStyle = swhStyle; - swhStyle.Clean(); - - // - // SWL ... - XCAPivotStyle swlStyle; - swlStyle.width = 2; - swlStyle.clr = clrAqua; - swlStyle.style = STYLE_SOLID; - drawer.swlPivotStyle = swlStyle; - swlStyle.Clean(); - - // - // PV ... - - // - // PEAK ... - XCAPivotStyle peakStyle; - peakStyle.width = 2; - peakStyle.clr = clrMagenta; - peakStyle.style = STYLE_SOLID; - drawer.peakPivotStyle = peakStyle; - peakStyle.Clean(); - - // - // VALE ... - XCAPivotStyle valeStyle; - valeStyle.width = 2; - valeStyle.clr = clrAqua; - valeStyle.style = STYLE_SOLID; - drawer.valePivotStyle = valeStyle; - valeStyle.Clean(); - - // - // OB ... - - // - // Bullish ... - XCAPivotStyle obBullishStyle; - obBullishStyle.width = 2; - obBullishStyle.clr = clrLime; - obBullishStyle.style = STYLE_DASH; - drawer.obBullishPivotStyle = obBullishStyle; - obBullishStyle.Clean(); - - // - // Bearish ... - XCAPivotStyle obBearishStyle; - obBearishStyle.width = 2; - obBearishStyle.clr = clrRed; - obBearishStyle.style = STYLE_DASH; - drawer.obBearishPivotStyle = obBearishStyle; - obBearishStyle.Clean(); - - // - // FVG ... - - // - // Bullish ... - XCAPivotStyle fvgBullishStyle; - fvgBullishStyle.width = 2; - fvgBullishStyle.clr = clrLime; - fvgBullishStyle.style = STYLE_DASH; - drawer.fvgBullishPivotStyle = fvgBullishStyle; - fvgBullishStyle.Clean(); - - // - // Bearish ... - XCAPivotStyle fvgBearishStyle; - fvgBearishStyle.width = 2; - fvgBearishStyle.clr = clrRed; - fvgBearishStyle.style = STYLE_DASH; - drawer.fvgBearishPivotStyle = fvgBearishStyle; - fvgBearishStyle.Clean(); - - // - // TREND ... - - // - // Bullish ... - XCAPivotStyle trendBullishStyle; - trendBullishStyle.width = 2; - trendBullishStyle.clr = clrLime; - trendBullishStyle.style = STYLE_DOT; - drawer.trendBullishPivotStyle = trendBullishStyle; - trendBullishStyle.Clean(); - - // - // Bearish ... - XCAPivotStyle trendBearishStyle; - trendBearishStyle.width = 2; - trendBearishStyle.clr = clrRed; - trendBearishStyle.style = STYLE_DOT; - drawer.trendBearishPivotStyle = trendBearishStyle; - trendBearishStyle.Clean(); - } - - // -}; - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/tmp.detect.tb.mq5 b/Documents/BKP/XCAEA_BKP/tmp.detect.tb.mq5 deleted file mode 100644 index 07d149d7..00000000 --- a/Documents/BKP/XCAEA_BKP/tmp.detect.tb.mq5 +++ /dev/null @@ -1,1214 +0,0 @@ - -// -// Detect Trigger Block ... -bool DetectTriggerBlock( - // - string symbol, - ENUM_TIMEFRAMES period, - // - XTriggerBlock &tb, - // - XCBarAnalyser *barAnalyser, - // - // Required Buffers ... - const double &_atrBuffer[], - const double &_rsiBuffer[], - const double &_adxBuffer[], - const double &_adxpBuffer[], - const double &_adxnBuffer[], - const double &_peakBuffer[], - const double &_valeBuffer[], - const double &_deltaBuffer[], - const double &_sarBuffer[], - const double &_sarStateBuffer[], - const double &_trendBuffer[], - const double &_trendStateBuffer[], - const double &_atrUpperBuffer[], - const double &_atrLowerBuffer[], - const double &_sBarOpenSBuffer[], - const double &_sBarCloseBuffer[], - const double &_hkSBarOpenBuffer[], - const double &_hkSBarCloseBuffer[], - const double &_peakGoldenBuffer[], - const double &_valeGoldenBuffer[], - const double &_deltaSignalBuffer[], - const double &_bullishVolumeSignalBuffer[], - const double &_bearishVolumeSignalBuffer[], - // - int barIndex, - // - int _r2r, - double _slAtrMultiplier, - // - // Configs ... - double _rsiOBLevel, - double _rsiOSLevel, - double _adxThreshold, - // - // Validators ... - // - bool _forceOBBarType = false, - bool _forceFVGBarType = false, - bool _forceHasSwing = false, - bool _forceHasFLiquidity = false, - bool _forceHasRLiquidity = false, - bool _validateGapSequence = false, - bool _validateBlockEdgeBreakout = false, - // - // Filters ... - bool _filterBasedOnPV = false, - bool _filterBasedOnSar = false, - bool _filterBasedOnRSI = false, - bool _filterBasedOnADX = false, - bool _filterBasedOnATR = false, - bool _filterBasedOnTrend = false, - bool _filterBasedOnDelta = false, - bool _filterBasedOnVolume = false, - bool _filterBasedOnSignalBar = false, - bool _filterBasedOnHKSignalBar = false // -) -{ - // - bool result = false; - - // - // Custom Configs ... - - // // - // _r2r = 2; - // _slAtrMultiplier = 1; - - // // - // // Validators ... - // _forceHasSwing = true; - // _forceOBBarType = true; - // _forceFVGBarType = true; - // _validateGapSequence = true; - - // // - // _forceHasFLiquidity = false; - // _forceHasRLiquidity = false; - // _validateBlockEdgeBreakout = true; - - // // - // // Filters ... - // _filterBasedOnPV = true; - // _filterBasedOnATR = true; - // _filterBasedOnDelta = true; - // _filterBasedOnVolume = true; - - // // - // _filterBasedOnSar = true; - // _filterBasedOnRSI = false; - // _filterBasedOnADX = false; - // _filterBasedOnTrend = false; - // _filterBasedOnSignalBar = true; - // _filterBasedOnHKSignalBar = true; - - // - tb.Clean(); - - // - result = barAnalyser != NULL; - if (!result) - { - return result; - } - - // - int zIDX = 0; - bool has = false; - bool isDone = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Retrieve Required Bars ... - - // - XOHCL iBar; - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - has = zBar.Init( - symbol, - period, - barIndex // - ); - - // - // Detect Based Order Block ... - has = - has && - barAnalyser.IsOB( - zBar, - tb.ob, - _forceFVGBarType, // Force FVG Bar Type ... - _forceOBBarType // Force Block Two Bar Checking ... - ); - - // - // Detect Based Fair Value Gap ... - has = - has && - barAnalyser.IsFVG( - zBar, - tb.fvg, - _forceFVGBarType // Force FVG Bar Type ... - ); - - // - // Clone Trigger Block ... - if (has) - { - // - tb.trigger = tb.ob; - tb.trigger.type = "XTRGB"; - } - - // - bool isBullish = - has && - tb.IsBullish(); - - // - bool isBearish = - has && - tb.IsBearish(); - - // - int toIDX = tb.ToIndex(); - int fromIDX = tb.FromIndex(); - - // - // Verifications and Filters ... - - // - int loopback = 144; - - // - // Forces ... - - // - // Force Has Proper Swing ... - if (has && - _forceHasSwing) - { - // - XOHCL iPBar; - XOHCL iP2Bar; - toIDX = tb.ToIndex(); - fromIDX = tb.FromIndex(); - for (int i = toIDX; i <= fromIDX; i++) - { - // - // Initialize iBar ... - isDone = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - isDone = - isDone && - iBar.GetPreviousBar(iPBar); - isDone = - isDone && - iPBar.GetPreviousBar(iP2Bar); - isDone = - isDone && - barAnalyser.IsSimpleSwing( - iBar, - iDir // - ) && - iDir == tb.GetDirection(); - if (isDone) - { - // - bool canSet = - !tb.swingBar.IsValid() - ? true - : (isBullish - ? tb.swingBar.low > iP2Bar.low - : tb.swingBar.high < iP2Bar.high); - if (canSet) - { - tb.swingBar = iP2Bar; - } - } - - // - iBar.Clean(); - iPBar.Clean(); - iP2Bar.Clean(); - } - - // - has = tb.swingBar.IsValid(); - } - - // - // Force Has Liquidity ... - // TODO: Add Validation based on Liquidities - // if necessary ... - if (has && - (_forceHasFLiquidity || - _forceHasRLiquidity)) - { - // - toIDX = tb.ToIndex(); - fromIDX = tb.FromIndex(); - for (int i = toIDX; i < fromIDX + loopback; i++) - { - // - // Initialize iBar ... - isDone = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - - // - bool isRejected = - isDone && - barAnalyser.IsRejected( - iBar, - iDir, - false, // Force Bar Type ... - true // Force Fibo Pressure ... - ); - - // - // Following Liquidity ... - bool isFLiq = - isDone && - isRejected && - iDir == tb.GetDirection() && - (isBullish - ? iBar.low < tb.trigger.lower - : iBar.high > tb.trigger.upper); - if (isFLiq && - _forceHasFLiquidity && - !tb.fLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iDir, - tb.fLiquidity, - tb.trigger.to // - ); - } - - // - // Reversal Liquidity ... - bool isRLiq = - isDone && - isRejected && - Opposit(iDir) == tb.GetDirection() && - (isBullish - ? iBar.low > tb.trigger.upper - : iBar.high < tb.trigger.lower); - if (isRLiq && - _forceHasRLiquidity && - !tb.rLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iDir, - tb.rLiquidity, - tb.trigger.to // - ); - } - - // - // Checking Conditions ... - isDone = - (!_forceHasFLiquidity - ? true - : tb.fLiquidity.IsValid()) && - (!_forceHasRLiquidity - ? true - : tb.rLiquidity.IsValid()); - if (isDone) - { - // - iBar.Clean(); - break; - } - - // - iBar.Clean(); - } - - // - // Checking Conditions ... - has = - (!_forceHasFLiquidity - ? true - : tb.fLiquidity.IsValid()) && - (!_forceHasRLiquidity - ? true - : tb.rLiquidity.IsValid()); - } - - // - // Validations ... - - // - // Validating Gap Sequence means - // Gap Bars must Follow each Other ... - if (has && - _validateGapSequence) - { - // - XOHCL iPBar; - toIDX = tb.fvg.ToIndex(); - fromIDX = tb.fvg.FromIndex(); - - // - for (int i = toIDX; i < fromIDX - 1; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - has = - has && - iBar.GetPreviousBar(iPBar); - has = - has && - (isBullish - ? iBar.low > iPBar.low - : iBar.high < iPBar.high); - if (!has) - { - break; - } - } - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - // Validate Block Edge Breakout ... - if (has && - _validateBlockEdgeBreakout) - { - // - has = tb.fvg.ToBar(iBar); - has = - has && - (isBullish - ? (iBar.GetDown() < tb.ob.upper && - iBar.GetUp() > tb.ob.upper) - : (iBar.GetDown() < tb.ob.lower && - iBar.GetUp() > tb.ob.lower)); - - // - iBar.Clean(); - } - - // - // Filters ... - - // - // PV ... - if (has && - _filterBasedOnPV) - { - // - double iPeak = _peakBuffer[barIndex]; - double iPPeak = _peakBuffer[barIndex + 1]; - double iP2Peak = _peakBuffer[barIndex + 2]; - - // - double iPeakGolden = _peakGoldenBuffer[barIndex]; - double iPPeakGolden = _peakGoldenBuffer[barIndex + 1]; - double iP2PeakGolden = _peakGoldenBuffer[barIndex + 2]; - - // - double iVale = _valeBuffer[barIndex]; - double iPVale = _valeBuffer[barIndex + 1]; - double iP2Vale = _valeBuffer[barIndex + 2]; - - // - double iValeGolden = _valeGoldenBuffer[barIndex]; - double iPValeGolden = _valeGoldenBuffer[barIndex + 1]; - double iP2ValeGolden = _valeGoldenBuffer[barIndex + 2]; - - // - // TODO: Fix this ... - has = - has && - (isBullish - ? (tb.trigger.lower <= iVale && - tb.trigger.upper < iPeak - // || tb.trigger.lower <= iValeGolden - ) - : (tb.trigger.upper >= iPeak && - tb.trigger.lower > iVale - // || tb.trigger.upper >= iPeakGolden - )); - } - - // - // SAR ... - if (has && - _filterBasedOnSar) - { - // - double iSarState = _sarStateBuffer[barIndex]; - double iPSarState = _sarStateBuffer[barIndex + 1]; - double iP2SarState = _sarStateBuffer[barIndex + 2]; - - // - bool isSarBullish = iSarState > 0; - bool isPSarBullish = iPSarState > 0; - bool isP2SarBullish = iP2SarState > 0; - - // - bool isSarBearish = iSarState < 0; - bool isPSarBearish = iPSarState < 0; - bool isP2SarBearish = iP2SarState < 0; - - // - bool isSarSwitchedToBullish = - isSarBullish && - !isPSarBullish; - - // - bool isSarSwitchedToBearish = - isSarBearish && - !isPSarBearish; - - // - bool isSarPSwitchedToBullish = - isPSarBullish && - !isP2SarBullish; - - // - bool isSarPSwitchedToBearish = - isPSarBearish && - !isP2SarBearish; - - // - has = - has && - (isBullish - ? (isSarSwitchedToBullish || - isSarPSwitchedToBullish) - : (isSarSwitchedToBearish || - isSarPSwitchedToBearish)); - } - - // - // RSI ... - if (has && - _filterBasedOnRSI) - { - // - double rsiTrend = (_rsiOBLevel + _rsiOSLevel) / 2; - - // - double iRSI = _rsiBuffer[barIndex]; - double iPRSI = _rsiBuffer[barIndex + 1]; - double iP2RSI = _rsiBuffer[barIndex + 2]; - - // - bool isRSICrossedOverOS = - iRSI > _rsiOSLevel && - iPRSI <= _rsiOSLevel; - - // - bool isRSICrossedUnderOB = - iRSI < _rsiOBLevel && - iPRSI >= _rsiOBLevel; - - // - bool isPRSICrossedOverOS = - iPRSI > _rsiOSLevel && - iP2RSI <= _rsiOSLevel; - - // - bool isPRSICrossedUnderOB = - iPRSI < _rsiOBLevel && - iP2RSI >= _rsiOBLevel; - - // - has = - has && - (isBullish - ? (isRSICrossedOverOS || - isPRSICrossedOverOS) - : (isRSICrossedUnderOB || - isPRSICrossedUnderOB)); - } - - // - // ADX ... - if (has && - _filterBasedOnADX) - { - // - // ADX ... - double iADX = _adxBuffer[barIndex]; - double iPADX = _adxBuffer[barIndex + 1]; - double iP2ADX = _adxBuffer[barIndex + 2]; - - // - // ADX +DI ... - double iADXP = _adxpBuffer[barIndex]; - double iPADXP = _adxpBuffer[barIndex + 1]; - double iP2ADXP = _adxpBuffer[barIndex + 2]; - - // - // ADX -DI ... - double iADXN = _adxnBuffer[barIndex]; - double iPADXN = _adxnBuffer[barIndex + 1]; - double iP2ADXN = _adxnBuffer[barIndex + 2]; - - // - // Preparing Conditions ... - - // - bool isADXBullish = iADX > _adxThreshold; - bool isADXBearish = iADX < _adxThreshold; - - // - bool isPADXBullish = iPADX > _adxThreshold; - bool isPADXBearish = iPADX < _adxThreshold; - - // - bool isP2ADXBullish = iP2ADX > _adxThreshold; - bool isP2ADXBearish = iP2ADX < _adxThreshold; - - // - bool isADXSwitchedToBullish = - isADXBullish && - !isPADXBullish; - - // - bool isADXSwitchedToBearish = - isADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isPADXBearish && - !isP2ADXBearish; - - // - has = - has && - (isBullish - ? (isADXSwitchedToBullish || - isPADXSwitchedToBullish) - : (isADXSwitchedToBearish || - isPADXSwitchedToBearish)); - } - - // - // ATR ... - if (has && - _filterBasedOnATR) - { - // - fromIDX = tb.FromIndex(); - double iATRUpper = _atrUpperBuffer[fromIDX]; - double iATRLower = _atrLowerBuffer[fromIDX]; - - // - has = - has && - (isBullish - ? tb.trigger.lower < iATRLower - : tb.trigger.upper > iATRUpper); - } - - // - // TREND ... - if (has && - _filterBasedOnTrend) - { - // - double iTrendState = _trendStateBuffer[barIndex]; - double iPTrendState = _trendStateBuffer[barIndex + 1]; - - // - bool isTrendBullish = iTrendState > 0; - bool isPTrendBullish = iPTrendState > 0; - - // - bool isTrendBearish = iTrendState < 0; - bool isPTrendBearish = iPTrendState < 0; - - // - double trends[]; - int toIDX = tb.ToIndex(); - int fromIDX = tb.FromIndex(); - double iTrend = _trendBuffer[toIDX]; - for (int i = toIDX; i <= fromIDX; i++) - { - // - Add( - _trendBuffer[i], - trends // - ); - } - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - bool isTrendUp = - iTrend > trendsMin && - iTrend >= trendsAVG; - - // - bool isTrendDown = - iTrend < trendsMax && - iTrend <= trendsAVG; - - // - bool isTrendSwitchedToBullish = - isTrendUp && - isTrendBullish && - !isPTrendBullish; - - // - bool isTrendSwitchedToBearish = - isTrendDown && - isTrendBearish && - !isPTrendBearish; - - // - has = - has && - (isBullish - ? isTrendSwitchedToBullish - : isTrendSwitchedToBearish); - } - - // - // DELTA ... - if (has && - _filterBasedOnDelta) - { - // - double iDelta = _deltaBuffer[barIndex]; - double iPDelta = _deltaBuffer[barIndex + 1]; - - // - bool isDeltaUp = iDelta > iPDelta; - bool isDeltaDown = iDelta < iPDelta; - - // - double iDeltaSignal = _deltaSignalBuffer[barIndex]; - double iPDeltaSignal = _deltaSignalBuffer[barIndex + 1]; - - // - bool isDeltaSignalUp = iDeltaSignal > iPDeltaSignal; - bool isDeltaSignalDown = iDeltaSignal < iPDeltaSignal; - - // - bool isDeltaSwitchedToBullish = - isDeltaUp && - isDeltaSignalUp && - iDelta > iDeltaSignal && - iPDelta < iPDeltaSignal; - - // - bool isDeltaSwitchedToBearish = - isDeltaDown && - isDeltaSignalDown && - iDelta < iDeltaSignal && - iPDelta > iPDeltaSignal; - - // - has = - has && - (isBullish - ? isDeltaSwitchedToBullish - : isDeltaSwitchedToBearish); - } - - // - // VOLUME ... - if (has && - _filterBasedOnVolume) - { - // - double iBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex]; - double iPBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex + 1]; - - // - bool isBullishVolumeSignalUp = iBullishVolumeSignal > iPBullishVolumeSignal; - bool isBullishVolumeSignalDown = iBullishVolumeSignal < iPBullishVolumeSignal; - - // - double iBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex]; - double iPBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex + 1]; - - // - bool isBearishVolumeSignalUp = iBearishVolumeSignal > iPBearishVolumeSignal; - bool isBearishVolumeSignalDown = iBearishVolumeSignal < iPBearishVolumeSignal; - - // - bool isVolumeSwitchdToBullish = - isBullishVolumeSignalUp && - !isBearishVolumeSignalUp && - iBullishVolumeSignal > iBearishVolumeSignal && - iPBullishVolumeSignal < iPBearishVolumeSignal; - - // - bool isVolumeSwitchdToBearish = - isBearishVolumeSignalUp && - !isBullishVolumeSignalUp && - iBearishVolumeSignal > iBullishVolumeSignal && - iPBearishVolumeSignal < iPBullishVolumeSignal; - - // - has = - has && - (isBullish - ? isVolumeSwitchdToBullish - : isVolumeSwitchdToBearish); - } - - // - // SIGNAL Bar ... - if (has && - _filterBasedOnSignalBar) - { - // - double iSignalOpen = _sBarOpenSBuffer[barIndex]; - double iPSignalOpen = _sBarOpenSBuffer[barIndex + 1]; - - // - double iSignalClose = _sBarCloseBuffer[barIndex]; - double iPSignalClose = _sBarCloseBuffer[barIndex + 1]; - - // - bool isSignalBarBullish = iSignalOpen < iSignalClose; - bool isPSignalBarBullish = iPSignalOpen < iPSignalClose; - - // - bool isSignalBarBearish = iSignalOpen > iSignalClose; - bool isPSignalBarBearish = iPSignalOpen > iPSignalClose; - - // - bool isSignalBarSwitchedToBullish = - isSignalBarBullish && - !isPSignalBarBullish; - - // - bool isSignalBarSwitchedToBearish = - isSignalBarBearish && - !isPSignalBarBearish; - - // - has = - has && - (isBullish - ? isSignalBarSwitchedToBullish - : isSignalBarSwitchedToBearish); - } - - // - // HK SIGNAL Bar ... - if (has && - _filterBasedOnHKSignalBar) - { - // - double iHKSignalOpen = _hkSBarOpenBuffer[barIndex]; - double iPHKSignalOpen = _hkSBarOpenBuffer[barIndex + 1]; - - // - double iHKSignalClose = _hkSBarCloseBuffer[barIndex]; - double iPHKSignalClose = _hkSBarCloseBuffer[barIndex + 1]; - - // - bool isHKSignalBarBullish = iHKSignalOpen < iHKSignalClose; - bool isPHKSignalBarBullish = iPHKSignalOpen < iPHKSignalClose; - - // - bool isHKSignalBarBearish = iHKSignalOpen > iHKSignalClose; - bool isPHKSignalBarBearish = iPHKSignalOpen > iPHKSignalClose; - - // - bool isHKSignalBarSwitchedToBullish = - isHKSignalBarBullish && - !isPHKSignalBarBullish; - - // - bool isHKSignalBarSwitchedToBearish = - isHKSignalBarBearish && - !isPHKSignalBarBearish; - - // - has = - has && - (isBullish - ? isHKSignalBarSwitchedToBullish - : isHKSignalBarSwitchedToBearish); - } - - // - // Valdating Directional Trending ... - bool _filterBasedOnDirection = false; - if (has && - _filterBasedOnDirection) - { - // - iBar.Clean(); - fromIDX = tb.FromIndex(); - int loopbackForValidating = 30; - for (int i = fromIDX; i < fromIDX + loopbackForValidating; i++) - { - // - // Initialize iBar ... - iBar.Clean(); - has = iBar.Init( - symbol, - period, - i // - ); - - // - has = - has && - (isBullish - ? iBar.high < tb.trigger.upper - : iBar.low > tb.trigger.lower); - if (!has) - { - break; - } - } - - // - // Update Trigger Block ... - if (has) - { - tb.trigger.from = iBar.time; - } - - // - iBar.Clean(); - } - - // - // Preparing Signal ... - if (has) - { - // - // CArrayObj *tbObjects = new CArrayObj(); - // DrawTriggerBlock( - // tb, - // drawer, - // tbObjects, - // NULL // - // ); - - // - double targets[]; - for (int i = 1; i <= _r2r; i++) - { - // - Add( - (double)i, - targets // - ); - } - - // - double iATR = 0; - if (barIndex > 0 && - barIndex < ArraySize(_atrBuffer)) - { - iATR = _atrBuffer[barIndex]; - } - double slAdditional = _slAtrMultiplier * iATR; - - // - has = ToSignal( - tb.trigger, - tb.signal, - targets, - slAdditional // - ); - } - - // - result = has; - - // - return result; -} - -// -// Signal ... -// int signalR2R; // Risk Reward Ratio -// bool drawSignals; // Draw Signal -// bool drawTriggerBlock; // Draw Trigger Block -// double slAtrMultiplier; // ATR Multiplier for SL - -// -// Validating ... -bool forceHasSwing; // Force Blocks to Have Swing -bool forceOBBarType; // Force Block Has Reversal Bar -bool forceOBFVGBarType; // Force FVG Has Same Bars -bool forceHasFLiquidity; // Force Blocks to Have Following Liquidity -bool forceHasRLiquidity; // Force Blocks to Have Reversal Liquidity -bool validateGapSequence; // Validate Block's Gap Sequence -bool validateBlockEdgeBreakout; // Validate Block's Edge Breakout - -// -// Filtering ... -bool filterBasedOnPV; // Filter Based on Peak and Vale -bool filterBasedOnSar; // Filter Based on Sar -bool filterBasedOnRSI; // Filter Based on RSI -bool filterBasedOnADX; // Filter Based on ADX -bool filterBasedOnATR; // Filter Based on ATR -bool filterBasedOnTrend; // Filter Based on Trend -bool filterBasedOnDelta; // Filter Based on Delta -bool filterBasedOnVolume; // Filter Based on Volume -bool filterBasedOnSignalBar; // Filter Based on Signal Bar -bool filterBasedOnHKSignalBar; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -string alertPrefix; // Alert Prefix -bool logAlerts; // Log Alerts -bool pushAlerts; // Push Alerts -bool mailAlerts; // Mail Alerts -bool terminalAlerts; // Terminal Alerts - - // - // Initialize and Configure Alert ... - mAlert = new XCAlert(); - mEnableAlerts = - _logAlerts || - _pushAlerts || - _mailAlerts || - _terminalAlerts; - string mPrefix = ShortName + - (!IsValid(mAlertPrefix) - ? "" - : "[" + mAlertPrefix + "]"); - mAlert.SetPrefix(mPrefix); - mAlert.SetLogAlerts(_logAlerts); - mAlert.SetMailAlerts(_mailAlerts); - mAlert.SetPushAlerts(_pushAlerts); - mAlert.SetEnableAlerts(mEnableAlerts); - mAlert.SetTerminalAlerts(_terminalAlerts); - -// -// Validating ... -forceHasSwing = false; // Force Blocks to Have Swing -forceOBBarType = false; // Force Block Has Reversal Bar -forceOBFVGBarType = false; // Force FVG Has Same Bars -forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -validateGapSequence = false; // Validate Block's Gap Sequence -validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -filterBasedOnPV = false; // Filter Based on Peak and Vale -filterBasedOnSar = false; // Filter Based on Sar -filterBasedOnRSI = false; // Filter Based on RSI -filterBasedOnADX = false; // Filter Based on ADX -filterBasedOnATR = false; // Filter Based on ATR -filterBasedOnTrend = false; // Filter Based on Trend -filterBasedOnDelta = false; // Filter Based on Delta -filterBasedOnVolume = false; // Filter Based on Volume -filterBasedOnSignalBar = false; // Filter Based on Signal Bar -filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -alertPrefix = ""; // Alert Prefix -logAlerts = false; // Log Alerts -pushAlerts = false; // Push Alerts -mailAlerts = false; // Mail Alerts -terminalAlerts = false; // Terminal Alerts - -// -// Validating ... -forceHasSwing = false; // Force Blocks to Have Swing -forceOBBarType = false; // Force Block Has Reversal Bar -forceOBFVGBarType = false; // Force FVG Has Same Bars -forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -validateGapSequence = false; // Validate Block's Gap Sequence -validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -filterBasedOnPV = false; // Filter Based on Peak and Vale -filterBasedOnSar = false; // Filter Based on Sar -filterBasedOnRSI = false; // Filter Based on RSI -filterBasedOnADX = false; // Filter Based on ADX -filterBasedOnATR = false; // Filter Based on ATR -filterBasedOnTrend = false; // Filter Based on Trend -filterBasedOnDelta = false; // Filter Based on Delta -filterBasedOnVolume = false; // Filter Based on Volume -filterBasedOnSignalBar = false; // Filter Based on Signal Bar -filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -alertPrefix = ""; // Alert Prefix -logAlerts = false; // Log Alerts -pushAlerts = false; // Push Alerts -mailAlerts = false; // Mail Alerts -terminalAlerts = false; // Terminal Alerts - -"", // Validating ... - mInputs.forceHasSwing, - mInputs.forceOBBarType, - mInputs.forceOBFVGBarType, - mInputs.forceHasFLiquidity, - mInputs.forceHasRLiquidity, - mInputs.validateGapSequence, - mInputs.validateBlockEdgeBreakout, - "", // Filtering ... - mInputs.filterBasedOnPV, - mInputs.filterBasedOnSar, - mInputs.filterBasedOnRSI, - mInputs.filterBasedOnADX, - mInputs.filterBasedOnATR, - mInputs.filterBasedOnTrend, - mInputs.filterBasedOnDelta, - mInputs.filterBasedOnVolume, - mInputs.filterBasedOnSignalBar, - mInputs.filterBasedOnHKSignalBar, - "", // Alerts ... - mInputs.alertPrefix, - mInputs.logAlerts, - mInputs.pushAlerts, - mInputs.mailAlerts, - mInputs.terminalAlerts, - - // - // Validating ... - input group "Validating"; -input bool forceHasSwing = false; // Force Blocks to Have Swing -input bool forceObBarType = false; // Force Block Has Reversal Bar -input bool forceOBFVGBarType = false; // Force FVG Has Same Bars -input bool forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -input bool forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -input bool validateGapSequence = false; // Validate Block's Gap Sequence -input bool validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -input group "Filtering"; -input bool filterBasedOnPV = false; // Filter Based on Peak and Vale -input bool filterBasedOnSar = false; // Filter Based on Sar -input bool filterBasedOnRSI = false; // Filter Based on RSI -input bool filterBasedOnADX = false; // Filter Based on ADX -input bool filterBasedOnATR = false; // Filter Based on ATR -input bool filterBasedOnTrend = false; // Filter Based on Trend -input bool filterBasedOnDelta = false; // Filter Based on Delta -input bool filterBasedOnVolume = false; // Filter Based on Volume -input bool filterBasedOnSignalBar = false; // Filter Based on Signal Bar -input bool filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -input group "Alerts"; -input string mAlertPrefix = ""; // Alert Prefix -input bool _logAlerts = false; // Log Alerts -input bool _pushAlerts = false; // Push Alerts -input bool _mailAlerts = false; // Mail Alerts -input bool _terminalAlerts = false; // Terminal Alerts - - - // - // Set Validators ... - eaInputs.forceHasSwing = eaForceHasSwing; - eaInputs.forceOBBarType = eaForceOBBarType; - eaInputs.forceOBFVGBarType = eaForceOBFVGBarType; - eaInputs.forceHasFLiquidity = eaForceHasFLiquidity; - eaInputs.forceHasRLiquidity = eaForceHasRLiquidity; - eaInputs.validateGapSequence = eaValidateGapSequence; - eaInputs.validateBlockEdgeBreakout = eaValidateBlockEdgeBreakout; - - // - // Set Filters ... - eaInputs.filterBasedOnPV = eaFilterBasedOnPV; - eaInputs.filterBasedOnSar = eaFilterBasedOnSar; - eaInputs.filterBasedOnRSI = eaFilterBasedOnRSI; - eaInputs.filterBasedOnADX = eaFilterBasedOnADX; - eaInputs.filterBasedOnATR = eaFilterBasedOnATR; - eaInputs.filterBasedOnTrend = eaFilterBasedOnTrend; - eaInputs.filterBasedOnDelta = eaFilterBasedOnDelta; - eaInputs.filterBasedOnVolume = eaFilterBasedOnVolume; - eaInputs.filterBasedOnSignalBar = eaFilterBasedOnSignalBar; - eaInputs.filterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar; - - // - // Alerts ... - eaInputs.alertPrefix = eaTag; - eaInputs.logAlerts = false; // eaLogAlerts; - eaInputs.pushAlerts = false; // eaMailAlerts; - eaInputs.mailAlerts = false; // eaPushAlerts; - eaInputs.terminalAlerts = false; // eaTerminalAlerts; - - - - // - // TODO: Remove this ... - // Temparory Testing Configs ... - // validations.maxAllowedRange = 200; - // validations.forceHasSwing = true; - // validations.forceFVGBarType = true; - // validations.forceOBBarType = true; - // validations.validateGapSequence = true; - // validations.validateBlockEdgeBreakout = true; - // validations.liquidityLoopback = 144; - // validations.forceHasFLiquidity = true; - // validations.forceHasRLiquidity = true; - // validations.minAllowedBlockLength = 7; - - // - // TODO: Remove this ... - // filters.bosLoopback = 0; - // filters.filterBasedOnPV = true; - // filters.filterBasedOnSar = true; - // filters.forceSarSwitched = false; - // filters.forceSarOnBothSide = true; - // filters.forceSarHasBreakout = true; - // filters.forceSarHasReversalSide = false; - // filters.filterBasedOnRSI = false; - // filters.forceHasRSITrending = false; - // filters.forceHasRSIVPattern = false; - // filters.forceHasRSICrossing = false; - // filters.filterBasedOnADX = true; - // filters.forceHasADXTrending = false; - // filters.forceHasADXCrossing = true; - // filters.filterBasedOnATR = true; - // filters.forceHasATRTrending = true; - // filters.forceHasATRBreakout = true; - // filters.filterBasedOnTrend = false; - // filters.forceHasTrendDir = false; - // filters.forceHasTrendPlace = false; - // filters.forceHasTrendChange = false; - // filters.forceHasTrendTrending = false; - // filters.forceHasTrendRejection = false; - // filters.forceHasTrendLineInside = false; - // filters.forceHasTrendDirOnBothSide = false; - // filters.filterBasedOnDelta = false; - // filters.filterBasedOnVolume = false; - // filters.filterBasedOnSignalBar = true; - // filters.filterBasedOnHKSignalBar = true; diff --git a/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.lib.mq5 b/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.lib.mq5 deleted file mode 100644 index 06070b0d..00000000 --- a/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.lib.mq5 +++ /dev/null @@ -1,3053 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Library -// --------------------------------------- -// Name: XCATBLib -// Description: required Parsers for XCATB ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright `023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Helpers/x-saherelm.x121.xcatb.helper.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x-poi.lib.mq5" - -// -// Definiions ... - -// -#define XLiquidityToken "XLQ"; -#define XTriggerBlockToken "XTRG"; - -// -struct XTriggerBlock -{ - // - // Props ... - XBoxZone ob; // Order Block - XBoxZone fvg; // Fair Value Gap - XOHCL swingBar; // Swing of Trigger - XBoxZone trigger; // Trigger Block - XBoxZone rLiquidity; // Reversal Liquidity - XBoxZone fLiquidity; // Following Liquidity - - // - XSignal signal; // Pepared Signal - - // - // Constructor ... - XTriggerBlock() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - ob.Clean(); - fvg.Clean(); - signal.Clean(); - trigger.Clean(); - swingBar.Clean(); - rLiquidity.Clean(); - fLiquidity.Clean(); - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = ob.IsValid() && - fvg.IsValid() && - trigger.IsValid(); - - // - return result; - } - - // - bool IsBullish() - { - return IsValid() && - ob.IsBullish(); - } - - // - bool IsBearish() - { - return IsValid() && - ob.IsBearish(); - } - - // - int ToIndex() - { - return trigger.ToIndex(); - } - - // - int FromIndex() - { - return trigger.FromIndex(); - } - - // - ENUM_X_DIRECTION GetDirection() - { - // - ENUM_X_DIRECTION result = X_DIRECTION_NONE; - - // - if (IsValid()) - { - result = ob.dir; - } - - // - return result; - } - - // -}; - -// -// Trigger Block Validation Rules ... -struct XTriggerBlockValidationRules -{ - // - // Props ... - bool forceHasSwing; // Force Block to Has Propper Swing ... - bool forceOBBarType; // Force Order Block to Has InDirectional Bars ... - int minRequiredOBBar; // Min Required OB Bar ... - bool forceFVGBarType; // Force Fair Value Gaps Bars Type ... - double maxAllowedRange; // Max Allowed Order Block Range ... - double minAllowedRange; // Min Allowed Order Block Range ... - bool forceHasFLiquidity; // Force Order Block To Has Reversal Liquidity ... - bool forceHasRLiquidity; // Force Order Block to Has Following Liquidity ... - int liquidityLoopback; // Liquidity Detection Loopback ... - bool validateGapSequence; // Validate Fair Value Gaps Bar Sequences ... - bool validateBlockEdgeBreakout; // Validate Order Block Edge Breakeout ... - - // - // Constructor(s) ... - XTriggerBlockValidationRules() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - maxAllowedRange = 0; - minAllowedRange = 0; - minRequiredOBBar = 0; - liquidityLoopback = 0; - forceHasSwing = false; - forceOBBarType = false; - forceFVGBarType = false; - forceHasFLiquidity = false; - forceHasRLiquidity = false; - validateGapSequence = false; - validateBlockEdgeBreakout = false; - - // - ZeroMemory(this); - } -}; - -// -// Trigger Block Filters ... -struct XTriggerBlockFilters -{ - // - // Props ... - bool filterBasedOnPV; // Filter Based On PV ... - bool filterBasedOnSar; // Filter Based On SAR ... - bool filterBasedOnRSI; // Filter Based On RSI ... - bool filterBasedOnADX; // Filter Based On ADX ... - bool filterBasedOnATR; // Filter Based On ATR ... - bool filterBasedOnTrend; // Filter Based On Trend ... - bool filterBasedOnDelta; // Filter Based On Delta ... - bool filterBasedOnVolume; // Filter Based On Volume ... - bool filterBasedOnSignalBar; // Filter Based on Signal Bar ... - bool filterBasedOnHKSignalBar; // Filter Based On HK Signal Bar ... - - // - int bosLoopback; // PV Based Filtering BOS Lookup ... - - // - // Constructor(s) ... - XTriggerBlockFilters() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - filterBasedOnPV = false; - filterBasedOnSar = false; - filterBasedOnRSI = false; - filterBasedOnADX = false; - filterBasedOnATR = false; - filterBasedOnTrend = false; - filterBasedOnDelta = false; - filterBasedOnVolume = false; - filterBasedOnSignalBar = false; - filterBasedOnHKSignalBar = false; - - // - bosLoopback = 0; - - // - ZeroMemory(this); - } -}; - -// -// Extensions ... - -/** - * Detect Trigger Block ... - * - * @param helper: XCX121XCatbHelper instance pointer ... - * @param barAnalyser: XCBarAnalyser instance pointer ... - * @param triggerBlock: XTriggerBlock Refrence, holds Detected Trigger Block ... - * @param conditions: X121XCatbConditions Refrence, holds Trigger Block Conditions ... - * @param validations: XTriggerBlockValidationRules Refrence, Provides Trigger Block Validation Rules ... - * @param filters: XTriggerBlockFilters Refrence, Provides Trigger Block Filters ... - * @param barIndex: int, Bar Index ... - * @param loopback: int, Loopback for Conditions reading ... - * - * @return ( bool ) - */ -bool DetectTriggerBlock1( - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - XTriggerBlock &triggerBlock, - X121XCatbConditions &conditions, - XTriggerBlockValidationRules &validations, - XTriggerBlockFilters &filters, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - conditions.Clean(); - triggerBlock.Clean(); - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 0); - - // - // Validate Args ... - result = - helper != NULL && - barAnalyser != NULL; - if (!result) - { - return result; - } - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - bool has = false; - string symbol = helper.GetSymbol(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Initial Requirements ... - - // - // Required Bars ... - XOHCL zBar; - XOHCL cBar; - result = - result && - zBar.Init( - symbol, - period, - barIndex // - ); - result = - result && - zBar.GetPreviousBar(cBar); - - // - // Here we Must Detect Order Block ... - // then Detect FVG ... - // then Prepare Trigger Box ... - - // - // Select Application Bar ... - XOHCL iBar; - if (barIndex == 0) - { - iBar = cBar; - } - else if (barIndex > 0) - { - iBar = zBar; - } - iBar = cBar; - result = - result && - iBar.IsValid(); - - // - // Detect Order Block ... - result = - result && - barAnalyser - .IsOB( - iBar, - triggerBlock.ob, - false, - false // - ); - - // - // Detect Fair Value Gap ... - result = - result && - barAnalyser - .IsFVG( - iBar, - triggerBlock.fvg, - false // - ); - - // - // Check Result and Create Trigger Box based on it ... - if (result) - { - // - triggerBlock.trigger = triggerBlock.ob; - triggerBlock.trigger.type = XTriggerBlockToken; - - // - // Update Upper and Lower ... - int toIDX = triggerBlock.ob.ToIndex(); - int fromIDX = triggerBlock.ob.FromIndex(); - - // - iBar.Clean(); - result = iBar.Init( - symbol, - period, - toIDX // - ); - if (result) - { - // - double iLL = iBar.FindLowest(fromIDX - toIDX, MODE_LOW); - double iHH = iBar.FindHighest(fromIDX - toIDX, MODE_HIGH); - - // - triggerBlock.trigger.upper = MathMax(iHH, triggerBlock.trigger.upper); - triggerBlock.trigger.lower = MathMin(iLL, triggerBlock.trigger.lower); - } - - // - iBar.Clean(); - } - - // - // TODO: Remove this ... - // Temparory Testing Configs ... - // validations.maxAllowedRange = 200; - // validations.forceHasSwing = true; - // validations.forceFVGBarType = true; - // validations.forceOBBarType = true; - // validations.validateGapSequence = true; - // validations.validateBlockEdgeBreakout = true; - // validations.liquidityLoopback = 144; - // validations.forceHasFLiquidity = true; - // validations.forceHasRLiquidity = true; - - // - // Apply Validations ... - if (result) - { - // - result = ValidateTriggerBlock( - helper, - barAnalyser, - triggerBlock, - conditions, - validations, - barIndex, - loopback // - ); - - // - if (!result) - { - triggerBlock.Clean(); - } - } - - // - // TODO: Remove this ... - filters.bosLoopback = 30; - filters.filterBasedOnPV = true; - - // - // Apply Filtering ... - if (result) - { - // - result = FilterTriggerBlock( - helper, - barAnalyser, - triggerBlock, - conditions, - filters, - barIndex, - loopback // - ); - - // - if (!result) - { - triggerBlock.Clean(); - } - } - - // - // Summarizing Result ... - result = - result && - triggerBlock.IsValid(); - - // - // Preparing Signal ... - if (result) - { - // - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - zBar.Clean(); - cBar.Clean(); - - // - if (!result) - { - triggerBlock.Clean(); - } - - // - return result; -} - -/** - * Validate a Trigger Block ... - * - * @param helper: XCX121XCatbHelper instance pointer ... - * @param barAnalyser: XCBarAnalyser instance pointer ... - * @param triggerBlock: XTriggerBlock Refrence, Trigger Block ... - * @param conditions: X121XCatbConditions Refrence, Trigger Block Conditions ... - * @param validations: XTriggerBlockValidationRules Refrence, Provides Trigger Block Validation Rules ... - * @param barIndex: int, Bar Index ... - * @param loopback: int, Loopback for Conditions reading ... - * - * @return ( bool ) - */ -bool ValidateTriggerBlock( - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - XTriggerBlock &triggerBlock, - X121XCatbConditions &conditions, - XTriggerBlockValidationRules &validations, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Checking Conditions ... - - // - // Normalize Args ... - conditions.Clean(); - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 0); - - // - // Validate Args ... - result = - helper != NULL && - barAnalyser != NULL && - triggerBlock.IsValid(); - if (!result) - { - return result; - } - - // - // Reading Market Conditions ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - XOHCL iBar; - int count = 0; - int toIDX = -1; - int fromIDX = -1; - bool has = false; - bool isBullish = triggerBlock.IsBullish(); - bool isBearish = triggerBlock.IsBearish(); - double points = GetPoints(triggerBlock.ob.symbol); - ENUM_X_DIRECTION iDir = triggerBlock.GetDirection(); - - // - // Checking Conditions ... - - // - // Range Validation ... - - // - // Max Allowed OB Range ... - if (result && - validations.maxAllowedRange > 0) - { - // - double iRange = triggerBlock.ob.GetRange(); - result = iRange <= (validations.maxAllowedRange * points); - } - - // - // Min Allowed OB Range ... - if (result && - validations.minAllowedRange > 0) - { - // - double iRange = triggerBlock.ob.GetRange(); - result = iRange >= (validations.maxAllowedRange * points); - } - - // - // Has Swing ... - if (result && - validations.forceHasSwing) - { - // - bool isSwing = false; - toIDX = triggerBlock.ToIndex(); - fromIDX = triggerBlock.FromIndex(); - ENUM_X_DIRECTION swingDir = X_DIRECTION_NONE; - for (int i = toIDX; i <= fromIDX; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - conditions.symbol, - conditions.period, - i // - ); - isSwing = - has && - barAnalyser - .IsSimpleSwing( - iBar, - swingDir // - ); - if (isSwing && - swingDir == iDir) - { - break; - } - - // - iBar.Clean(); - } - - // - result = - isSwing && - iBar.IsValid() && - swingDir == iDir; - if (result) - { - // - // Initialize Swing Bar ... - result = triggerBlock - .swingBar - .Init( - iBar.symbol, - iBar.period, - iBar.Index() + 2 // - ); - } - - // - iBar.Clean(); - } - - // - // Force FVG Bar Types ... - if (result && - validations.forceFVGBarType) - { - // - toIDX = triggerBlock.fvg.ToIndex(); - fromIDX = triggerBlock.fvg.FromIndex(); - for (int i = toIDX; i < fromIDX; i++) - { - // - // Initialize iBar ... - result = iBar.Init( - conditions.symbol, - conditions.period, - i // - ); - result = - result && - iDir == iBar.GetDirection(); - - // - iBar.Clean(); - - // - if (!result) - { - break; - } - } - - // - iBar.Clean(); - } - - // - // Force OB Start By InDirectional Bars ... - if (result && - validations.forceOBBarType) - { - // - count = 0; - fromIDX = triggerBlock.fvg.FromIndex() + 1; - int sIDX = fromIDX; - has = true; - while (has) - { - // - // Initialize iBar .. - has = iBar.Init( - conditions.symbol, - conditions.period, - fromIDX // - ); - has = has && - iDir == Opposit(iBar.GetDirection()); - if (has) - { - count++; - } - - // - fromIDX++; - } - - // - int required = - validations.minRequiredOBBar > 0 - ? validations.minRequiredOBBar - : 1; - - // - result = count >= required; - - // - // Update Trigger Block Box based on OB Bar Types ... - if (result) - { - // - result = iBar.Init( - conditions.symbol, - conditions.period, - sIDX // - ); - if (result) - { - // - datetime iFrom = GetBarTime( - conditions.symbol, - conditions.period, - sIDX + count // - ); - double iLL = iBar.FindLowest(count, MODE_LOW); - double iHH = iBar.FindHighest(count, MODE_HIGH); - - // - triggerBlock.trigger.from = iFrom; - triggerBlock.trigger.upper = MathMax(iHH, triggerBlock.trigger.upper); - triggerBlock.trigger.lower = MathMin(iLL, triggerBlock.trigger.lower); - } - } - - // - iBar.Clean(); - } - - // - // Force Fair Value Gap to Following Sequence ... - if (result && - validations.validateGapSequence) - { - // - XOHCL iPBar; - toIDX = triggerBlock.fvg.ToIndex(); - fromIDX = triggerBlock.fvg.FromIndex() - 1; - for (int i = toIDX; i < fromIDX; i++) - { - // - result = iBar.Init( - conditions.symbol, - conditions.period, - i // - ); - result = - result && - iBar.GetPreviousBar(iPBar); - result = - result && - (isBullish - ? iBar.low > iPBar.low - : iBar.high < iPBar.high); - if (!result) - { - break; - } - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - // Validate OB Edge Breakeout Using Gaps End Bar ... - if (result && - validations.validateBlockEdgeBreakout) - { - // - // Initialize Gap End Bar ... - toIDX = triggerBlock.fvg.ToIndex(); - result = iBar.Init( - conditions.symbol, - conditions.period, - toIDX // - ); - - // - result = - result && - (isBullish - ? iBar.open < triggerBlock.ob.upper && - iBar.close > triggerBlock.ob.upper - : iBar.open > triggerBlock.ob.lower && - iBar.close < triggerBlock.ob.lower); - - // - // Here we Can Apply Edge Breakout Using Fibo ... - - // - iBar.Clean(); - } - - // - // Force Block to Has Liquidity ... - if (result && - validations.liquidityLoopback > 0 && - (validations.forceHasFLiquidity || - validations.forceHasRLiquidity)) - { - // - toIDX = triggerBlock.ToIndex(); - fromIDX = triggerBlock.FromIndex(); - ENUM_X_DIRECTION iLiqDir = X_DIRECTION_NONE; - for (int i = toIDX; i < fromIDX + validations.liquidityLoopback; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - conditions.symbol, - conditions.period, - i // - ); - has = - has && - barAnalyser - .IsRejected( - iBar, - iLiqDir, - false, // Force Bar Type ... - true // Force Fibo Pressure ... - ); - - // - bool isFLiq = - has && - iLiqDir == iDir; - if (isFLiq && - validations.forceHasFLiquidity && - !triggerBlock.fLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iLiqDir, - triggerBlock.fLiquidity, - triggerBlock.trigger.to // - ); - } - - // - bool isRLiq = - has && - iLiqDir == Opposit(iDir); - if (isRLiq && - validations.forceHasRLiquidity && - !triggerBlock.rLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iLiqDir, - triggerBlock.rLiquidity, - triggerBlock.trigger.to // - ); - } - - // - // Here We Can Apply Liquidity Validations ... - ValidateTriggerBlockLiquidities( - helper, - barAnalyser, - triggerBlock, - conditions, - validations // - ); - - // - // Check Liquidities ... - has = (!validations.forceHasFLiquidity - ? true - : triggerBlock.fLiquidity.IsValid()) && - (!validations.forceHasRLiquidity - ? true - : triggerBlock.rLiquidity.IsValid()); - - // - iBar.Clean(); - - // - if (has) - { - break; - } - } - - // - // Check Result ... - result = (!validations.forceHasFLiquidity - ? true - : triggerBlock.fLiquidity.IsValid()) && - (!validations.forceHasRLiquidity - ? true - : triggerBlock.rLiquidity.IsValid()); - - // - iBar.Clean(); - } - - // - if (!result) - { - triggerBlock.Clean(); - } - - // - // Summarize result ... - result = triggerBlock.IsValid(); - - // - // Cleanup Resources ... - - // - iBar.Clean(); - - // - if (!result) - { - // - conditions.Clean(); - triggerBlock.Clean(); - } - - // - return result; -} - -/** - * Filter a Trigger Block ... - * - * @param helper: XCX121XCatbHelper instance pointer ... - * @param barAnalyser: XCBarAnalyser instance pointer ... - * @param triggerBlock: XTriggerBlock Refrence, Trigger Block ... - * @param conditions: X121XCatbConditions Refrence, Trigger Block Conditions ... - * @param filters: XTriggerBlockFilters Refrence, Provides Trigger Block Filters ... - * @param barIndex: int, Bar Index ... - * @param loopback: int, Loopback for Conditions reading ... - * - * @return ( bool ) - */ -bool FilterTriggerBlock( - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - XTriggerBlock &triggerBlock, - X121XCatbConditions &conditions, - XTriggerBlockFilters &filters, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Checking Conditions ... - - // - // Normalize Args ... - conditions.Clean(); - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 0); - - // - // Validate Args ... - result = - helper != NULL && - barAnalyser != NULL && - triggerBlock.IsValid(); - if (!result) - { - return result; - } - - // - // Reading Market Conditions ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - XOHCL iBar; - int toIDX = -1; - int fromIDX = -1; - bool has = false; - bool isBullish = triggerBlock.IsBullish(); - bool isBearish = triggerBlock.IsBearish(); - double points = GetPoints(triggerBlock.ob.symbol); - ENUM_X_DIRECTION iDir = triggerBlock.GetDirection(); - - // - // Checking Conditions ... - - // - // Filter Based On PV ... - if (result && - filters.filterBasedOnPV) - { - // - // For PV Filtering ... - - // - // Detect Bos ... - if (filters.bosLoopback > 0) - { - // - has = true; - bool isBOS = false; - bool isPeakOverLast = false; - bool isValeUnderLast = false; - toIDX = triggerBlock.ob.ToIndex(); - fromIDX = triggerBlock.ob.FromIndex(); - int sIDX = fromIDX; - while (has) - { - // - double iPeak = helper.GetPeak(sIDX); - double iPPeak = helper.GetPeak(sIDX + 1); - - // - double iVale = helper.GetVale(sIDX); - double iPVale = helper.GetVale(sIDX + 1); - - // - isPeakOverLast = - iPeak > 0 && - iPeak > iPPeak; - - // - isValeUnderLast = - iVale > 0 && - iVale < iPVale; - - // - isBOS = - (isBullish && - isPeakOverLast) || - (isBearish && - isValeUnderLast); - if (isBOS) - { - break; - } - - // - sIDX++; - has = !isBOS && - sIDX < fromIDX + filters.bosLoopback; - } - - // - result = isBOS; - } - } - - // - if (!result) - { - triggerBlock.Clean(); - } - - // - // Summarize result ... - result = triggerBlock.IsValid(); - - // - // Cleanup Resources ... - - // - iBar.Clean(); - - // - if (!result) - { - // - conditions.Clean(); - triggerBlock.Clean(); - } - - // - return result; -} - -// -void ValidateTriggerBlockLiquidities( - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - XTriggerBlock &triggerBlock, - X121XCatbConditions &conditions, - XTriggerBlockValidationRules &validations // -) -{ - // - bool has = false; - - // - has = - helper != NULL && - barAnalyser != NULL && - triggerBlock.IsValid() && - (triggerBlock.fLiquidity.IsValid() || - triggerBlock.rLiquidity.IsValid()); - if (!has) - { - return; - } - - // - bool hasFLiq = triggerBlock.fLiquidity.IsValid(); - bool hasRLiq = triggerBlock.rLiquidity.IsValid(); - - // - // TODO: Implement Liquidity Validation ... -} - -// -bool DetectSignalZone( - XCPOIDrawer *&drawer, - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - XBoxZone &signalZone, - X121XCatbConditions &conditions, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Checking Conditions ... - - // - // Normalize Args ... - signalZone.Clean(); - conditions.Clean(); - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 0); - - // - // Validate Args ... - result = helper != NULL && - barAnalyser != NULL; - if (!result) - { - return result; - } - - // - // Reading Market Conditions ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - signalZone.Clean(); - conditions.Clean(); - - // - return result; - } - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - double sl = 0; - double tp = 0; - double upper = 0; - double lower = 0; - datetime to = NULL; - datetime from = NULL; - string signalProvider = NULL; - - // - // Checking Conditions ... - - // - // Detect Bar Verifications ... - - // - ENUM_X_DIRECTION iDir; - - // - // Rejected ... - bool isRejected = - barAnalyser - .IsRejected( - conditions.bars[cIDX], - iDir // - ); - bool isBullishRejected = - isRejected && - IsBullish(iDir); - bool isBearishRejected = - isRejected && - IsBearish(iDir); - - // - // Engulfed ... - bool isEngulfed = - barAnalyser - .IsEngulfed( - conditions.bars[cIDX], - iDir // - ); - bool isBullishEngulfed = - isEngulfed && - IsBullish(iDir); - bool isBearishEngulfed = - isEngulfed && - IsBearish(iDir); - - // - // Momentum ... - bool isMomentum = - barAnalyser - .IsMomentum( - conditions.bars[cIDX], - iDir // - ); - bool isBullishMomentum = - isMomentum && - IsBullish(iDir); - bool isBearishMomentum = - isMomentum && - IsBearish(iDir); - - // - bool isBarBullishPressured = - isBullishRejected || - isBullishEngulfed || - isBullishMomentum; - - // - bool isBarBearishPressured = - isBearishRejected || - isBearishEngulfed || - isBearishMomentum; - - // - // Detect Indicator Base Start Directional Movement ... - - // - // SAR ... - - // - bool isSarBullishStart = - // - ( - // - // Current SAR is Directional ... - conditions.isSarBullish && - // - // Previous InDirectional Sar Exists ... - helper.lastSarBearish.IsValid() && - // - // Current Close is Over previous Sar ... - conditions.bars[cIDX].close > helper.lastSarBearish.after && - // - // Before Close is not Over previous Sar ... - conditions.bars[pIDX].close <= helper.lastSarBearish.after - // - ) - // - ; - - // - bool isSarBearishStart = - // - ( - // - // Current SAR is Directional ... - conditions.isSarBearish && - // - // Previous InDirectional Sar Exists ... - helper.lastSarBullish.IsValid() && - // - // Current Close is Under previous ... - conditions.bars[cIDX].close < helper.lastSarBullish.after && - // - // Before Close is not Under previous ... - conditions.bars[pIDX].close >= helper.lastSarBullish.after - // - ) - // - ; - - // - // TREND ... - - // - bool isTrendBullishStart = - // - ( - // - // Current Trend is Directional ... - conditions.isTrendBullish && - // - // Previous InDirectiona; Trend Exists ... - helper.lastTrendBearish.IsValid() && - // - // Current Close is Over previous ... - conditions.bars[cIDX].close > helper.lastTrendBearish.after && - // - // Before close is not Over previous ... - conditions.bars[pIDX].close <= helper.lastTrendBearish.after - // - ) - // - ; - - // - bool isTrendBearishStart = - // - ( - // - // Current Trend is Directional ... - conditions.isTrendBearish && - // - // Previous InDirectiona; Trend Exists ... - helper.lastTrendBullish.IsValid() && - // - // Current Close is Under previous ... - conditions.bars[cIDX].close < helper.lastTrendBullish.after && - // - // Before close is not Under previous ... - conditions.bars[pIDX].close >= helper.lastTrendBullish.after - // - ) - // - ; - - // - // ADX ... - - // - bool isADXBullishStart = - // - ( - // - // ADX Value is Switched to Strong ... - conditions.adxBuffer[cIDX] > conditions.adxThreshold && - conditions.adxBuffer[pIDX] <= conditions.adxThreshold && - // - // ADX must Up ... - conditions.adxBuffer[cIDX] > conditions.adxBuffer[pIDX] && - // - // ADX +DI is Bigger than -DI ... - conditions.adxpBuffer[cIDX] > conditions.adxnBuffer[cIDX] && - // - // ADX +DI is Up ... - conditions.adxpBuffer[cIDX] > conditions.adxpBuffer[pIDX] - // - ) - // - ; - - // - bool isADXBearishStart = - // - ( - // - // ADX Value is Switched to Strong ... - conditions.adxBuffer[cIDX] > conditions.adxThreshold && - conditions.adxBuffer[pIDX] <= conditions.adxThreshold && - // - // ADX must Up ... - conditions.adxBuffer[cIDX] > conditions.adxBuffer[pIDX] && - // - // ADX -DI is Bigger than +DI ... - conditions.adxnBuffer[cIDX] > conditions.adxpBuffer[cIDX] && - // - // ADX -DI is Up ... - conditions.adxnBuffer[cIDX] > conditions.adxnBuffer[pIDX] - // - ) - // - ; - - // - // DELTA ... - - // - bool isDeltaBullishStart = - // - // Check State ... - ( - // - // Delta is Up ... - conditions.deltaBuffer[cIDX] > conditions.deltaBuffer[pIDX] && - // - // Delta Signal is Up ... - conditions.deltaSignalBuffer[cIDX] > conditions.deltaSignalBuffer[pIDX] && - // - // Delta Crossed Over Delta Signal ... - conditions.deltaBuffer[cIDX] > conditions.deltaSignalBuffer[cIDX] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastDeltaBearish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close > helper.lastDeltaBearish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close <= helper.lastDeltaBearish.after - // - ; - - // - bool isDeltaBearishStart = - // - // Check State ... - ( - // - // Delta is Down ... - conditions.deltaBuffer[cIDX] < conditions.deltaBuffer[pIDX] && - // - // Delta Signal is Down ... - conditions.deltaSignalBuffer[cIDX] < conditions.deltaSignalBuffer[pIDX] && - // - // Delta Crossed Under Delta Signal ... - conditions.deltaBuffer[cIDX] < conditions.deltaSignalBuffer[cIDX] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastDeltaBullish.IsValid() && - // - // Current Close is Under last ... - conditions.bars[cIDX].close < helper.lastDeltaBullish.after && - // - // Before Close is not Under last ... - conditions.bars[pIDX].close >= helper.lastDeltaBullish.after - // - ; - - // - // VOLUME ... - - // - bool isVolumeBullishStart = - // - ( - // - // - // Volume is Up ... - conditions.bullishVolumeBuffer[1] > conditions.bullishVolumeBuffer[2] && - // - // Volume Signal is Up ... - conditions.bullishVolumeSignalBuffer[1] > conditions.bullishVolumeSignalBuffer[2] && - // - // Volume Signals Crossed Over ... - conditions.bullishVolumeSignalBuffer[1] > conditions.bearishVolumeSignalBuffer[1] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastVolumeBearish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close > helper.lastVolumeBearish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close <= helper.lastVolumeBearish.after - // - ; - - // - bool isVolumeBearishStart = - // - ( - // - // - // Volume is Up ... - conditions.bearishVolumeBuffer[1] > conditions.bearishVolumeBuffer[2] && - // - // Volume Signal is Up ... - conditions.bearishVolumeSignalBuffer[1] > conditions.bearishVolumeSignalBuffer[2] && - // - // Volume Signals Crossed Over ... - conditions.bearishVolumeSignalBuffer[1] > conditions.bullishVolumeSignalBuffer[1] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastVolumeBullish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close < helper.lastVolumeBullish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close >= helper.lastVolumeBullish.after - // - ; - - // - // SIGNAL Bar ... - - // - bool isSBarBullishStart = - // - ( - // - // Check Direction ... - conditions.isSBarBullish && - // - // Previous InDirectional Exists ... - helper.lastSignalBarBearish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.sBarCloseBuffer[cIDX] > helper.lastSignalBarBearish.after && - // - // Prev Signal Bar not close over prev ... - conditions.sBarCloseBuffer[pIDX] <= helper.lastSignalBarBearish.after - // - ) - // - ; - - // - bool isSBarBearishStart = - // - ( - // - // Check Direction ... - conditions.isSBarBearish && - // - // Previous InDirectional Exists ... - helper.lastSignalBarBullish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.sBarCloseBuffer[cIDX] < helper.lastSignalBarBullish.after && - // - // Prev Signal Bar not close over prev ... - conditions.sBarCloseBuffer[pIDX] >= helper.lastSignalBarBullish.after - // - ) - // - ; - - // - // HKSIGNAL Bar ... - - // - bool isHKSBarBullishStart = - // - ( - // - // Check Direction ... - conditions.isHKSBarBullish && - // - // Previous InDirectional Exists ... - helper.lastHKSignalBarBearish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.hkSBarCloseBuffer[cIDX] > helper.lastHKSignalBarBearish.after && - // - // Prev Signal Bar not close over prev ... - conditions.hkSBarCloseBuffer[pIDX] <= helper.lastHKSignalBarBearish.after - // - ) - // - ; - - // - bool isHKSBarBearishStart = - // - ( - // - // Check Direction ... - conditions.isHKSBarBearish && - // - // Previous InDirectional Exists ... - helper.lastHKSignalBarBullish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.hkSBarCloseBuffer[cIDX] < helper.lastHKSignalBarBullish.after && - // - // Prev Signal Bar not close over prev ... - conditions.hkSBarCloseBuffer[pIDX] >= helper.lastHKSignalBarBullish.after - // - ) - // - ; - - // - // Check for Vale and Peak ... - - // - bool isPeakOverLast = - // - (conditions.peakBuffer[cIDX] > conditions.peakBuffer[pIDX] && - conditions.peakBuffer[pIDX] <= conditions.peakBuffer[p2IDX] && - conditions.bars[cIDX].close > conditions.peakBuffer[pIDX]) - // - ; - - // - bool isValeUnderLast = - // - (conditions.valeBuffer[cIDX] < conditions.valeBuffer[pIDX] && - conditions.valeBuffer[pIDX] >= conditions.valeBuffer[p2IDX] && - conditions.bars[cIDX].close < conditions.valeBuffer[pIDX]) - // - ; - - // - // Start Different Conditions Implemntation ... - - // - // Condition 1: - // --------------------------- - // Descriptions: - // - // - // --------------------------- - - // - // Bullish ... - bool isCond1Bullish = false; - - // - // Bearish ... - bool isCond1Bearish = false; - - // - bool isCond1 = - isCond1Bullish || - isCond1Bearish; - if (isCond1) - { - // - // Prepare Cond1 Based Requirements ... - - // - to = NULL; - upper = 0; - lower = 0; - from = NULL; - - // - // Provider Definition ... - signalProvider = "Cond1"; - } - - // - // Try to Summarize Conditions ... - - // - bool isBullish = - // - isCond1Bullish - // - ; - - // - bool isBearish = - // - isCond1Bearish - // - ; - - // - // Summarize Result ... - result = - isBullish || - isBearish; - if (result) - { - // - // Prepare Signal Zone ... - - // - signalZone.to = to; - signalZone.from = from; - signalZone.upper = upper; - signalZone.lower = lower; - signalZone.type = signalProvider; - signalZone.symbol = conditions.symbol; - signalZone.period = conditions.period; - - // - signalZone.dir = - isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Validate Signal Zone ... - result = signalZone.IsValid(); - } - - // - // Cleanup Resources ... - - // - if (!result) - { - // - signalZone.Clean(); - conditions.Clean(); - } - - // - return result; -} - -// -// Detect Trigger Block ... -bool DetectTriggerBlock( - // - string symbol, - ENUM_TIMEFRAMES period, - // - XTriggerBlock &tb, - // - XCBarAnalyser *barAnalyser, - // - // Required Buffers ... - const double &_atrBuffer[], - const double &_rsiBuffer[], - const double &_adxBuffer[], - const double &_adxpBuffer[], - const double &_adxnBuffer[], - const double &_peakBuffer[], - const double &_valeBuffer[], - const double &_deltaBuffer[], - const double &_sarBuffer[], - const double &_sarStateBuffer[], - const double &_trendBuffer[], - const double &_trendStateBuffer[], - const double &_atrUpperBuffer[], - const double &_atrLowerBuffer[], - const double &_sBarOpenSBuffer[], - const double &_sBarCloseBuffer[], - const double &_hkSBarOpenBuffer[], - const double &_hkSBarCloseBuffer[], - const double &_peakGoldenBuffer[], - const double &_valeGoldenBuffer[], - const double &_deltaSignalBuffer[], - const double &_bullishVolumeSignalBuffer[], - const double &_bearishVolumeSignalBuffer[], - // - int barIndex, - // - int _r2r, - double _slAtrMultiplier, - // - // Configs ... - double _rsiOBLevel, - double _rsiOSLevel, - double _adxThreshold, - // - // Validators ... - // - bool _forceOBBarType = false, - bool _forceFVGBarType = false, - bool _forceHasSwing = false, - bool _forceHasFLiquidity = false, - bool _forceHasRLiquidity = false, - bool _validateGapSequence = false, - bool _validateBlockEdgeBreakout = false, - // - // Filters ... - bool _filterBasedOnPV = false, - bool _filterBasedOnSar = false, - bool _filterBasedOnRSI = false, - bool _filterBasedOnADX = false, - bool _filterBasedOnATR = false, - bool _filterBasedOnTrend = false, - bool _filterBasedOnDelta = false, - bool _filterBasedOnVolume = false, - bool _filterBasedOnSignalBar = false, - bool _filterBasedOnHKSignalBar = false // -) -{ - // - bool result = false; - - // - // Custom Configs ... - - // // - // _r2r = 2; - // _slAtrMultiplier = 1; - - // // - // // Validators ... - // _forceHasSwing = true; - // _forceOBBarType = true; - // _forceFVGBarType = true; - // _validateGapSequence = true; - - // // - // _forceHasFLiquidity = false; - // _forceHasRLiquidity = false; - // _validateBlockEdgeBreakout = true; - - // // - // // Filters ... - // _filterBasedOnPV = true; - // _filterBasedOnATR = true; - // _filterBasedOnDelta = true; - // _filterBasedOnVolume = true; - - // // - // _filterBasedOnSar = true; - // _filterBasedOnRSI = false; - // _filterBasedOnADX = false; - // _filterBasedOnTrend = false; - // _filterBasedOnSignalBar = true; - // _filterBasedOnHKSignalBar = true; - - // - tb.Clean(); - - // - result = barAnalyser != NULL; - if (!result) - { - return result; - } - - // - int zIDX = 0; - bool has = false; - bool isDone = false; - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Retrieve Required Bars ... - - // - XOHCL iBar; - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - has = zBar.Init( - symbol, - period, - barIndex // - ); - - // - // Detect Based Order Block ... - has = - has && - barAnalyser.IsOB( - zBar, - tb.ob, - _forceFVGBarType, // Force FVG Bar Type ... - _forceOBBarType // Force Block Two Bar Checking ... - ); - - // - // Detect Based Fair Value Gap ... - has = - has && - barAnalyser.IsFVG( - zBar, - tb.fvg, - _forceFVGBarType // Force FVG Bar Type ... - ); - - // - // Clone Trigger Block ... - if (has) - { - // - tb.trigger = tb.ob; - tb.trigger.type = "XTRGB"; - } - - // - bool isBullish = - has && - tb.IsBullish(); - - // - bool isBearish = - has && - tb.IsBearish(); - - // - int toIDX = tb.ToIndex(); - int fromIDX = tb.FromIndex(); - - // - // Verifications and Filters ... - - // - int loopback = 144; - - // - // Forces ... - - // - // Force Has Proper Swing ... - if (has && - _forceHasSwing) - { - // - XOHCL iPBar; - XOHCL iP2Bar; - toIDX = tb.ToIndex(); - fromIDX = tb.FromIndex(); - for (int i = toIDX; i <= fromIDX; i++) - { - // - // Initialize iBar ... - isDone = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - isDone = - isDone && - iBar.GetPreviousBar(iPBar); - isDone = - isDone && - iPBar.GetPreviousBar(iP2Bar); - isDone = - isDone && - barAnalyser.IsSimpleSwing( - iBar, - iDir // - ) && - iDir == tb.GetDirection(); - if (isDone) - { - // - bool canSet = - !tb.swingBar.IsValid() - ? true - : (isBullish - ? tb.swingBar.low > iP2Bar.low - : tb.swingBar.high < iP2Bar.high); - if (canSet) - { - tb.swingBar = iP2Bar; - } - } - - // - iBar.Clean(); - iPBar.Clean(); - iP2Bar.Clean(); - } - - // - has = tb.swingBar.IsValid(); - } - - // - // Force Has Liquidity ... - // TODO: Add Validation based on Liquidities - // if necessary ... - if (has && - (_forceHasFLiquidity || - _forceHasRLiquidity)) - { - // - toIDX = tb.ToIndex(); - fromIDX = tb.FromIndex(); - for (int i = toIDX; i < fromIDX + loopback; i++) - { - // - // Initialize iBar ... - isDone = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - - // - bool isRejected = - isDone && - barAnalyser.IsRejected( - iBar, - iDir, - false, // Force Bar Type ... - true // Force Fibo Pressure ... - ); - - // - // Following Liquidity ... - bool isFLiq = - isDone && - isRejected && - iDir == tb.GetDirection() && - (isBullish - ? iBar.low < tb.trigger.lower - : iBar.high > tb.trigger.upper); - if (isFLiq && - _forceHasFLiquidity && - !tb.fLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iDir, - tb.fLiquidity, - tb.trigger.to // - ); - } - - // - // Reversal Liquidity ... - bool isRLiq = - isDone && - isRejected && - Opposit(iDir) == tb.GetDirection() && - (isBullish - ? iBar.low > tb.trigger.upper - : iBar.high < tb.trigger.lower); - if (isRLiq && - _forceHasRLiquidity && - !tb.rLiquidity.IsValid()) - { - // - FillLiquidity( - iBar, - iDir, - tb.rLiquidity, - tb.trigger.to // - ); - } - - // - // Checking Conditions ... - isDone = - (!_forceHasFLiquidity - ? true - : tb.fLiquidity.IsValid()) && - (!_forceHasRLiquidity - ? true - : tb.rLiquidity.IsValid()); - if (isDone) - { - // - iBar.Clean(); - break; - } - - // - iBar.Clean(); - } - - // - // Checking Conditions ... - has = - (!_forceHasFLiquidity - ? true - : tb.fLiquidity.IsValid()) && - (!_forceHasRLiquidity - ? true - : tb.rLiquidity.IsValid()); - } - - // - // Validations ... - - // - // Validating Gap Sequence means - // Gap Bars must Follow each Other ... - if (has && - _validateGapSequence) - { - // - XOHCL iPBar; - toIDX = tb.fvg.ToIndex(); - fromIDX = tb.fvg.FromIndex(); - - // - for (int i = toIDX; i < fromIDX - 1; i++) - { - // - // Initialize iBar ... - has = iBar.Init( - zBar.symbol, - zBar.period, - i // - ); - has = - has && - iBar.GetPreviousBar(iPBar); - has = - has && - (isBullish - ? iBar.low > iPBar.low - : iBar.high < iPBar.high); - if (!has) - { - break; - } - } - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - // Validate Block Edge Breakout ... - if (has && - _validateBlockEdgeBreakout) - { - // - has = tb.fvg.ToBar(iBar); - has = - has && - (isBullish - ? (iBar.GetDown() < tb.ob.upper && - iBar.GetUp() > tb.ob.upper) - : (iBar.GetDown() < tb.ob.lower && - iBar.GetUp() > tb.ob.lower)); - - // - iBar.Clean(); - } - - // - // Filters ... - - // - // PV ... - if (has && - _filterBasedOnPV) - { - // - double iPeak = _peakBuffer[barIndex]; - double iPPeak = _peakBuffer[barIndex + 1]; - double iP2Peak = _peakBuffer[barIndex + 2]; - - // - double iPeakGolden = _peakGoldenBuffer[barIndex]; - double iPPeakGolden = _peakGoldenBuffer[barIndex + 1]; - double iP2PeakGolden = _peakGoldenBuffer[barIndex + 2]; - - // - double iVale = _valeBuffer[barIndex]; - double iPVale = _valeBuffer[barIndex + 1]; - double iP2Vale = _valeBuffer[barIndex + 2]; - - // - double iValeGolden = _valeGoldenBuffer[barIndex]; - double iPValeGolden = _valeGoldenBuffer[barIndex + 1]; - double iP2ValeGolden = _valeGoldenBuffer[barIndex + 2]; - - // - // TODO: Fix this ... - has = - has && - (isBullish - ? (tb.trigger.lower <= iVale && - tb.trigger.upper < iPeak - // || tb.trigger.lower <= iValeGolden - ) - : (tb.trigger.upper >= iPeak && - tb.trigger.lower > iVale - // || tb.trigger.upper >= iPeakGolden - )); - } - - // - // SAR ... - if (has && - _filterBasedOnSar) - { - // - double iSarState = _sarStateBuffer[barIndex]; - double iPSarState = _sarStateBuffer[barIndex + 1]; - double iP2SarState = _sarStateBuffer[barIndex + 2]; - - // - bool isSarBullish = iSarState > 0; - bool isPSarBullish = iPSarState > 0; - bool isP2SarBullish = iP2SarState > 0; - - // - bool isSarBearish = iSarState < 0; - bool isPSarBearish = iPSarState < 0; - bool isP2SarBearish = iP2SarState < 0; - - // - bool isSarSwitchedToBullish = - isSarBullish && - !isPSarBullish; - - // - bool isSarSwitchedToBearish = - isSarBearish && - !isPSarBearish; - - // - bool isSarPSwitchedToBullish = - isPSarBullish && - !isP2SarBullish; - - // - bool isSarPSwitchedToBearish = - isPSarBearish && - !isP2SarBearish; - - // - has = - has && - (isBullish - ? (isSarSwitchedToBullish || - isSarPSwitchedToBullish) - : (isSarSwitchedToBearish || - isSarPSwitchedToBearish)); - } - - // - // RSI ... - if (has && - _filterBasedOnRSI) - { - // - double rsiTrend = (_rsiOBLevel + _rsiOSLevel) / 2; - - // - double iRSI = _rsiBuffer[barIndex]; - double iPRSI = _rsiBuffer[barIndex + 1]; - double iP2RSI = _rsiBuffer[barIndex + 2]; - - // - bool isRSICrossedOverOS = - iRSI > _rsiOSLevel && - iPRSI <= _rsiOSLevel; - - // - bool isRSICrossedUnderOB = - iRSI < _rsiOBLevel && - iPRSI >= _rsiOBLevel; - - // - bool isPRSICrossedOverOS = - iPRSI > _rsiOSLevel && - iP2RSI <= _rsiOSLevel; - - // - bool isPRSICrossedUnderOB = - iPRSI < _rsiOBLevel && - iP2RSI >= _rsiOBLevel; - - // - has = - has && - (isBullish - ? (isRSICrossedOverOS || - isPRSICrossedOverOS) - : (isRSICrossedUnderOB || - isPRSICrossedUnderOB)); - } - - // - // ADX ... - if (has && - _filterBasedOnADX) - { - // - // ADX ... - double iADX = _adxBuffer[barIndex]; - double iPADX = _adxBuffer[barIndex + 1]; - double iP2ADX = _adxBuffer[barIndex + 2]; - - // - // ADX +DI ... - double iADXP = _adxpBuffer[barIndex]; - double iPADXP = _adxpBuffer[barIndex + 1]; - double iP2ADXP = _adxpBuffer[barIndex + 2]; - - // - // ADX -DI ... - double iADXN = _adxnBuffer[barIndex]; - double iPADXN = _adxnBuffer[barIndex + 1]; - double iP2ADXN = _adxnBuffer[barIndex + 2]; - - // - // Preparing Conditions ... - - // - bool isADXBullish = iADX > _adxThreshold; - bool isADXBearish = iADX < _adxThreshold; - - // - bool isPADXBullish = iPADX > _adxThreshold; - bool isPADXBearish = iPADX < _adxThreshold; - - // - bool isP2ADXBullish = iP2ADX > _adxThreshold; - bool isP2ADXBearish = iP2ADX < _adxThreshold; - - // - bool isADXSwitchedToBullish = - isADXBullish && - !isPADXBullish; - - // - bool isADXSwitchedToBearish = - isADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isPADXBearish && - !isP2ADXBearish; - - // - has = - has && - (isBullish - ? (isADXSwitchedToBullish || - isPADXSwitchedToBullish) - : (isADXSwitchedToBearish || - isPADXSwitchedToBearish)); - } - - // - // ATR ... - if (has && - _filterBasedOnATR) - { - // - fromIDX = tb.FromIndex(); - double iATRUpper = _atrUpperBuffer[fromIDX]; - double iATRLower = _atrLowerBuffer[fromIDX]; - - // - has = - has && - (isBullish - ? tb.trigger.lower < iATRLower - : tb.trigger.upper > iATRUpper); - } - - // - // TREND ... - if (has && - _filterBasedOnTrend) - { - // - double iTrendState = _trendStateBuffer[barIndex]; - double iPTrendState = _trendStateBuffer[barIndex + 1]; - - // - bool isTrendBullish = iTrendState > 0; - bool isPTrendBullish = iPTrendState > 0; - - // - bool isTrendBearish = iTrendState < 0; - bool isPTrendBearish = iPTrendState < 0; - - // - double trends[]; - int toIDX = tb.ToIndex(); - int fromIDX = tb.FromIndex(); - double iTrend = _trendBuffer[toIDX]; - for (int i = toIDX; i <= fromIDX; i++) - { - // - Add( - _trendBuffer[i], - trends // - ); - } - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - bool isTrendUp = - iTrend > trendsMin && - iTrend >= trendsAVG; - - // - bool isTrendDown = - iTrend < trendsMax && - iTrend <= trendsAVG; - - // - bool isTrendSwitchedToBullish = - isTrendUp && - isTrendBullish && - !isPTrendBullish; - - // - bool isTrendSwitchedToBearish = - isTrendDown && - isTrendBearish && - !isPTrendBearish; - - // - has = - has && - (isBullish - ? isTrendSwitchedToBullish - : isTrendSwitchedToBearish); - } - - // - // DELTA ... - if (has && - _filterBasedOnDelta) - { - // - double iDelta = _deltaBuffer[barIndex]; - double iPDelta = _deltaBuffer[barIndex + 1]; - - // - bool isDeltaUp = iDelta > iPDelta; - bool isDeltaDown = iDelta < iPDelta; - - // - double iDeltaSignal = _deltaSignalBuffer[barIndex]; - double iPDeltaSignal = _deltaSignalBuffer[barIndex + 1]; - - // - bool isDeltaSignalUp = iDeltaSignal > iPDeltaSignal; - bool isDeltaSignalDown = iDeltaSignal < iPDeltaSignal; - - // - bool isDeltaSwitchedToBullish = - isDeltaUp && - isDeltaSignalUp && - iDelta > iDeltaSignal && - iPDelta < iPDeltaSignal; - - // - bool isDeltaSwitchedToBearish = - isDeltaDown && - isDeltaSignalDown && - iDelta < iDeltaSignal && - iPDelta > iPDeltaSignal; - - // - has = - has && - (isBullish - ? isDeltaSwitchedToBullish - : isDeltaSwitchedToBearish); - } - - // - // VOLUME ... - if (has && - _filterBasedOnVolume) - { - // - double iBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex]; - double iPBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex + 1]; - - // - bool isBullishVolumeSignalUp = iBullishVolumeSignal > iPBullishVolumeSignal; - bool isBullishVolumeSignalDown = iBullishVolumeSignal < iPBullishVolumeSignal; - - // - double iBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex]; - double iPBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex + 1]; - - // - bool isBearishVolumeSignalUp = iBearishVolumeSignal > iPBearishVolumeSignal; - bool isBearishVolumeSignalDown = iBearishVolumeSignal < iPBearishVolumeSignal; - - // - bool isVolumeSwitchdToBullish = - isBullishVolumeSignalUp && - !isBearishVolumeSignalUp && - iBullishVolumeSignal > iBearishVolumeSignal && - iPBullishVolumeSignal < iPBearishVolumeSignal; - - // - bool isVolumeSwitchdToBearish = - isBearishVolumeSignalUp && - !isBullishVolumeSignalUp && - iBearishVolumeSignal > iBullishVolumeSignal && - iPBearishVolumeSignal < iPBullishVolumeSignal; - - // - has = - has && - (isBullish - ? isVolumeSwitchdToBullish - : isVolumeSwitchdToBearish); - } - - // - // SIGNAL Bar ... - if (has && - _filterBasedOnSignalBar) - { - // - double iSignalOpen = _sBarOpenSBuffer[barIndex]; - double iPSignalOpen = _sBarOpenSBuffer[barIndex + 1]; - - // - double iSignalClose = _sBarCloseBuffer[barIndex]; - double iPSignalClose = _sBarCloseBuffer[barIndex + 1]; - - // - bool isSignalBarBullish = iSignalOpen < iSignalClose; - bool isPSignalBarBullish = iPSignalOpen < iPSignalClose; - - // - bool isSignalBarBearish = iSignalOpen > iSignalClose; - bool isPSignalBarBearish = iPSignalOpen > iPSignalClose; - - // - bool isSignalBarSwitchedToBullish = - isSignalBarBullish && - !isPSignalBarBullish; - - // - bool isSignalBarSwitchedToBearish = - isSignalBarBearish && - !isPSignalBarBearish; - - // - has = - has && - (isBullish - ? isSignalBarSwitchedToBullish - : isSignalBarSwitchedToBearish); - } - - // - // HK SIGNAL Bar ... - if (has && - _filterBasedOnHKSignalBar) - { - // - double iHKSignalOpen = _hkSBarOpenBuffer[barIndex]; - double iPHKSignalOpen = _hkSBarOpenBuffer[barIndex + 1]; - - // - double iHKSignalClose = _hkSBarCloseBuffer[barIndex]; - double iPHKSignalClose = _hkSBarCloseBuffer[barIndex + 1]; - - // - bool isHKSignalBarBullish = iHKSignalOpen < iHKSignalClose; - bool isPHKSignalBarBullish = iPHKSignalOpen < iPHKSignalClose; - - // - bool isHKSignalBarBearish = iHKSignalOpen > iHKSignalClose; - bool isPHKSignalBarBearish = iPHKSignalOpen > iPHKSignalClose; - - // - bool isHKSignalBarSwitchedToBullish = - isHKSignalBarBullish && - !isPHKSignalBarBullish; - - // - bool isHKSignalBarSwitchedToBearish = - isHKSignalBarBearish && - !isPHKSignalBarBearish; - - // - has = - has && - (isBullish - ? isHKSignalBarSwitchedToBullish - : isHKSignalBarSwitchedToBearish); - } - - // - // Valdating Directional Trending ... - bool _filterBasedOnDirection = false; - if (has && - _filterBasedOnDirection) - { - // - iBar.Clean(); - fromIDX = tb.FromIndex(); - int loopbackForValidating = 30; - for (int i = fromIDX; i < fromIDX + loopbackForValidating; i++) - { - // - // Initialize iBar ... - iBar.Clean(); - has = iBar.Init( - symbol, - period, - i // - ); - - // - has = - has && - (isBullish - ? iBar.high < tb.trigger.upper - : iBar.low > tb.trigger.lower); - if (!has) - { - break; - } - } - - // - // Update Trigger Block ... - if (has) - { - tb.trigger.from = iBar.time; - } - - // - iBar.Clean(); - } - - // - // Preparing Signal ... - if (has) - { - // - // CArrayObj *tbObjects = new CArrayObj(); - // DrawTriggerBlock( - // tb, - // drawer, - // tbObjects, - // NULL // - // ); - - // - double targets[]; - for (int i = 1; i <= _r2r; i++) - { - // - Add( - (double)i, - targets // - ); - } - - // - double iATR = 0; - if (barIndex > 0 && - barIndex < ArraySize(_atrBuffer)) - { - iATR = _atrBuffer[barIndex]; - } - double slAdditional = _slAtrMultiplier * iATR; - - // - has = ToSignal( - tb.trigger, - tb.signal, - targets, - slAdditional // - ); - } - - // - result = has; - - // - return result; -} - -// -// Draw Specific Trigger Block ... -bool DrawTriggerBlock( - XTriggerBlock &trigger, - XCPOIDrawer *drawer, - CArrayObj &objects, - datetime to = NULL, - // - bool _drawSignals = false, - int rrZoneLength = 10, - // Styles ... - // - // Trigger Block ... - int tbWidth = 1, // Trigger Block Width - color tbBullishColor = clrAqua, // Trigger Block Bullish Color - color tbBearishColor = clrMagenta, // Trigger Block Bearish Color - ENUM_LINE_STYLE tbStyle = STYLE_DASHDOTDOT, // Trigger Block Style - // - // OB ... - int obWidth = 1, // OB Width - color obBullishColor = clrLime, // OB Bullish Color - color obBearishColor = clrRed, // OB Bearish Color - ENUM_LINE_STYLE obStyle = STYLE_DOT, // OB Style - // - // FVG ... - int fvgWidth = 2, // FVG Width - color fvgBullishColor = clrLime, // FVG Bullish Color - color fvgBearishColor = clrRed, // FVG Bearish Color - ENUM_LINE_STYLE fvgStyle = STYLE_SOLID // FVG Style -) -{ - // - bool result = false; - - // - // Validate Args ... - result = trigger.IsValid() && - drawer != NULL; - if (!result) - { - return result; - } - - // - // Update To ... - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - // - trigger.trigger.to = to; - trigger.rLiquidity.to = to; - trigger.fLiquidity.to = to; - } - - // - bool isBullish = trigger.IsBullish(); - - // - // Draw OB ... - if (trigger.ob.IsValid()) - { - // - XCBoxObject *iOBObj; - result = drawer.DrawBox( - trigger.ob, - iOBObj // - ); - if (result) - { - // - // Style Object ... - - // - color iClr = - isBullish - ? obBullishColor - : obBearishColor; - - // - iOBObj.BoxColor(iClr); - iOBObj.BoxWidth(obWidth); - iOBObj.BoxStyle(obStyle); - - // - // Store Object ... - objects.Add(iOBObj); - } - ZeroMemory(iOBObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw FVG ... - if (trigger.fvg.IsValid()) - { - // - XCBoxObject *iFVGObj; - result = drawer.DrawBox( - trigger.fvg, - iFVGObj // - ); - if (result) - { - // - // Style Object ... - - // - color iClr = - isBullish - ? fvgBullishColor - : fvgBearishColor; - - // - iFVGObj.BoxColor(iClr); - iFVGObj.BoxWidth(fvgWidth); - iFVGObj.BoxStyle(fvgStyle); - - // - // Store Object ... - objects.Add(iFVGObj); - } - ZeroMemory(iFVGObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Trigger ... - if (trigger.trigger.IsValid()) - { - // - XCBoxObject *iTriggerObj; - result = drawer.DrawBox( - trigger.trigger, - iTriggerObj // - ); - if (result) - { - // - // Style Object ... - - // - color iClr = - isBullish - ? tbBullishColor - : tbBearishColor; - - // - iTriggerObj.BoxColor(iClr); - iTriggerObj.BoxWidth(tbWidth); - iTriggerObj.BoxStyle(tbStyle); - - // - // Store Object ... - objects.Add(iTriggerObj); - } - ZeroMemory(iTriggerObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Liquidities ... - - // - // Reversla Liquidity ... - if (trigger.rLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = drawer.DrawBox( - trigger.rLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Following Liquidity ... - if (trigger.fLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = drawer.DrawBox( - trigger.fLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Swing Bar ... - if (trigger.swingBar.IsValid()) - { - // - color swingColor = - trigger.fvg.IsBullish() - ? clrAqua - : clrMagenta; - ENUM_X_PRICE swingPType = - trigger.fvg.IsBullish() - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - XCBarArrowObject *swingObj; - result = drawer.CreateBarArrow( - trigger.swingBar, - swingObj, - swingPType, - 159, - swingColor // - ); - if (result) - { - objects.Add(swingObj); - } - ZeroMemory(swingObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw RR of Signal ... - if (_drawSignals && - trigger.signal.IsValid() && - rrZoneLength > 0) - { - // - XCRRObject *iRRObj; - iRRObj = new XCRRObject(); - result = iRRObj.Create( - drawer.ChartIdentification(), - drawer.SubWindowIdentification(), - trigger.signal, - rrZoneLength // - ); - if (result) - { - // - int iWidth = 2; - ENUM_LINE_STYLE iStyle = STYLE_SOLID; - - // - iRRObj.TPWidth(iWidth); - iRRObj.SLWidth(iWidth); - iRRObj.EntryWidth(iWidth); - iRRObj.TargetWidth(iWidth); - - // - iRRObj.TPStyle(iStyle); - iRRObj.SLStyle(iStyle); - iRRObj.EntryStyle(iStyle); - iRRObj.TargetStyle(iStyle); - - // - iRRObj.TPColor(clrLime); - iRRObj.SLColor(clrRed); - iRRObj.EntryColor(clrYellow); - iRRObj.TargetColor(clrLightBlue); - - // - objects.Add(iRRObj); - } - ZeroMemory(iRRObj); - - // - if (result) - { - return result; - } - } - - // - return result; -} diff --git a/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.mq5 b/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.mq5 deleted file mode 100644 index 8fb1e13d..00000000 --- a/Documents/BKP/XCAEA_BKP/x-saherelm.x121.xcatb.mq5 +++ /dev/null @@ -1,2777 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: X121 XCATB -// Description: Integrates All Requirements inside -// this indicator for analyse Markets to -// Detect Trigger Blocks ... -// -// - HK Bars; -// - ATR Band; -// - Signal Bars; -// - Parabolic Sar; -// - HK Signal Bars; -// - Peaks and Vales; -// - Peaks and Vales Goldens; -// - Trending Average Prices; -// -// - ATR; -// - RSI; -// - ADX; -// - DELTA; -// - VOLUME; -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121 XCATB Indicator" -#property strict - -// -// Definitions ... - -// -#define ShortName "X121 XCATB" - -// -// Imports ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x121.xcatb.lib.mq5" - -// -// Inputs ... - -// -input group "Market"; - -// -// Short ... -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period - -// -// Medium ... -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period - -// -// Long ... -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period - -// -// Hind ... -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period - -// -// Select Trending Cycle ... -// this Cycle Used for All Calculations ... -input ENUM_X_MARKET_CYCLES appliedCycle = X_MARKET_CYCLE_HIND; // Applied Cycle - -// -// Signal ... -input group "Signal"; -input int signalR2R = 4; // Risk Reward Ratio -input bool drawSignals = true; // Draw Signal -input bool drawTriggerBlock = true; // Draw Trigger Block -input double slAtrMultiplier = 1.0; // ATR Multiplier for SL - -// -// Validating ... -input group "Validating"; -input bool forceHasSwing = false; // Force Blocks to Have Swing -input bool forceObBarType = false; // Force Block Has Reversal Bar -input bool forceOBFVGBarType = false; // Force FVG Has Same Bars -input bool forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -input bool forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -input bool validateGapSequence = false; // Validate Block's Gap Sequence -input bool validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -input group "Filtering"; -input bool filterBasedOnPV = false; // Filter Based on Peak and Vale -input bool filterBasedOnSar = false; // Filter Based on Sar -input bool filterBasedOnRSI = false; // Filter Based on RSI -input bool filterBasedOnADX = false; // Filter Based on ADX -input bool filterBasedOnATR = false; // Filter Based on ATR -input bool filterBasedOnTrend = false; // Filter Based on Trend -input bool filterBasedOnDelta = false; // Filter Based on Delta -input bool filterBasedOnVolume = false; // Filter Based on Volume -input bool filterBasedOnSignalBar = false; // Filter Based on Signal Bar -input bool filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -input group "Alerts"; -input string mAlertPrefix = ""; // Alert Prefix -input bool _logAlerts = false; // Log Alerts -input bool _pushAlerts = false; // Push Alerts -input bool _mailAlerts = false; // Mail Alerts -input bool _terminalAlerts = false; // Terminal Alerts - -// -// Presentation ... -input group "Presentation"; -input bool showBars = true; // Show Bars -input bool showPV = false; // Show PV -input bool showPVGolden = false; // Show PV Golden -input bool showSar = false; // Show Sar -input bool showTrend = false; // Show Trend -input bool showATRBand = false; // Show ATR Band -input bool showSignalBars = false; // Show Signal Bars -input bool showHKSignalBars = false; // Show Hiken Ashi Signal Bars - -// -input int startCalculationForLastBars = 1500; // Calculate Last n Bars - -// -// Non Inputs ... -double sarStep = 0.02; // Step -double sarMax = 0.2; // Maximum -double rsiOBLevel = 70.0; // RSI OB Level -double rsiOSLevel = 30.0; // RSI OS Level -double adxThreshold = 25.0; // ADX Threshold -int sarArrowCode = 159; // Parabolic Sar Arrow Code -int peakArrowCode = 159; // Peaks Arrow Code -int valeArrowCode = 159; // Vales Arrow Code -double atrMultiplier = 1.5; // ATR Band Multiplier -bool showShortCycle = false; // Show Short Cycle Range -bool showMediumCycle = false; // Show Medium Cycle Range -bool showLongCycle = false; // Show Long Cycle Range -bool showHindCycle = false; // Show Hind Cycle Range -ENUM_MA_METHOD trendMode = MODE_SMA; // Trend Mode -ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method -ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method -ENUM_X_PRICE atrUpperPriceType = X_PRICE_HIGH; // ATR Upper Zone Applied To -ENUM_X_PRICE atrLowerPriceType = X_PRICE_LOW; // ATR Lower Zone Applied To -ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // RSI Applied To -ENUM_APPLIED_PRICE trendAppliedTo = PRICE_MEDIAN; // Trend Applied To -ENUM_X_MA_METHOD atrSignalMethod = X_MA_MODE_EMA; // ATR Signalling Method -ENUM_X_MA_METHOD barsSignalMethod = X_MA_MODE_EMA; // Bars Signalling Method -ENUM_X_MA_METHOD deltaSignalMethod = X_MA_MODE_EMA; // Delta Signalling Method -ENUM_X_MA_METHOD hkSignalBarMethod = X_MA_MODE_EMA; // Hiken Ashi Signal Method -ENUM_X_MA_METHOD volumeSignalMethod = X_MA_MODE_EMA; // Volume Signalling Method - -// -#define hideColorIDX 0 -#define bullishColorIDX 1 -#define bearishColorIDX 2 -#define neuturalColorIDX 3 - -// -#define bullishState 1 -#define neuturalState 0 -#define bearishState -1 - -// -#define emptyValue 0.0 - -// -// Buffers ... - -// -#property indicator_chart_window - -// -// Plot: 18 -// Color: 4 -// Bar: 8 -// Data Buffer: 19 -#property indicator_buffers 49 -#property indicator_plots 18 - -// -// Plot Buffers ... - -// -// SAR ... - -// -#define sarBufferIndex 0 -#define sarBufferPlotIndex 0 -double sarBuffer[]; - -// -#define sarColorBufferIndex 1 -double sarColorBuffer[]; - -// -#property indicator_label1 "SAR" -#property indicator_type1 DRAW_COLOR_ARROW -#property indicator_color1 CLR_NONE, clrLime, clrRed, clrGray -#property indicator_width1 2 - -// -// PEAKS ... - -// -#define peakBufferIndex 2 -#define peakBufferPlotIndex 1 -double peakBuffer[]; - -// -#property indicator_label2 "PEAK" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 1 - -// -// VALES ... - -// -#define valeBufferIndex 3 -#define valeBufferPlotIndex 2 -double valeBuffer[]; - -// -#property indicator_label3 "VALE" -#property indicator_type3 DRAW_ARROW -#property indicator_color3 clrAqua -#property indicator_width3 1 - -// -// PEAKS Golden ... - -// -#define peakGoldenBufferIndex 4 -#define peakGoldenBufferPlotIndex 3 -double peakGoldenBuffer[]; - -// -#property indicator_label4 "PEAK Golden" -#property indicator_type4 DRAW_LINE -#property indicator_color4 clrMagenta -#property indicator_style4 STYLE_DOT -#property indicator_width4 1 - -// -// VALE Golden ... - -// -#define valeGoldenBufferIndex 5 -#define valeGoldenBufferPlotIndex 4 -double valeGoldenBuffer[]; - -// -#property indicator_label5 "VALES Golden" -#property indicator_type5 DRAW_LINE -#property indicator_color5 clrAqua -#property indicator_style5 STYLE_DOT -#property indicator_width5 1 - -// -// ATR ... - -// -// Upper ... - -// -#define atrUpperBufferIndex 6 -#define atrUpperBufferPlotIndex 5 -double atrUpperBuffer[]; - -// -#property indicator_label6 "XATRU" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrYellow -#property indicator_style6 STYLE_SOLID -#property indicator_width6 1 - -// -// Lower ... - -// -#define atrLowerBufferIndex 7 -#define atrLowerBufferPlotIndex 6 -double atrLowerBuffer[]; - -// -#property indicator_label7 "XATRL" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrYellow -#property indicator_style7 STYLE_SOLID -#property indicator_width7 1 - -// -// TREND ... - -// -#define trendBufferIndex 8 -#define trendBufferPlotIndex 7 -double trendBuffer[]; - -// -#define trendColorBufferIndex 9 -double trendColorBuffer[]; - -// -#property indicator_label8 "Trend" -#property indicator_type8 DRAW_COLOR_LINE -#property indicator_color8 CLR_NONE, clrAqua, clrMagenta, clrGray -#property indicator_style8 STYLE_SOLID -#property indicator_width8 2 - -// -// Signal Bar ... - -// -#define sBarOpenBufferIndex 10 -double sBarOpenBuffer[]; - -// -#define sBarHighBufferIndex 11 -double sBarHighBuffer[]; - -// -#define sBarLowBufferIndex 12 -double sBarLowBuffer[]; - -// -#define sBarCloseBufferIndex 13 -double sBarCloseBuffer[]; - -// -#define sBarColorBufferIndex 14 -double sBarColorBuffer[]; - -// -#define sBarBufferPlotIndex 8 -#property indicator_label9 "XSGB Open;XSGB High;XSGB Low;XSGB Close" -#property indicator_type9 DRAW_COLOR_CANDLES -#property indicator_color9 CLR_NONE, clrLime, clrRed - -// -// XHK SIGNAL ... - -// -#define hkSBarOpenBufferIndex 15 -double hkSBarOpenBuffer[]; - -// -#define hkSBarHighBufferIndex 16 -double hkSBarHighBuffer[]; - -// -#define hkSBarLowBufferIndex 17 -double hkSBarLowBuffer[]; - -// -#define hkSBarCloseBufferIndex 18 -double hkSBarCloseBuffer[]; - -// -#define hkSBarColorBufferIndex 19 -double hkSBarColorBuffer[]; - -// -#define hkSBarBufferPlotIndex 9 -#property indicator_label10 "XHKSGB Open;XHKSGB High;XHKSGB Low;XHKSGB Close" -#property indicator_type10 DRAW_COLOR_CANDLES -#property indicator_color10 CLR_NONE, clrAqua, clrMagenta - -// -// CYCLES Range ... - -// -// SHORT ... - -// -#define sHHBufferIndex 20 -#define sHHBufferPlotIndex 10 -double sHHBuffer[]; - -// -#property indicator_label11 "SH" -#property indicator_type11 DRAW_LINE -#property indicator_color11 clrGray -#property indicator_style11 STYLE_DOT -#property indicator_width11 1 - -// -#define sLLBufferIndex 21 -#define sLLBufferPlotIndex 11 -double sLLBuffer[]; - -// -#property indicator_label12 "SL" -#property indicator_type12 DRAW_LINE -#property indicator_color12 clrGray -#property indicator_style12 STYLE_DOT -#property indicator_width12 1 - -// -// MEDIUM ... - -// -#define mHHBufferIndex 22 -#define mHHBufferPlotIndex 12 -double mHHBuffer[]; - -// -#property indicator_label13 "MH" -#property indicator_type13 DRAW_LINE -#property indicator_color13 clrIndigo -#property indicator_style13 STYLE_DOT -#property indicator_width13 1 - -// -#define mLLBufferIndex 23 -#define mLLBufferPlotIndex 13 -double mLLBuffer[]; - -// -#property indicator_label14 "ML" -#property indicator_type14 DRAW_LINE -#property indicator_color14 clrIndigo -#property indicator_style14 STYLE_DOT -#property indicator_width14 1 - -// -// LONG ... - -// -#define lHHBufferIndex 24 -#define lHHBufferPlotIndex 14 -double lHHBuffer[]; - -// -#property indicator_label15 "LH" -#property indicator_type15 DRAW_LINE -#property indicator_color15 clrGoldenrod -#property indicator_style15 STYLE_DOT -#property indicator_width15 1 - -// -#define lLLBufferIndex 25 -#define lLLBufferPlotIndex 15 -double lLLBuffer[]; - -// -#property indicator_label16 "LL" -#property indicator_type16 DRAW_LINE -#property indicator_color16 clrGoldenrod -#property indicator_style16 STYLE_DOT -#property indicator_width16 1 - -// -// HIND ... - -// -#define hHHBufferIndex 26 -#define hHHBufferPlotIndex 16 -double hHHBuffer[]; - -// -#property indicator_label17 "HH" -#property indicator_type17 DRAW_LINE -#property indicator_color17 clrBrown -#property indicator_style17 STYLE_DOT -#property indicator_width17 1 - -// -#define hLLBufferIndex 27 -#define hLLBufferPlotIndex 17 -double hLLBuffer[]; - -// -#property indicator_label18 "HL" -#property indicator_type18 DRAW_LINE -#property indicator_color18 clrBrown -#property indicator_style18 STYLE_DOT -#property indicator_width18 1 - -// -// Data Buffers ... - -// -#define mLastBufferIndex 27 - -// -// SAR ... - -// -#define sarStateBufferIndex mLastBufferIndex + 1 -double sarStateBuffer[]; - -// -// TREND State ... - -// -#define trendStateBufferIndex mLastBufferIndex + 2 -double trendStateBuffer[]; - -// -// RSI ... - -// -#define rsiBufferIndex mLastBufferIndex + 3 -double rsiBuffer[]; - -// -// ADX ... - -// -#define adxBufferIndex mLastBufferIndex + 4 -double adxBuffer[]; - -// -#define adxpBufferIndex mLastBufferIndex + 5 -double adxpBuffer[]; - -// -#define adxnBufferIndex mLastBufferIndex + 6 -double adxnBuffer[]; - -// -// DELTA ... - -// -#define deltaBufferIndex mLastBufferIndex + 7 -double deltaBuffer[]; - -// -#define deltaSignalBufferIndex mLastBufferIndex + 8 -double deltaSignalBuffer[]; - -// -// VOLUMES ... - -// -#define bullishVolumeBufferIndex mLastBufferIndex + 9 -double bullishVolumeBuffer[]; - -// -#define bearishVolumeBufferIndex mLastBufferIndex + 10 -double bearishVolumeBuffer[]; - -// -#define bullishVolumeSignalBufferIndex mLastBufferIndex + 11 -double bullishVolumeSignalBuffer[]; - -// -#define bearishVolumeSignalBufferIndex mLastBufferIndex + 12 -double bearishVolumeSignalBuffer[]; - -// -// ATR ... - -// -#define atrBufferIndex mLastBufferIndex + 13 -double atrBuffer[]; - -// -#define atrUpperRawBufferIndex mLastBufferIndex + 14 -double atrUpperRawBuffer[]; - -// -#define atrLowerRawBufferIndex mLastBufferIndex + 15 -double atrLowerRawBuffer[]; - -// -// HK ... - -// -#define openHKBufferIndex mLastBufferIndex + 16 -double openHKBuffer[]; - -// -#define highHKBufferIndex mLastBufferIndex + 17 -double highHKBuffer[]; - -// -#define lowHKBufferIndex mLastBufferIndex + 18 -double lowHKBuffer[]; - -// -#define closeHKBufferIndex mLastBufferIndex + 19 -double closeHKBuffer[]; - -// -// Variables, Properties and etc ... - -// -int limit; - -// -int maxLength; - -// -int firstBarIndex; - -// -// Bars Color Variables ... -color _upColor = clrLime; -color _downColor = clrRed; -color _lineColor = clrLime; -color _bullishColor = clrLime; -color _bearishColor = clrRed; - -// -// XMarketCycle sc; -int mSCLength = 0; -ENUM_TIMEFRAMES mSCPeriod = NULL; - -// -// XMarketCycle mc; -int mMCLength = 0; -ENUM_TIMEFRAMES mMCPeriod = NULL; - -// -// XMarketCycle lc; -int mLCLength = 0; -ENUM_TIMEFRAMES mLCPeriod = NULL; - -// -// XMarketCycle hc; -int mHCLength = 0; -ENUM_TIMEFRAMES mHCPeriod = NULL; - -// -// Applied Cycle ... -int mAppliedLength; -ENUM_TIMEFRAMES mAppliedPeriod = NULL; - -// -// Handlers ... -int atrHandler = INVALID_HANDLE; -int sarHandler = INVALID_HANDLE; -int rsiHandler = INVALID_HANDLE; -int adxHandler = INVALID_HANDLE; -int trendHandler = INVALID_HANDLE; - -// -XCAlert *mAlert; -CArrayObj mObjects; -XCPOIDrawer *mDrawer; -bool mEnableAlerts = false; -XCBarAnalyser *mBarAnalyser; - -// -// Event Handlers ... - -/** - * Initialize Indicator ... - * - * @return ( int ) - */ -int OnInit() -{ - // - bool has = false; - - // - ReadBarStyle(); - - // - // Validate Inputs ... - has = ValidateInputs(); - if (!has) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - has = InitCycles(); - if (!has) - { - return INIT_FAILED; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initial Requirements ... - has = InitRequirements(); - if (!has) - { - return INIT_FAILED; - } - - // - if (showBars) - { - ShowBars(); - } - else - { - HideBars(); - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; - - // -} - -/** - * De Initialize Indicator ... - * - * @param reason: Integer, De Initialization Reason ... - */ -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - ShowBars(); - - // - mObjects.Clear(); - - // - delete mAlert; - ZeroMemory(mAlert); - - // - delete mDrawer; - ZeroMemory(mDrawer); - - // - delete mBarAnalyser; - ZeroMemory(mBarAnalyser); - - // - // De Initialize all Handlers and etc ... - IndicatorRelease(atrHandler); - IndicatorRelease(sarHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(adxHandler); - IndicatorRelease(trendHandler); -} - -/** - * Calculate Bars ... - * - * @param rates_total: Integer, Total Bars on Chart ... - * @param prev_calculated: Integer, Total Calculated Bars on Charts ... - * @param time: DateTime Array, History of Open Time ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param low: Double Array, History of Low Prices ... - * @param close: Double Array, History of Close Prices ... - * @param tick_volume: Long, History of Tick Volumes on Bar ... - * @param volume: Long, History of Trade Volumes ... - * @param spread: Double, History of Spread Price ... - * - * @return ( int ) - */ -int OnCalculate( - const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[] // -) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // Validate Calculated Bars ... - - // - // ATR ... - int atrCalculatedBars = BarsCalculated(atrHandler); - - // - // SAR ... - int sarCalculatedBars = BarsCalculated(sarHandler); - - // - // RSI ... - int rsiCalculatedBars = BarsCalculated(rsiHandler); - - // - // ADX ... - int adxCalculatedBars = BarsCalculated(adxHandler); - - // - // TREND ... - int trendCalculatedBars = BarsCalculated(trendHandler); - - // - bool isPassedRequiredCalculatedBars = - // - // ATR ... - atrCalculatedBars >= maxLength && - // - // SAR ... - sarCalculatedBars >= maxLength && - // - // RSI ... - rsiCalculatedBars >= maxLength && - // - // ADX ... - adxCalculatedBars >= maxLength && - // - // TREND ... - trendCalculatedBars >= maxLength - // - ; - if (!isPassedRequiredCalculatedBars) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) - ? rates_total - : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - - // - // ATR ... - int copiedAtrs = CopyBuffer(atrHandler, MAIN_LINE, 0, limit, atrBuffer); - - // - // SAR ... - int copiedSars = CopyBuffer(sarHandler, MAIN_LINE, 0, limit, sarBuffer); - - // - // RSI ... - int copiedRSIs = CopyBuffer(rsiHandler, MAIN_LINE, 0, limit, rsiBuffer); - - // - // ADX ... - int copiedADXs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); - - // - // ADX Plus ... - int copiedADXPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxpBuffer); - - // - // ADX Negative ... - int copiedADXNs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxnBuffer); - - // - // TREND ... - int copiedTrends = CopyBuffer(trendHandler, MAIN_LINE, 0, limit, trendBuffer); - - // - // Validate Copied Items ... - bool isPassedRequiredCopiedItems = - // - // ATR ... - copiedAtrs >= limit && - // - // SAR ... - copiedSars >= limit && - // - // RSI ... - copiedRSIs >= limit && - // - // TREND ... - copiedTrends >= limit - // - ; - if (!isPassedRequiredCopiedItems) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - close, - low, - tick_volume // - ); - } - - // - if (prev_calculated == 0) - { - // - string message = "History Finished ..."; - Print(message); - } - - // - return rates_total; -} - -// -// Custom Functions ... - -/** - * Set Indicator Short Name and also we can define Buffers Labels ... - */ -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -/** - * Validate Input Args for Initialization ... - * - * @return ( bool ) - */ -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - sarMax > 0 && - sarStep > 0 && - rsiOBLevel > 0 && - rsiOSLevel > 0 && - adxThreshold > 0 && - sarMax > sarStep && - atrMultiplier > 0 && - // - IsValid(appliedCycle) && - // - IsValid(atrUpperPriceType) && - IsValid(atrLowerPriceType) && - // - // CYCLES ... - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) - // - ; - - // - return result; -} - -/** - * Extract Max Length of Inputs ... - * - * @return ( int ) - */ -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(mSCLength, mMCLength); - result = MathMax(result, mLCLength); - result = MathMax(result, mHCLength); - - // - return result; -} - -/** - * Define Required Buffers ... - */ -void DefineBuffers() -{ - // - // Plot Buffers ... - - // - // SAR ... - - // - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_SHOW_DATA, showSar); - PlotIndexSetDouble(sarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sarBufferPlotIndex, PLOT_ARROW, sarArrowCode); - - // - ArraySetAsSeries(sarColorBuffer, true); - SetIndexBuffer(sarColorBufferIndex, sarColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(sarStateBuffer, true); - SetIndexBuffer(sarStateBufferIndex, sarStateBuffer, INDICATOR_CALCULATIONS); - - // - // PEAK / VALE ... - - // - ENUM_DRAW_TYPE pvDrawType = showPV ? DRAW_ARROW : DRAW_NONE; - - // - // PEAK ... - - // - ArraySetAsSeries(peakBuffer, true); - SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(peakBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(peakBufferPlotIndex, PLOT_ARROW, peakArrowCode); - - // - // VALE ... - - // - ArraySetAsSeries(valeBuffer, true); - SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_SHOW_DATA, showPV); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - PlotIndexSetDouble(valeBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(valeBufferPlotIndex, PLOT_ARROW, valeArrowCode); - - // - // PV GOLDEN ... - - // - ENUM_DRAW_TYPE pvGoldenDrawType = showPVGolden ? DRAW_LINE : DRAW_NONE; - - // - // PEAK Golden ... - - // - ArraySetAsSeries(peakGoldenBuffer, true); - SetIndexBuffer(peakGoldenBufferIndex, peakGoldenBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(peakGoldenBufferPlotIndex, PLOT_SHOW_DATA, showPVGolden); - PlotIndexSetInteger(peakGoldenBufferPlotIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); - - // - PlotIndexSetDouble(peakGoldenBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // VALE Golden ... - - // - ArraySetAsSeries(valeGoldenBuffer, true); - SetIndexBuffer(valeGoldenBufferIndex, valeGoldenBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(valeGoldenBufferPlotIndex, PLOT_SHOW_DATA, showPVGolden); - PlotIndexSetInteger(valeGoldenBufferPlotIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); - - // - PlotIndexSetDouble(valeGoldenBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // ATR Band ... - - // - // UPPER ... - ENUM_DRAW_TYPE atrUpperDrawType = showATRBand ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(atrUpperBuffer, true); - SetIndexBuffer(atrUpperBufferIndex, atrUpperBuffer, INDICATOR_DATA); - - // - PlotIndexSetDouble(atrUpperBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(atrUpperBufferPlotIndex, PLOT_SHOW_DATA, showATRBand); - PlotIndexSetInteger(atrUpperBufferPlotIndex, PLOT_DRAW_TYPE, atrUpperDrawType); - - // - // LOWER ... - ENUM_DRAW_TYPE atrLowerDrawType = showATRBand ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(atrLowerBuffer, true); - SetIndexBuffer(atrLowerBufferIndex, atrLowerBuffer, INDICATOR_DATA); - - // - PlotIndexSetDouble(atrLowerBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(atrLowerBufferPlotIndex, PLOT_SHOW_DATA, showATRBand); - PlotIndexSetInteger(atrLowerBufferPlotIndex, PLOT_DRAW_TYPE, atrLowerDrawType); - - // - // TREND ... - - // - ArraySetAsSeries(trendBuffer, true); - SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrend); - PlotIndexSetDouble(trendBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - ArraySetAsSeries(trendColorBuffer, true); - SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(trendStateBuffer, true); - SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); - - // - // SIGNAL Bar ... - - // - // Signal Bars Color ... - ArraySetAsSeries(sBarColorBuffer, true); - SetIndexBuffer(sBarColorBufferIndex, sBarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(sBarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(sBarBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(sBarOpenBuffer, true); - SetIndexBuffer(sBarOpenBufferIndex, sBarOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(sBarHighBuffer, true); - SetIndexBuffer(sBarHighBufferIndex, sBarHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(sBarLowBuffer, true); - SetIndexBuffer(sBarLowBufferIndex, sBarLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(sBarCloseBuffer, true); - SetIndexBuffer(sBarCloseBufferIndex, sBarCloseBuffer, INDICATOR_DATA); - - // - // XHK SIGNAL Bar ... - - // - // HK Bars Color ... - ArraySetAsSeries(hkSBarColorBuffer, true); - SetIndexBuffer(hkSBarColorBufferIndex, hkSBarColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on XHK Bar Buffer ... - PlotIndexSetDouble(hkSBarBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - PlotIndexSetInteger(hkSBarBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(hkSBarOpenBuffer, true); - SetIndexBuffer(hkSBarOpenBufferIndex, hkSBarOpenBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(hkSBarHighBuffer, true); - SetIndexBuffer(hkSBarHighBufferIndex, hkSBarHighBuffer, INDICATOR_DATA); - - // - // Low ... - ArraySetAsSeries(hkSBarLowBuffer, true); - SetIndexBuffer(hkSBarLowBufferIndex, hkSBarLowBuffer, INDICATOR_DATA); - - // - // Close ... - ArraySetAsSeries(hkSBarCloseBuffer, true); - SetIndexBuffer(hkSBarCloseBufferIndex, hkSBarCloseBuffer, INDICATOR_DATA); - - // - // CYCLES ... - - // - // SHORT ... - - // - ENUM_DRAW_TYPE sDrawType = showShortCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(sHHBuffer, true); - SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_SHOW_DATA, showShortCycle); - PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_DRAW_TYPE, sDrawType); - PlotIndexSetDouble(sHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(sLLBuffer, true); - SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_SHOW_DATA, showShortCycle); - PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_DRAW_TYPE, sDrawType); - PlotIndexSetDouble(sLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // MEDIUM ... - - // - ENUM_DRAW_TYPE mDrawType = showMediumCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(mHHBuffer, true); - SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_SHOW_DATA, showMediumCycle); - PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_DRAW_TYPE, mDrawType); - PlotIndexSetDouble(mHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(mLLBuffer, true); - SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_SHOW_DATA, showMediumCycle); - PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_DRAW_TYPE, mDrawType); - PlotIndexSetDouble(mLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LONG ... - - // - ENUM_DRAW_TYPE lDrawType = showLongCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(lHHBuffer, true); - SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_SHOW_DATA, showLongCycle); - PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_DRAW_TYPE, lDrawType); - PlotIndexSetDouble(lHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(lLLBuffer, true); - SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_SHOW_DATA, showLongCycle); - PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_DRAW_TYPE, lDrawType); - PlotIndexSetDouble(lLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // HIND ... - - // - ENUM_DRAW_TYPE hDrawType = showHindCycle ? DRAW_LINE : DRAW_NONE; - - // - // HH ... - - // - ArraySetAsSeries(hHHBuffer, true); - SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_SHOW_DATA, showHindCycle); - PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_DRAW_TYPE, hDrawType); - PlotIndexSetDouble(hHHBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // LL ... - - // - ArraySetAsSeries(hLLBuffer, true); - SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_SHOW_DATA, showHindCycle); - PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_DRAW_TYPE, hDrawType); - PlotIndexSetDouble(hLLBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); - - // - // Data Buffers ... - - // - // RSI ... - ArraySetAsSeries(rsiBuffer, true); - SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); - - // - // ADX ... - - // - ArraySetAsSeries(adxBuffer, true); - SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxpBuffer, true); - SetIndexBuffer(adxpBufferIndex, adxpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(adxnBuffer, true); - SetIndexBuffer(adxnBufferIndex, adxnBuffer, INDICATOR_CALCULATIONS); - - // - // DELTA ... - - // - ArraySetAsSeries(deltaBuffer, true); - SetIndexBuffer(deltaBufferIndex, deltaBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(deltaSignalBuffer, true); - SetIndexBuffer(deltaSignalBufferIndex, deltaSignalBuffer, INDICATOR_CALCULATIONS); - - // - // VOLUME ... - - // - ArraySetAsSeries(bullishVolumeBuffer, true); - SetIndexBuffer(bullishVolumeBufferIndex, bullishVolumeBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bearishVolumeBuffer, true); - SetIndexBuffer(bearishVolumeBufferIndex, bearishVolumeBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bullishVolumeSignalBuffer, true); - SetIndexBuffer(bullishVolumeSignalBufferIndex, bullishVolumeSignalBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bearishVolumeSignalBuffer, true); - SetIndexBuffer(bearishVolumeSignalBufferIndex, bearishVolumeSignalBuffer, INDICATOR_CALCULATIONS); - - // - // ATR ... - - ArraySetAsSeries(atrBuffer, true); - SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(atrUpperRawBuffer, true); - SetIndexBuffer(atrUpperRawBufferIndex, atrUpperRawBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(atrLowerRawBuffer, true); - SetIndexBuffer(atrLowerRawBufferIndex, atrLowerRawBuffer, INDICATOR_CALCULATIONS); - - // - // XHK ... - - // - ArraySetAsSeries(openHKBuffer, true); - SetIndexBuffer(openHKBufferIndex, openHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(highHKBuffer, true); - SetIndexBuffer(highHKBufferIndex, highHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(lowHKBuffer, true); - SetIndexBuffer(lowHKBufferIndex, lowHKBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(closeHKBuffer, true); - SetIndexBuffer(closeHKBufferIndex, closeHKBuffer, INDICATOR_CALCULATIONS); - - // -} - -/** - * Initial Market Cycles ... - * - * @return ( bool ) - */ -bool InitCycles() -{ - // - bool result = false; - - // - int cPeriodSeconds = PeriodSeconds(_Period); - - // - // Find Cycle Period ... - if (scMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mSCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_SHORT, - _Period // - ); - } - else - { - mSCPeriod = scPeriod; - } - - // - if (IsValid(mSCPeriod)) - { - mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (mcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mMCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_MEDIUM, - _Period // - ); - } - else - { - mMCPeriod = mcPeriod; - } - - // - if (IsValid(mMCPeriod)) - { - mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (lcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mLCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_LONG, - _Period // - ); - } - else - { - mLCPeriod = lcPeriod; - } - - // - if (IsValid(mLCPeriod)) - { - mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (hcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mHCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mHCPeriod = hcPeriod; - } - - // - if (IsValid(mHCPeriod)) - { - mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; - } - - // - result = mSCLength > 0 && - mMCLength > mSCLength && - mLCLength > mMCLength && - mHCLength > mLCLength; - - // - // Selecte Applied Cycle ... - if (result) - { - // - switch (appliedCycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - mAppliedLength = mSCLength; - mAppliedPeriod = mSCPeriod; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - mAppliedLength = mMCLength; - mAppliedPeriod = mMCPeriod; - break; - - // - case X_MARKET_CYCLE_LONG: - // - mAppliedLength = mLCLength; - mAppliedPeriod = mLCPeriod; - break; - - // - case X_MARKET_CYCLE_HIND: - // - mAppliedLength = mHCLength; - mAppliedPeriod = mHCPeriod; - break; - } - } - - // - return result; -} - -/** - * Initial all Indicator Requirements ... - * - * @return ( false ) - * - */ -bool InitRequirements() -{ - // - bool result = false; - - // - // Handlers ... - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMax // - ); - result = sarHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // ATR ... - atrHandler = iATR( - _Symbol, - _Period, - mAppliedLength // - ); - result = atrHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // RSI ... - rsiHandler = iRSI( - _Symbol, - _Period, - mAppliedLength, - rsiAppliedTo // - ); - result = rsiHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // ADX ... - adxHandler = iADX( - _Symbol, - _Period, - mAppliedLength // - ); - result = adxHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // TREND ... - trendHandler = iMA( - _Symbol, - _Period, - mAppliedLength, - 0, - trendMode, - trendAppliedTo // - ); - result = trendHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - // Initial Class Instances ... - - // - mDrawer = new XCPOIDrawer(); - mBarAnalyser = new XCBarAnalyser(); - - // - // Initialize and Configure Alert ... - mAlert = new XCAlert(); - mEnableAlerts = - _logAlerts || - _pushAlerts || - _mailAlerts || - _terminalAlerts; - string mPrefix = ShortName + - (!IsValid(mAlertPrefix) - ? "" - : "[" + mAlertPrefix + "]"); - mAlert.SetPrefix(mPrefix); - mAlert.SetLogAlerts(_logAlerts); - mAlert.SetMailAlerts(_mailAlerts); - mAlert.SetPushAlerts(_pushAlerts); - mAlert.SetEnableAlerts(mEnableAlerts); - mAlert.SetTerminalAlerts(_terminalAlerts); - - // - return result; -} - -/** - * Calculate Custom Buffers ... - * - * @param barIndex: Integer, Represent Current Bar ... - * @param prevCalculated: Integer, Represent Previous Calculated Bars ... - * @param ratesTotal: Integer, Represents All Available Bars ... - * @param open: Double Array, History of Open Prices ... - * @param high: Double Array, History of High Prices ... - * @param close: Double Array, History of Close Prices ... - * @param low: Double Array, History of Low Prices ... - * @param tickVolume: Long, History of Tick Volumes on Bar ... - */ -void CalculateBuffers( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int barsLimit = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : 0; - if (barsLimit == 0) - { - // - barsLimit = ratesTotal; - firstBarIndex = barsLimit - 1; - } - else - { - firstBarIndex = startCalculationForLastBars; - } - - // - // bool canCalculate = true; - bool canCalculate = - barIndex <= barsLimit; - if (canCalculate) - { - // - // Calculate Values ... - CalculateValues( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - } - else - { - FillBuffersZero(barIndex); - } -} - -/** - * Fill All Bufers to Zero Vlue for Specified Bar Index ... - * - * @param barIndex: Integer ... - */ -void FillBuffersZero(int barIndex) -{ - // - sarColorBuffer[barIndex] = hideColorIDX; - trendColorBuffer[barIndex] = hideColorIDX; - - // - atrUpperRawBuffer[barIndex] = emptyValue; - atrLowerRawBuffer[barIndex] = emptyValue; -} - -// -// Custom Handlers ... - -/** - * Calculate Values ... - * - * @param barIndex: int, Specified Bar Index ... - * @param prevCalculated: int, Provides Previous Calculated Bars ... - * @param ratesTotal: int, Provides All Availabled Bars ... - * @param open: double Collection, Provides Open Prices Time Series ... - * @param high: double Collection, Provides High Prices Time Series ... - * @param close: double Collection, Provides Close Prices Time Series ... - * @param low: double Collection, Provides Low Prices Time Series ... - * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... - */ -void CalculateValues( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - // Cycle Ranges ... - CalculateCycleRanges( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // PV ... - CalculatePV( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // SAR ... - CalculateSAR( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // SBAR ... - CalculateSBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // HKBAR ... - CalculateHKBar( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // DELTA ... - CalculateDelta( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // TREND ... - CalculateTrend( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // VOLUME ... - CalculateVolume( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // ATR Band ... - CalculateATRBand( - barIndex, - prevCalculated, - ratesTotal, - open, - high, - close, - low, - tickVolume // - ); - - // - // Try To Detect Trigger Block ... - - // - // Prevent Calculation ... - if (maxBarIndex - barIndex < maxLength) - { - return; - } - - // - XTriggerBlock tb; - bool has = DetectTriggerBlock( - // - _Symbol, - _Period, - // - tb, - // - mBarAnalyser, - // - // Required Buffers ... - atrBuffer, - rsiBuffer, - adxBuffer, - adxpBuffer, - adxnBuffer, - peakBuffer, - valeBuffer, - deltaBuffer, - sarBuffer, - sarStateBuffer, - trendBuffer, - trendStateBuffer, - atrUpperBuffer, - atrLowerBuffer, - sBarOpenBuffer, - sBarCloseBuffer, - hkSBarOpenBuffer, - hkSBarCloseBuffer, - peakGoldenBuffer, - valeGoldenBuffer, - deltaSignalBuffer, - bullishVolumeSignalBuffer, - bearishVolumeSignalBuffer, - // - barIndex, - // - // Signalling ... - signalR2R, - slAtrMultiplier, - // - // Configs ... - rsiOBLevel, - rsiOSLevel, - adxThreshold, - // - // Validators ... - forceObBarType, - forceOBFVGBarType, - forceHasSwing, - forceHasFLiquidity, - forceHasRLiquidity, - validateGapSequence, - validateBlockEdgeBreakout, - // - // Filters ... - filterBasedOnPV, - filterBasedOnSar, - filterBasedOnRSI, - filterBasedOnADX, - filterBasedOnATR, - filterBasedOnTrend, - filterBasedOnDelta, - filterBasedOnVolume, - filterBasedOnSignalBar, - filterBasedOnHKSignalBar // - ); - if (has) - { - // - // Draw ... - if (drawTriggerBlock) - { - // - has = DrawTriggerBlock( - tb, - mDrawer, - mObjects, - NULL, - drawSignals // - ); - } - - // - // Alert ... - bool canAlert = - mEnableAlerts && - prevCalculated > 0; - bool canLogOnly = - mEnableAlerts && - prevCalculated == 0; - if (has && - (canAlert || - canLogOnly)) - { - // - string message = - tb.trigger.symbol + "," + - ToString(tb.trigger.period) + "> " + - ToString(tb.trigger.dir) + - " Zone Detected at: " + ToString(tb.trigger.to); - - // - if (canLogOnly) - { - mAlert.LogAlert(message); - } - else if (canAlert) - { - mAlert.SendAlert(message); - } - } - } -} - -// -void CalculateCycleRanges( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // SHORT ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_SHORT, - sHHBuffer, - sLLBuffer // - ); - - // - // MEDIUM ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_MEDIUM, - mHHBuffer, - mLLBuffer // - ); - - // - // LONG ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_LONG, - lHHBuffer, - lLLBuffer // - ); - - // - // HIND ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_HIND, - hHHBuffer, - hLLBuffer // - ); -} - -// -void CalculatePV( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iSHH = sHHBuffer[barIndex]; - double iSLL = sLLBuffer[barIndex]; - - // - double iMHH = mHHBuffer[barIndex]; - double iMLL = mLLBuffer[barIndex]; - - // - double iLHH = lHHBuffer[barIndex]; - double iLLL = lLLBuffer[barIndex]; - - // - double iHHH = hHHBuffer[barIndex]; - double iHLL = hLLBuffer[barIndex]; - - // - // Calculate VALE ... - bool isVale = iSLL == iMLL && - iMLL == iLLL && - iLLL == iHLL; - double iPVale = - isFirstBar - ? emptyValue - : valeBuffer[lastBarIndex]; - double iVale = - isVale - ? iSLL - : iPVale; - valeBuffer[barIndex] = iVale; - - // - // Calculate PEAK ... - bool isPeak = iSHH == iMHH && - iMHH == iLHH && - iLHH == iHHH; - double iPPeak = - isFirstBar - ? emptyValue - : peakBuffer[lastBarIndex]; - double iPeak = - isPeak - ? iSHH - : iPPeak; - peakBuffer[barIndex] = iPeak; - - // - // GOLDEN ... - - XOHCL iBar; - bool isInited = iBar.Init( - _Symbol, - _Period, - barIndex // - ); - - // - // Calculate PV Gold ... - double lastPeakGold = - isFirstBar - ? emptyValue - : peakGoldenBuffer[lastBarIndex]; - double lastValeGold = - isFirstBar - ? emptyValue - : valeGoldenBuffer[lastBarIndex]; - double iPeakGold = lastPeakGold; - double iValeGold = lastValeGold; - if (isInited) - { - // - iPeakGold = iBar.FindHighest(mHCLength, MODE_CLOSE); - if (iPeakGold == 0) - { - iPeakGold = lastPeakGold; - } - - // - iValeGold = iBar.FindLowest(mHCLength, MODE_CLOSE); - if (iValeGold == 0) - { - iValeGold = lastValeGold; - } - } - else - { - // - iPeakGold = lastPeakGold; - iValeGold = lastValeGold; - } - - // - peakGoldenBuffer[barIndex] = iPeakGold; - valeGoldenBuffer[barIndex] = iValeGold; - - // - iBar.Clean(); -} - -// -void CalculateSAR( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iLow = low[barIndex]; - double iHigh = low[barIndex]; - double iSar = sarBuffer[barIndex]; - - // - bool isBullish = iSar < iLow; - bool isBearish = iSar > iHigh; - - // - double iSarState = isBullish - ? 1 - : isBearish - ? -1 - : 0; - double iSarColor = iSarState > 0 - ? bullishColorIDX - : iSarState < 0 - ? bearishColorIDX - : neuturalColorIDX; - sarStateBuffer[barIndex] = iSarState; - sarColorBuffer[barIndex] = showSar - ? iSarColor - : hideColorIDX; -} - -// -void CalculateSBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - open, - sBarOpenBuffer, - barsSignalMethod // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - close, - sBarCloseBuffer, - barsSignalMethod // - ); - - // - double min = MathMin(sBarCloseBuffer[barIndex], sBarOpenBuffer[barIndex]); - double max = MathMin(sBarCloseBuffer[barIndex], sBarOpenBuffer[barIndex]); - - // - sBarLowBuffer[barIndex] = min; - sBarHighBuffer[barIndex] = max; - - // - // Calculate HK Signal Color ... - double iSignalColorValue = - sBarOpenBuffer[barIndex] < sBarCloseBuffer[barIndex] - ? bullishColorIDX - : bearishColorIDX; - sBarColorBuffer[barIndex] = - showSignalBars - ? iSignalColorValue - : hideColorIDX; -} - -// -void CalculateHKBar( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double lastHKOpen = - isFirstBar - ? emptyValue - : openHKBuffer[lastBarIndex]; - double lastHKClose = - isFirstBar - ? emptyValue - : closeHKBuffer[lastBarIndex]; - - // - double iHKOpenValue = (lastHKOpen + lastHKClose) / 2; - double iHKCloseValue = (open[barIndex] + high[barIndex] + close[barIndex] + low[barIndex]) / 4; - double iHKHighValue = MathMax(high[barIndex], MathMax(iHKOpenValue, iHKCloseValue)); - double iHKLowValue = MathMin(low[barIndex], MathMin(iHKOpenValue, iHKCloseValue)); - - // - // Raw HK Buffers ... - openHKBuffer[barIndex] = iHKOpenValue; - highHKBuffer[barIndex] = iHKHighValue; - lowHKBuffer[barIndex] = iHKLowValue; - closeHKBuffer[barIndex] = iHKCloseValue; - - // - // XHK Signal ... - - // - // Open ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - openHKBuffer, - hkSBarOpenBuffer, - hkSignalBarMethod // - ); - - // - // Close ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - closeHKBuffer, - hkSBarCloseBuffer, - hkSignalBarMethod // - ); - - // - double min = MathMin(hkSBarCloseBuffer[barIndex], hkSBarOpenBuffer[barIndex]); - double max = MathMin(hkSBarCloseBuffer[barIndex], hkSBarOpenBuffer[barIndex]); - - // - hkSBarLowBuffer[barIndex] = min; - hkSBarHighBuffer[barIndex] = max; - - // - // Calculate HK Signal Color ... - double iHKSignalColorValue = - hkSBarOpenBuffer[barIndex] < hkSBarCloseBuffer[barIndex] - ? bullishColorIDX - : bearishColorIDX; - hkSBarColorBuffer[barIndex] = - showHKSignalBars - ? iHKSignalColorValue - : hideColorIDX; -} - -// -void CalculateDelta( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - int lastBarIndex = barIndex + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? barIndex == startCalculationForLastBars - : barIndex == firstBarIndex; - - // - double iClose = close[barIndex]; - double iOpen = open[barIndex]; - double iVolume = (double)iVolume(_Symbol, _Period, barIndex); - - // - bool isBullish = iClose > iOpen; - bool isBearish = iClose < iOpen; - - // - // DELTA ... - double lastDelta = - isFirstBar - ? emptyValue - : deltaBuffer[lastBarIndex]; - double iAppliedVolume = - isBullish - ? iVolume - : -1 * iVolume; - double iDelta = - lastDelta + iAppliedVolume; - deltaBuffer[barIndex] = iDelta; - - // - // Calculate Delta Signal ... - int deltaSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - deltaBuffer, - deltaSignalBuffer, - deltaSignalMethod // - ); -} - -// -void CalculateTrend( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iLow = low[barIndex]; - double iHigh = high[barIndex]; - double iClose = close[barIndex]; - double iTrend = trendBuffer[barIndex]; - - // - bool isBullish = iTrend < iLow; - bool isBearish = iTrend > iHigh; - - // - double iTrendState = - isBullish - ? 1 - : isBearish - ? -1 - : 0; - double iTrendColor = - iTrendState > 0 - ? bullishColorIDX - : iTrendState < 0 - ? bearishColorIDX - : neuturalColorIDX; - trendStateBuffer[barIndex] = iTrendState; - trendColorBuffer[barIndex] = showTrend - ? iTrendColor - : hideColorIDX; -} - -// -void CalculateVolume( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iClose = close[barIndex]; - double iOpen = open[barIndex]; - double iVolume = (double)iVolume(_Symbol, _Period, barIndex); - - // - bool isBullish = iClose > iOpen; - bool isBearish = iClose < iOpen; - - // - double iBullishVolume = emptyValue; - double iBearishVolume = emptyValue; - if (isBullish) - { - iBullishVolume = iVolume; - } - else if (isBearish) - { - iBearishVolume = iVolume; - } - else - { - // - double iHalfVolume = iVolume / 2; - - // - iBullishVolume = iHalfVolume; - iBearishVolume = iHalfVolume; - } - bullishVolumeBuffer[barIndex] = iBullishVolume; - bearishVolumeBuffer[barIndex] = iBearishVolume; - - // - // Calculate Volume Signals ... - - // - int bullishVolumeSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - bullishVolumeBuffer, - bullishVolumeSignalBuffer, - volumeSignalMethod // - ); - - // - int bearishVolumeSignalsCount = iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - bearishVolumeBuffer, - bearishVolumeSignalBuffer, - volumeSignalMethod // - ); -} - -// -void CalculateATRBand( - int barIndex, - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - double iATR = atrBuffer[barIndex]; - double iAppliedATR = atrMultiplier * iATR; - double iATRUpperPrice = GetAppliedPrice( - atrUpperPriceType, - open, - high, - low, - close, - barIndex // - ); - double iATRLowerPrice = GetAppliedPrice( - atrLowerPriceType, - open, - high, - low, - close, - barIndex // - ); - double iATRUpper = iATRUpperPrice + iAppliedATR; - double iATRLower = iATRLowerPrice - iAppliedATR; - atrUpperRawBuffer[barIndex] = iATRUpper; - atrLowerRawBuffer[barIndex] = iATRLower; - - // - bool canSignalATR = IsValid(atrSignalMethod); - if (canSignalATR) - { - // - // Upper ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - atrUpperRawBuffer, - atrUpperBuffer, - atrSignalMethod // - ); - - // - // Lower ... - iMAOnBuffer( - ratesTotal, - prevCalculated, - barIndex, - mAppliedLength, - atrLowerRawBuffer, - atrLowerBuffer, - atrSignalMethod // - ); - } - else - { - // - atrUpperBuffer[barIndex] = iATRUpper; - atrLowerBuffer[barIndex] = iATRLower; - } -} - -/** - * Calculate Specified Market Cycle Info ... - * - * @param barIndex: Integer, Bar Index ... - * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... - * @param hhBuffer: Highest High Buffer Reference ... - * @param llBuffer: Lowest Low Buffer Reference ... - */ -void CalculateCycle( - int barIndex, - ENUM_X_MARKET_CYCLES cycle, - double &hhBuffer[], - double &llBuffer[] // -) -{ - // - XOHCL bar; - bool isBarInited = bar.Init( - _Symbol, - _Period, - barIndex - // - ); - if (!isBarInited) - { - return; - } - - // - int mLength = 0; - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - mLength = mSCLength; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - mLength = mMCLength; - break; - - // - case X_MARKET_CYCLE_LONG: - mLength = mLCLength; - break; - - // - case X_MARKET_CYCLE_HIND: - mLength = mHCLength; - break; - } - - // - if (mLength == 0) - { - return; - } - - // - // Find Highest High ... - double hhValue = bar.FindHighest( - mLength, - upperMode // - ); - hhBuffer[barIndex] = hhValue; - - // - // Find Lowest Low ... - double llValue = bar.FindLowest( - mLength, - lowerMode // - ); - llBuffer[barIndex] = llValue; - - // - bar.Clean(); -} - -// -void ReadBarStyle() -{ - // - long chartId = ChartID(); - - // - _upColor = GetChartUpColor(chartId); - _downColor = GetChartDownColor(chartId); - _lineColor = GetChartLineColor(chartId); - _bullishColor = GetChartBullishColor(chartId); - _bearishColor = GetChartBearishColor(chartId); -} - -// -void ShowBars() -{ - // - long chartId = ChartID(); - - // - SetChartUpColor(_upColor, chartId); - SetChartDownColor(_downColor, chartId); - SetChartLineColor(_lineColor, chartId); - SetChartBullishColor(_bullishColor, chartId); - SetChartBearishColor(_bearishColor, chartId); -} - -// -void HideBars() -{ - // - long chartId = ChartID(); - - // - SetChartUpColor(CLR_NONE, chartId); - SetChartDownColor(CLR_NONE, chartId); - SetChartLineColor(CLR_NONE, chartId); - SetChartBullishColor(CLR_NONE, chartId); - SetChartBearishColor(CLR_NONE, chartId); -} - -// \ No newline at end of file diff --git a/Documents/BKP/XCAEA_BKP/x-saherelm.xcaea.ea.mq5 b/Documents/BKP/XCAEA_BKP/x-saherelm.xcaea.ea.mq5 deleted file mode 100644 index de8a36a9..00000000 --- a/Documents/BKP/XCAEA_BKP/x-saherelm.xcaea.ea.mq5 +++ /dev/null @@ -1,961 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XCAEA MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XCAEA -// Description: an Exper Advisor which used Panels -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XCAEA EA" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" -#include "../XCAEA/Classes/xcaea.x-trade.manager.class.mq5" -#include "../XCAEA/Signals/xcaea.signaller.class.mq5" - -// -#define ShortName "XCAEAEA" - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix -input ENUM_TIMEFRAMES eaAnalysisPeriod = PERIOD_H1; // Analysis Period - -// -// Symbols ... -// -// ------------------------------------------------------- -// ---------- -// eaSymbols: -// ---------- -// - if EMPTY use Current Symbol; -// - for Multi Symbol use Comma Separated Symbols: -// EURUSDb,XAUUSDb -// -// ------------------ -// eaSymbolSessions: -// ------------------ -// - if EMPTY use WHOLE Times; -// - for each Symbol use Comma Separated: -// (XEURS1_02:00_14:00),(XEURS2_19:00_23:00)| -// ------------------------------------------------------- -input group "Symbols"; -input string eaSymbols = ""; // Symbols Description -input string eaSymbolSessions = ""; // Symbols Sessions - -// -// 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 ... -input group "Management"; -input bool eaAllowTrade = true; // Allow Trade on Signals -input bool eaAllowLongs = true; // Allow Long Trades -input bool eaAllowShorts = true; // Allow Short Trades -input ENUM_XCAEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCAEA_TRADE_RESTRICATION_DAILY; // Trade Restrictions Period -input int eaMaxAllowedTPs = 2; // Max Allowed TP(s) per Day -input int eaMaxAllowedSLs = 2; // Max Allowed SL(s) per Day -input int eaMaxAllowedTrades = 3; // Max Allowed Trades per Day -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 = false; // 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 eaReportProtector = true; // Report Protector Actions -input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished - -// -// Variables, Instances ... -XCAlert *eaAlert; -XCTrade *eaTrade; -XSignal eaSignal; -XCVolume *eaVolume; -XTimeTracker eaTimeTracker; -XCXCAEASignaller *eaSignallers[]; -XCXCAEATradeManager *eaTradeManager; -XCAEAStrategyConditions eaConditions; - -// -string eaTag = ""; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initialize Timer ... - if (!InitTimer()) - { - return INIT_FAILED; - } - - // - // Initial Requirements ... - InitRequirements(); - - // - // Initialize Volume Manger ... - if (!InitVolume()) - { - return INIT_FAILED; - } - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - - // - ZeroMemory(eaAlert); - ZeroMemory(eaTrade); - ZeroMemory(eaVolume); - - // - eaSignal.Clean(); - eaConditions.Clean(); - eaTimeTracker.Clean(); - - // - int count = ArraySize(eaSignallers); - for (int i = 0; i < count; i++) - { - // - eaSignallers[i].DeInit(); - ZeroMemory(eaSignallers[i]); - } - Clean(eaSignallers); - - // - DestroyTimer(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - int idx = -1; - int count = 0; - bool has = false; - - // - HandleTimeReport(); - - // - // Handle Position Management / Protections ... - eaTradeManager.Manage(); - - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - double r2r = 4; - string provider = "XCAEA"; - datetime cTime = TimeCurrent(); - ENUM_POSITION_TYPE type = POSITION_TYPE_BUY; - ENUM_X_ORDER_MODES mode = X_ORDER_MODE_MARKET; - - // - bool hasLong = false; - bool hasShort = false; - - // - // Checking Signallers ... - has = HasChild(eaSignallers); - if (!has) - { - return; - } - - // - int signallersCount = ArraySize(eaSignallers); - for (int is = 0; is < signallersCount; is++) - { - // - // Start Calculations ... - - // - // Retrieve Common Data ... - string symbol = eaSignallers[is].GetSymbol(); - ENUM_TIMEFRAMES period = eaSignallers[is].GetPeriod(); - - // - // Required Value For SL/TP Calculations ... - double points = GetPoints(symbol); - double pip = GetPipPrice(symbol); - double pip2 = 2 * pip; - - // - // Detect Signal Setups ... - has = eaSignallers[is].DetectSignalSetup(r2r); - if (has) - { - // - count = eaSignallers[is] - .AddConditionsIfNotExists(); - - // - eaSignallers[is].mConditions.Clean(); - } - - // - // Check Setuped Conditions Exists ... - count = ArraySize(eaSignallers[is].mConditionsCollection); - has = IsValidSize(count); - if (!has) - { - continue; - } - - // - // Loop through Setuped Conditions for - // Validating or Looking up Triggers ... - for (int i = 0; i < count; i++) - { - // - // Check Signal Triggered or not ... - has = eaSignallers[is] - .DetectSignalTrigger(eaSignallers[is] - .mConditionsCollection[i]); - - // - // If Triggered ... - if (has) - { - // - idx = i; - eaConditions = eaSignallers[is].mConditionsCollection[i]; - break; - } - - // - // Check Condition Validation ... - has = eaSignallers[is].mConditionsCollection[i].IsValid() && - eaSignallers[is].mConditionsCollection[i].IsSetuped(); - if (!has) - { - idx = i; - break; - } - } - - // - // Remove Setuped Condition if provided IDX ... - has = IsValidIndex(idx); - if (has) - { - // - ArrayRemove( - eaSignallers[is].mConditionsCollection, - idx, - 1 // - ); - } - - // - // Check EA Conditions is Valid or not ... - has = eaConditions.IsSetuped() && - eaConditions.CanTrigger(); - if (!has) - { - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - continue; - } - - // - // Setting Time to Conditions ... - eaConditions.time = cTime; - has = ToPositionType( - type, - eaConditions.type // - ); - if (!has) - { - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - continue; - } - - // - // Checking Trigger Direction ... - hasLong = eaConditions.HasBullishSignal(); - hasShort = eaConditions.HasBearishSignal(); - has = hasLong || - hasShort; - if (!has) - { - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - continue; - } - - // - // Preparing Signal ... - eaSignal.mode = mode; - eaSignal.type = type; - eaSignal.entry = GetEntry( - eaConditions.symbol, - eaConditions.dir // - ); - eaSignal.provider = provider; - eaSignal.sl = eaConditions.sl; - eaSignal.tp = eaConditions.tp; - eaSignal.volume = X_MIN_VOLUME; - eaSignal.time = eaConditions.time; - eaSignal.symbol = eaConditions.symbol; - eaSignal.period = eaConditions.period; - - // - // Handling Targets ... - ApplyTargetsOnSignal( - eaConditions.dir, - eaConditions.targets, - eaSignal // - ); - - // - // Validate Signal ... - has = eaSignal.IsValid(); - if (!has) - { - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - continue; - } - - // - // Handle Volume Management ... - double iVolume = eaVolume.CalculateVolume(eaSignal); - if (iVolume > X_MIN_VOLUME && - iVolume != eaSignal.volume) - { - eaSignal.volume = iVolume; - } - - // - // Execute Signal ... - has = eaTradeManager.Execute( - eaSignal, - eaConditions // - ); - - // - eaSignal.Clean(); - eaConditions.Clean(); - } -} - -// -// 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; - - // - // EA Alert ... - eaAlert = new XCAlert( - eaTag, - eaEnableAlerts, - eaLogAlerts, - eaTerminalAlerts, - eaMailAlerts, - eaPushAlerts // - ); - - // - // 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 XCXCAEATradeManager( - eaTrade // - ); - eaTradeManager.SaveTrades(true); - eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts); - eaTradeManager.SetAlertPrefix(eaTag); - eaTradeManager.SetAlertLogAlerts(eaLogAlerts); - eaTradeManager.SetAlertMailAlerts(eaMailAlerts); - eaTradeManager.SetAlertPushAlerts(eaPushAlerts); - eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts); - - // - // Setting Trade Reports ... - eaTradeManager - .SetTradeReports( - eaReportTrades, - eaReportSignals, - eaReportProtector, - eaReportAfterTradesBalance // - ); - - // - // Setting Trade Permissions ... - eaTradeManager - .SetTradePermissions( - eaAllowTrade, - eaAllowLongs, - eaAllowShorts // - ); - - // - // Setting Trade Restrictions ... - eaTradeManager - .SetTradeRestrictions( - eaRestrictionsPeriod, - eaMaxAllowedTPs, - eaMaxAllowedSLs, - eaMaxAllowedTrades // - ); - - // - InitSymbolSessions(); - - // -} - -/** - * Initial Symbols and Active Sessions of EA ... - */ -void InitSymbolSessions() -{ - // - string symbols[]; - string sessions[]; - string iSymbol = NULL; - XCXCAEASignaller *iSignaller; - - // - // Parse Symbols ... - int symbolsCount = 0; - bool isMultiSymbol = IsValid(eaSymbols); - if (isMultiSymbol) - { - // - symbolsCount = SplitContent( - symbols, - eaSymbols // - ); - isMultiSymbol = IsValidSize(symbolsCount); - } - if (!isMultiSymbol) - { - // - Add( - _Symbol, - symbols // - ); - - // - symbolsCount = 1; - } - - // - // Parse Sessions ... - int sessionsCount = 0; - bool hasSession = IsValid(eaSymbolSessions); - if (hasSession) - { - // - // Extract Per Symbol Sessions ... - sessionsCount = SplitContent( - sessions, - eaSymbolSessions, - "|" // - ); - } - - // - // Setting Up Symbols ... - bool has = false; - - // - for (int i = 0; i < symbolsCount; i++) - { - // - iSymbol = symbols[i]; - - // - // EA Signaller ... - iSignaller = new XCXCAEASignaller( - iSymbol, - _Period, - eaAnalysisPeriod // Analysing Period ... - ); - - // - Add( - iSignaller, - eaSignallers // - ); - - // - ZeroMemory(iSignaller); - } - - // - // Setting Up Sessions ... - if (hasSession) - { - // - for (int i = 0; i < symbolsCount; i++) - { - // - iSymbol = symbols[i]; - - // - if (i < sessionsCount) - { - // - // Extract Per Symbol Sessions ... - string iSymbolSessionsStr[]; - int iSymbolSessionsCount = SplitContent( - iSymbolSessionsStr, - sessions[i], - "," // - ); - - // - has = IsValidSize(iSymbolSessionsCount); - if (has) - { - // - // Loop through Symbols Sessions ... - for (int j = 0; j < iSymbolSessionsCount; j++) - { - // - string iSessionDescriptorStr = ExtractString(iSymbolSessionsStr[j]); - has = IsValid(iSessionDescriptorStr); - if (has) - { - // - // Extract Session Descriptor Data ... - string parts[]; - int partsCount = SplitContent( - parts, - iSessionDescriptorStr, - "_" // - ); - has = IsValidSize(partsCount) && partsCount == 3; - if (has) - { - // - string iName = parts[0]; - string iStart = parts[1]; - string iEnd = parts[2]; - has = IsValid(iName) && - IsValid(iStart) && - IsValid(iEnd); - if (has) - { - // - eaTradeManager - .SetTradeSession( - iSymbol, - iStart, - iEnd, - iName // - ); - } - } - - // - Clean(parts); - } - } - } - - // - Clean(iSymbolSessionsStr); - } - } - } - - // - Clean(symbols); - Clean(sessions); - ZeroMemory(iSignaller); -} - -/** - * Handling Time Reporting ... - */ -void HandleTimeReport() -{ - // - // 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); - } -} - -// diff --git a/Documents/BKP/catb.test.ea.tmp.mq5 b/Documents/BKP/catb.test.ea.tmp.mq5 deleted file mode 100644 index c64d330f..00000000 --- a/Documents/BKP/catb.test.ea.tmp.mq5 +++ /dev/null @@ -1,942 +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-alert.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" -#include "../Helpers/x-saherelm.x121.xcatb.helper.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Libraries/x-saherelm.x121.xcatb.lib.mq5" -#include "../XCAEA/Classes/xcaea.x-trade.manager.class.mq5" - -// -#define ShortName "XCATB_EA" - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // 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 Blocks to Have Swing -input bool eaForceObBarType = false; // Force Block Has Reversal Bar -input bool eaForceOBFVGBarType = false; // Force FVG Has Same Bars -input bool eaForceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -input bool eaForceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -input bool eaValidateGapSequence = false; // Validate Block's Gap Sequence -input bool eaValidateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -input group "Filters"; -input bool eaFilterBasedOnPV = false; // Filter Based on Peak and Vale -input bool eaFilterBasedOnSar = false; // Filter Based on Sar -input bool eaFilterBasedOnRSI = false; // Filter Based on RSI -input bool eaFilterBasedOnADX = false; // Filter Based on ADX -input bool eaFilterBasedOnATR = false; // Filter Based on ATR -input bool eaFilterBasedOnTrend = false; // Filter Based on Trend -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 Hiken Ashi Signal Bar - -// -// Signal ... -input group "Signal"; -input int eaSignalR2R = 3; // Risk Reward Ratio -input double eaSLAtrMultiplier = 0.5; // ATR Multiplier for SL - -// -// 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 ... -input group "Management"; -input bool eaAllowTrade = true; // Allow Trade on Signals -input bool eaAllowLongs = true; // Allow Long Trades -input bool eaAllowShorts = true; // Allow Short Trades -input ENUM_XCAEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCAEA_TRADE_RESTRICATION_NONE; // Trade Restrictions Period -input int eaMaxAllowedTPs = 0; // Max Allowed TP(s) per Day -input int eaMaxAllowedSLs = 0; // Max Allowed SL(s) per Day -input int eaMaxAllowedTrades = 0; // Max Allowed Trades per Day -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 = true; // 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 eaReportProtector = true; // Report Protector Actions -input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished - -// -// Variables ... - -// -XCAlert *eaAlert; -XCTrade *eaTrade; -XSignal eaSignal; -XCVolume *eaVolume; -X121XCatbInputs eaInputs; -XCX121XCatbHelper *eaHelper; -XBarTracker eaBarTraker; -XTimeTracker eaTimeTracker; -XCXCAEATradeManager *eaTradeManager; -XCAEAStrategyConditions eaConditions; - -// -XTriggerBlock eaTB; - -// -CArrayObj *eaObjects; - -// -string eaTag = ""; - -// -// 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 - - // - // eaObjects.Clear(); - - // - delete eaHelper; - ZeroMemory(eaHelper); - - // - delete eaAlert; - ZeroMemory(eaAlert); - - // - delete eaTrade; - ZeroMemory(eaTrade); - - // - delete eaVolume; - ZeroMemory(eaVolume); - - // - eaSignal.Clean(); - eaBarTraker.Clean(); - eaConditions.Clean(); - eaTimeTracker.Clean(); - - // - DestroyTimer(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - HandleTimeReport(); - - // - // Handle Position Management / Protections ... - // eaTradeManager.Manage(); - - // // - // eaSignal.Clean(); - // eaConditions.Clean(); - - // - // Check Bar Processing ... - if (!eaBarTraker.CanProcessBar()) - { - return; - } - - // - bool has = false; - - // - // Retrieve Bars ... - // XOHCL zBar; - // XOHCL cBar; - // has = zBar.Init( - // _Symbol, - // _Period, - // 0 // - // ); - // has = - // has && - // zBar.GetPreviousBar(cBar); - // if (!has) - // { - // // - // zBar.Clean(); - // cBar.Clean(); - - // // - // return; - // } - - // - // double bid = GetBid(zBar.symbol); - - // - // XTriggerBlock iTB; - // has = GetNewestX121TriggerBlock( - // _Symbol, - // _Period, - // iTB // - // ); - // if (has) - // { - // // - // // Check Newest TB is Newer Than Exists TB ... - // bool canPass = - // !eaTB.IsValid() - // ? true - // : iTB.ToIndex() < eaTB.ToIndex(); - // if (canPass) - // { - // // - // eaTB = iTB; - // eaSignal = iTB.signal; - - // // - // // Prepare eaConditions if Reuqired ... - // } - // } - - // - // has = eaSignal.IsValid(); - // if (has) - // { - // // - // // Here we ensure which has a New Signal and must - // // prepare and Execute it ... - // Print("new Signal Detected ..."); - // } - - // - // eaTB.Clean(); - // zBar.Clean(); - // cBar.Clean(); - // eaSignal.Clean(); - // eaConditions.Clean(); -} - -// -// 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() -{ - // - // Initial Bar Tracker ... - eaBarTraker.Init( - _Symbol, - _Period // - ); - - // - // 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); - - // - // Objects ... - eaObjects = new CArrayObj(); - - // - // Configure XCA ... - eaInputs.Default(); - - // - // Hide all Visible Buffers ... - eaInputs.Hide(); - - // - // we Can make Show all requirements here ... - - // - eaInputs.showATRBand = true; - - // // - // // Signal ... - // eaInputs.signalR2R = eaSignalR2R; - // eaInputs.slAtrMultiplier = eaSLAtrMultiplier; - - // // - // // Set Validators ... - // eaInputs.forceHasSwing = eaForceHasSwing; - // eaInputs.forceObBarType = eaForceObBarType; - // eaInputs.forceOBFVGBarType = eaForceOBFVGBarType; - // eaInputs.forceHasFLiquidity = eaForceHasFLiquidity; - // eaInputs.forceHasRLiquidity = eaForceHasRLiquidity; - // eaInputs.validateGapSequence = eaValidateGapSequence; - // eaInputs.validateBlockEdgeBreakout = eaValidateBlockEdgeBreakout; - - // // - // // Set Filters ... - // eaInputs.filterBasedOnPV = eaFilterBasedOnPV; - // eaInputs.filterBasedOnSar = eaFilterBasedOnSar; - // eaInputs.filterBasedOnRSI = eaFilterBasedOnRSI; - // eaInputs.filterBasedOnADX = eaFilterBasedOnADX; - // eaInputs.filterBasedOnATR = eaFilterBasedOnATR; - // eaInputs.filterBasedOnTrend = eaFilterBasedOnTrend; - // eaInputs.filterBasedOnDelta = eaFilterBasedOnDelta; - // eaInputs.filterBasedOnVolume = eaFilterBasedOnVolume; - // eaInputs.filterBasedOnSignalBar = eaFilterBasedOnSignalBar; - // eaInputs.filterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar; - - // // - // // Alerts ... - // // eaInputs.alertPrefix = eaTag; - // // eaInputs.logAlerts = eaLogAlerts; - // // eaInputs.pushAlerts = eaMailAlerts; - // // eaInputs.mailAlerts = eaPushAlerts; - // // eaInputs.terminalAlerts = eaTerminalAlerts; - - // - // eaHelper = new XCX121XCatbHelper(); - // bool isInited = eaHelper.Init( - // _Symbol, - // _Period, - // eaInputs // - // ); - - // // - // // 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 XCXCAEATradeManager( - // eaTrade // - // ); - // eaTradeManager.SaveTrades(true); - // eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts); - // eaTradeManager.SetAlertPrefix(eaTag); - // eaTradeManager.SetAlertLogAlerts(eaLogAlerts); - // eaTradeManager.SetAlertMailAlerts(eaMailAlerts); - // eaTradeManager.SetAlertPushAlerts(eaPushAlerts); - // eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts); - - // // - // // Setting Trade Reports ... - // eaTradeManager - // .SetTradeReports( - // eaReportTrades, - // eaReportSignals, - // eaReportProtector, - // eaReportAfterTradesBalance // - // ); - - // // - // // Setting Trade Permissions ... - // eaTradeManager - // .SetTradePermissions( - // eaAllowTrade, - // eaAllowLongs, - // eaAllowShorts // - // ); - - // // - // // Setting Trade Restrictions ... - // eaTradeManager - // .SetTradeRestrictions( - // eaRestrictionsPeriod, - // eaMaxAllowedTPs, - // eaMaxAllowedSLs, - // eaMaxAllowedTrades // - // ); -} - -/** - * 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); - } -} - -// -// Apply Signal Targets ... -// void ApplySignalTargets(XSignal &signal) -// { -// // -// bool has = signal.IsValid(); -// if (!has) -// { -// return; -// } - -// // -// // Clean Signal Targets ... -// Clean(signal.targets); - -// // -// // Calculate Requirements ... -// double r2r = 1; -// // maxAllowedR2R > 0 -// // ? maxAllowedR2R -// // : 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 // -// ); -// } - - -///////////////////////////////////////////////////// - - -// -static XTriggerBlock mX121TriggerBlocks[]; - -// -int HasX121TriggerBlocks() -{ - return HasChild(mX121TriggerBlocks); -} - -// -int CountX121TriggerBlocks() -{ - return ArraySize(mX121TriggerBlocks); -} - -// -void CleanX121TriggerBlocks(int maxAllowed = 0) -{ - // - if (maxAllowed <= 0) - { - Clean(mX121TriggerBlocks); - } - else if (maxAllowed > 0) - { - // - CleanupArray( - mX121TriggerBlocks, - maxAllowed // - ); - } -} - -// -bool GetNewestX121TriggerBlock( - string forSymbol, - ENUM_TIMEFRAMES forPeriod, - XTriggerBlock &tb // -) -{ - // - bool result = false; - - // - tb.Clean(); - - // - result = - IsValid(forSymbol) && - IsValid(forPeriod) && - HasX121TriggerBlocks(); - if (!result) - { - return result; - } - - // - // Loop Through Trigger Blocks to Find Filtered Newest ... - int count = CountX121TriggerBlocks(); - for (int i = 0; i < count; i++) - { - // - bool canSet = !tb.IsValid() - ? true - : tb.ToIndex() < mX121TriggerBlocks[i].ToIndex(); - if (canSet) - { - tb = mX121TriggerBlocks[i]; - } - } - - // - result = tb.IsValid(); - if (!result) - { - tb.Clean(); - } - - // - return result; -} - - -/////////////////////////////////////////////////// - - - // - // Add Trigger Block to Collection - // and Cleanup Unuseds ... - AddRef( - tb, - mX121TriggerBlocks // - ); - CleanX121TriggerBlocks(20); diff --git a/Documents/BKP/detect.block.base.trigger.mq5 b/Documents/BKP/detect.block.base.trigger.mq5 deleted file mode 100644 index a3f61bf0..00000000 --- a/Documents/BKP/detect.block.base.trigger.mq5 +++ /dev/null @@ -1,218 +0,0 @@ - - // - // Detect Block Based Trigger ... - XBoxZone ob; - XOHCL swing; - XOHCL breaker; - XOHCL outSide; - ENUM_X_DIRECTION passedDir; - bool isPassed = helper.IsBlockBasedTriggerBar( - ob, - swing, - breaker, - outSide, - passedDir, - 1, // Bar Index ... - 50, // Loopback ... - 3 // Swing Length ... - ); - if (isPassed) - { - // - // Draw Block Based Trigger ... - - // - // Draw OB ... - XCBoxObject *obObject; - has = helper.poiDrawer.DrawBox( - ob, - obObject // - ); - if (has) - { - // - obObject.BoxWidth(2); - obObject.BoxStyle(STYLE_SOLID); - - // - color obColor = - ob.IsBullish() - ? clrAqua - : clrMagenta; - obObject.BoxColor(obColor); - - // - mObjects.Add(obObject); - - // - ZeroMemory(obObject); - } - - // - double breakPrice = - ob.IsBullish() - ? swing.high - : swing.low; - - // - // Draw Swing and Breake ... - CChartObjectTrend *tObj; - tObj = new CChartObjectTrend(); - string tName = "Swing_For_" + ToString(ob.dir) + "_" + ToString(breakPrice); - has = tObj.Create( - 0, - tName, - 0, - swing.time, - breakPrice, - breaker.time, - breakPrice // - ); - if (has) - { - // - tObj.Width(2); - tObj.Style(STYLE_SOLID); - - // - color tColor = ob.IsBullish() - ? clrRed - : clrLime; - tObj.Color(tColor); - - // - mObjects.Add(tObj); - - // - ZeroMemory(tObj); - } - - // - Print("Passed Bar ..."); - } - ob.Clean(); - swing.Clean(); - breaker.Clean(); - outSide.Clean(); - - - ////////////////////////////////////////////////////////// - - - /** - * Check Specified Bar is Swing or not ... - * - * @param bar: XOHCL instance reference, Specified Swing Bar ... - * @param forDir: ENUM_X_DIRECTION member, Specified Direction of Swing ... - * @param barIndex: int, Specified Bar Index to Check ... - * @param loopback: int, Specified Loopback for BothSide Checking ... - * - * @return ( bool ) - */ - bool IsSwingSide( - XOHCL &bar, - ENUM_X_DIRECTION forDir, - int loopback = 7 // - ) - { - // - bool result = false; - - // - result = bar.IsValid() && - HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool isSwingLow = IsBullish(forDir); - bool isSwingHigh = IsBearish(forDir); - - // - string symbol = bar.symbol; - ENUM_TIMEFRAMES period = bar.period; - - // - int totalBars = iBars( - symbol, - period // - ); - int barIndex = bar.Index(); - loopback = NormalizeInt(loopback, 3); - result = - barIndex - loopback > 0 && - barIndex + 1 + loopback <= totalBars; - if (!result) - { - return result; - } - - // - for (int i = 0; i < loopback; i++) - { - // - XOHCL iPBar; - XOHCL iNBar; - result = iPBar.Init( - symbol, - period, - barIndex + i // - ); - result = - result && - iNBar.Init( - symbol, - period, - barIndex - i // - ); - if (!result) - { - // - iPBar.Clean(); - iNBar.Clean(); - - // - break; - } - - // - isSwingLow = - isSwingLow && - bar.low < iPBar.low && - bar.low < iNBar.low; - - // - isSwingHigh = - isSwingHigh && - bar.high > iPBar.high && - bar.high > iNBar.high; - - // - result = isSwingLow || - isSwingHigh; - if (!result) - { - // - iPBar.Clean(); - iNBar.Clean(); - - // - break; - } - - // - iPBar.Clean(); - iNBar.Clean(); - } - - // - if (!result) - { - bar.Clean(); - } - - // - return result; - } diff --git a/Documents/BKP/rsi.divergence.2.mq5 b/Documents/BKP/rsi.divergence.2.mq5 deleted file mode 100644 index 5d728b50..00000000 --- a/Documents/BKP/rsi.divergence.2.mq5 +++ /dev/null @@ -1,317 +0,0 @@ -//+------------------------------------------------------------------+ -//| RSI_Div.mq5 | -//| Copyright 2023, MetaQuotes Software Corp. | -//| https://www.metaquotes.net/ | -//+------------------------------------------------------------------+ -#property copyright "Copyright 2023, MetaQuotes Software Corp." -#property link "https://www.metaquotes.net/" -#property version "1.00" -#property indicator_separate_window -#property indicator_buffers 8 -#property indicator_plots 2 -#property indicator_label1 "RSI" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrDodgerBlue -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 -#property indicator_label2 "Signal" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrOrange -#property indicator_style2 STYLE_DOT -#property indicator_width2 1 - -//--- Input parameters -input int InpRSIPeriod = 14; // RSI Period -input ENUM_APPLIED_PRICE InpRSIPrice = PRICE_CLOSE; // RSI Applied Price -input int InpLeftBars = 5; // Left bars to check -input int InpRightBars = 5; // Right bars to check -input double InpMinDivergence = 5.0; // Minimum divergence in % -input bool ShowRegularBullish = true; // Show Regular Bullish -input bool ShowRegularBearish = true; // Show Regular Bearish -input bool ShowHiddenBullish = true; // Show Hidden Bullish -input bool ShowHiddenBearish = true; // Show Hidden Bearish - -//--- Indicator buffers -double RSIBuffer[]; -double SignalBuffer[]; -double HighBuffer[]; -double LowBuffer[]; -double BullishDivBuffer[]; -double BearishDivBuffer[]; -double HiddenBullishDivBuffer[]; -double HiddenBearishDivBuffer[]; - -//--- Handles -int rsiHandle; - -//+------------------------------------------------------------------+ -//| Custom indicator initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - //--- Indicator buffers mapping - SetIndexBuffer(0, RSIBuffer, INDICATOR_DATA); - SetIndexBuffer(1, SignalBuffer, INDICATOR_DATA); - SetIndexBuffer(2, HighBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(3, LowBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(4, BullishDivBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(5, BearishDivBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(6, HiddenBullishDivBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(7, HiddenBearishDivBuffer, INDICATOR_CALCULATIONS); - - //--- Set accuracy - IndicatorSetInteger(INDICATOR_DIGITS, 2); - - //--- Set first bar from what index will be drawn - PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpRSIPeriod); - - //--- Create RSI handle - rsiHandle = iRSI(NULL, 0, InpRSIPeriod, InpRSIPrice); - - if (rsiHandle == INVALID_HANDLE) - { - Print("Failed to create RSI handle"); - return (INIT_FAILED); - } - - //--- Set buffer names - string short_name = "RSI Divergence(" + string(InpRSIPeriod) + ")"; - IndicatorSetString(INDICATOR_SHORTNAME, short_name); - - //--- Set empty value - PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0.0); - PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, 0.0); - - //--- Initialize arrays as series - ArraySetAsSeries(RSIBuffer, true); - ArraySetAsSeries(SignalBuffer, true); - ArraySetAsSeries(HighBuffer, true); - ArraySetAsSeries(LowBuffer, true); - ArraySetAsSeries(BullishDivBuffer, true); - ArraySetAsSeries(BearishDivBuffer, true); - ArraySetAsSeries(HiddenBullishDivBuffer, true); - ArraySetAsSeries(HiddenBearishDivBuffer, true); - - return (INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| Custom indicator iteration function | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[]) -{ - //--- Check for data sufficiency - if (rates_total < InpRSIPeriod + InpLeftBars + InpRightBars) - return (0); - - //--- Get RSI values - if (CopyBuffer(rsiHandle, 0, 0, rates_total, RSIBuffer) <= 0) - { - Print("Failed to copy RSI buffer"); - return (0); - } - - //--- Calculate signal line (just for visualization) - for (int i = 0; i < rates_total; i++) - SignalBuffer[i] = 30 + (70 - 30) / 2; - - //--- Find divergences - FindDivergences(rates_total, prev_calculated, high, low, close, time); - - return (rates_total); -} - -//+------------------------------------------------------------------+ -//| Find divergences between price and RSI | -//+------------------------------------------------------------------+ -void FindDivergences(const int rates_total, - const int prev_calculated, - const double &high[], - const double &low[], - const double &close[], - const datetime &time[]) -{ - int start_bar = MathMax(InpRSIPeriod + InpLeftBars + InpRightBars, prev_calculated); - - for (int i = start_bar; i < rates_total && !IsStopped(); i++) - { - //--- Reset buffers - BullishDivBuffer[i] = 0; - BearishDivBuffer[i] = 0; - HiddenBullishDivBuffer[i] = 0; - HiddenBearishDivBuffer[i] = 0; - - //--- Check array boundaries - if (i - InpLeftBars < 0 || i + InpRightBars >= rates_total) - continue; - - //--- Find highest high and lowest low in left bars - int highest_high_bar = Highest(high, i - InpLeftBars, InpLeftBars + InpRightBars + 1); - int lowest_low_bar = Lowest(low, i - InpLeftBars, InpLeftBars + InpRightBars + 1); - - //--- Check for regular bullish divergence - if (ShowRegularBullish && lowest_low_bar >= 0) - { - int rsi_lowest_bar = LowestRSI(i - InpLeftBars, InpLeftBars + InpRightBars + 1); - - if (rsi_lowest_bar >= 0 && rsi_lowest_bar != lowest_low_bar && - low[i - lowest_low_bar] < low[i] && - RSIBuffer[i - rsi_lowest_bar] > RSIBuffer[i] && - MathAbs(RSIBuffer[i - rsi_lowest_bar] - RSIBuffer[i]) >= InpMinDivergence) - { - BullishDivBuffer[i] = RSIBuffer[i] - 5; - if (i < ArraySize(time) && i < ArraySize(low)) - ObjectCreate(0, "BullDiv" + IntegerToString(i), OBJ_ARROW_UP, 0, time[i], low[i] - 50 * _Point); - } - } - - //--- Check for regular bearish divergence - if (ShowRegularBearish && highest_high_bar >= 0) - { - int rsi_highest_bar = HighestRSI(i - InpLeftBars, InpLeftBars + InpRightBars + 1); - - if (rsi_highest_bar >= 0 && rsi_highest_bar != highest_high_bar && - high[i - highest_high_bar] > high[i] && - RSIBuffer[i - rsi_highest_bar] < RSIBuffer[i] && - MathAbs(RSIBuffer[i - rsi_highest_bar] - RSIBuffer[i]) >= InpMinDivergence) - { - BearishDivBuffer[i] = RSIBuffer[i] + 5; - if (i < ArraySize(time) && i < ArraySize(high)) - ObjectCreate(0, "BearDiv" + IntegerToString(i), OBJ_ARROW_DOWN, 0, time[i], high[i] + 50 * _Point); - } - } - - //--- Check for hidden bullish divergence - if (ShowHiddenBullish && lowest_low_bar >= 0) - { - int rsi_lowest_bar = LowestRSI(i - InpLeftBars, InpLeftBars + InpRightBars + 1); - - if (rsi_lowest_bar >= 0 && rsi_lowest_bar != lowest_low_bar && - low[i - lowest_low_bar] > low[i] && - RSIBuffer[i - rsi_lowest_bar] < RSIBuffer[i] && - MathAbs(RSIBuffer[i - rsi_lowest_bar] - RSIBuffer[i]) >= InpMinDivergence) - { - HiddenBullishDivBuffer[i] = RSIBuffer[i] - 8; - if (i < ArraySize(time) && i < ArraySize(low)) - ObjectCreate(0, "HidBullDiv" + IntegerToString(i), OBJ_ARROW_UP, 0, time[i], low[i] - 80 * _Point); - } - } - - //--- Check for hidden bearish divergence - if (ShowHiddenBearish && highest_high_bar >= 0) - { - int rsi_highest_bar = HighestRSI(i - InpLeftBars, InpLeftBars + InpRightBars + 1); - - if (rsi_highest_bar >= 0 && rsi_highest_bar != highest_high_bar && - high[i - highest_high_bar] < high[i] && - RSIBuffer[i - rsi_highest_bar] > RSIBuffer[i] && - MathAbs(RSIBuffer[i - rsi_highest_bar] - RSIBuffer[i]) >= InpMinDivergence) - { - HiddenBearishDivBuffer[i] = RSIBuffer[i] + 8; - if (i < ArraySize(time) && i < ArraySize(high)) - ObjectCreate(0, "HidBearDiv" + IntegerToString(i), OBJ_ARROW_DOWN, 0, time[i], high[i] + 80 * _Point); - } - } - } -} - -//+------------------------------------------------------------------+ -//| Find bar with highest price in range | -//+------------------------------------------------------------------+ -int Highest(const double &price[], int start_pos, int count) -{ - if (start_pos < 0 || count <= 0 || start_pos + count > ArraySize(price)) - return -1; - - int highest_pos = start_pos; - double highest_val = price[start_pos]; - - for (int i = start_pos + 1; i < start_pos + count; i++) - { - if (price[i] > highest_val) - { - highest_val = price[i]; - highest_pos = i; - } - } - - return highest_pos - start_pos; -} - -//+------------------------------------------------------------------+ -//| Find bar with lowest price in range | -//+------------------------------------------------------------------+ -int Lowest(const double &price[], int start_pos, int count) -{ - if (start_pos < 0 || count <= 0 || start_pos + count > ArraySize(price)) - return -1; - - int lowest_pos = start_pos; - double lowest_val = price[start_pos]; - - for (int i = start_pos + 1; i < start_pos + count; i++) - { - if (price[i] < lowest_val) - { - lowest_val = price[i]; - lowest_pos = i; - } - } - - return lowest_pos - start_pos; -} - -//+------------------------------------------------------------------+ -//| Find bar with highest RSI in range | -//+------------------------------------------------------------------+ -int HighestRSI(int start_pos, int count) -{ - if (start_pos < 0 || count <= 0 || start_pos + count > ArraySize(RSIBuffer)) - return -1; - - int highest_pos = start_pos; - double highest_val = RSIBuffer[start_pos]; - - for (int i = start_pos + 1; i < start_pos + count; i++) - { - if (RSIBuffer[i] > highest_val) - { - highest_val = RSIBuffer[i]; - highest_pos = i; - } - } - - return highest_pos - start_pos; -} - -//+------------------------------------------------------------------+ -//| Find bar with lowest RSI in range | -//+------------------------------------------------------------------+ -int LowestRSI(int start_pos, int count) -{ - if (start_pos < 0 || count <= 0 || start_pos + count > ArraySize(RSIBuffer)) - return -1; - - int lowest_pos = start_pos; - double lowest_val = RSIBuffer[start_pos]; - - for (int i = start_pos + 1; i < start_pos + count; i++) - { - if (RSIBuffer[i] < lowest_val) - { - lowest_val = RSIBuffer[i]; - lowest_pos = i; - } - } - - return lowest_pos - start_pos; -} \ No newline at end of file diff --git a/Documents/BKP/rsi.divergence.mq5 b/Documents/BKP/rsi.divergence.mq5 deleted file mode 100644 index afbfd8e7..00000000 --- a/Documents/BKP/rsi.divergence.mq5 +++ /dev/null @@ -1,198 +0,0 @@ -//+------------------------------------------------------------------+ -//| RSIDivergence.mq5| -//| Custom RSI Divergence Detection Indicator | -//+------------------------------------------------------------------+ -#property strict -#property indicator_chart_window -#property indicator_buffers 2 -#property indicator_plots 0 - -//--- Input parameters -input int RSI_Period = 14; // RSI Period -input double Deviation = 0.0001; // Minimum price move to consider a swing -input int MaxBarsBack = 300; // Number of bars to analyze - -//--- Global handles -double rsiBuffer[]; -int rsiHandle; - -//--- For divergence detection -struct SwingPoint -{ - int index; - double price; - double rsi; -}; - -SwingPoint priceSwings[]; -SwingPoint rsiSwings[]; - -//+------------------------------------------------------------------+ -//| Custom indicator initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - SetIndexBuffer(0, rsiBuffer, INDICATOR_DATA); - rsiHandle = iRSI(_Symbol, _Period, RSI_Period, PRICE_CLOSE); - if (rsiHandle == INVALID_HANDLE) - { - Print("Could not create RSI handle"); - return (INIT_FAILED); - } - return (INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| Main indicator iteration function | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[]) -{ - //--- Get RSI values - ArraySetAsSeries(rsiBuffer, true); - CopyBuffer(rsiHandle, 0, 0, MaxBarsBack, rsiBuffer); - - //--- Detect swings - DetectSwingPoints(close, priceSwings); - DetectSwingPoints(rsiBuffer, rsiSwings); - - //--- Find and draw divergences - FindAndDrawDivergences(time, close); - - return (rates_total); -} - -//+------------------------------------------------------------------+ -//| Detect swing highs/lows | -//+------------------------------------------------------------------+ -void DetectSwingPoints(const double &values[], SwingPoint &swings[]) -{ - ArrayResize(swings, 0); // Clear previous swings - int count = 0; - - int size = ArraySize(values); - if (size < 3) - return; // Not enough data - - // Pre-allocate a safe amount of space - ArrayResize(swings, size / 2); // Max possible swings ~50% of total bars - - for (int i = 2; i < size - 2; i++) - { - // Bounds check - if (i - 1 < 0 || i + 1 >= size) - continue; - - // Check for swing high - if (values[i] > values[i - 1] && values[i] > values[i + 1]) - { - // Ensure we have space in the swings array - if (count >= ArraySize(swings)) - ArrayResize(swings, ArraySize(swings) + 10); - - swings[count].index = i; - swings[count].price = values[i]; - count++; - } - // Check for swing low - else if (values[i] < values[i - 1] && values[i] < values[i + 1]) - { - // Ensure we have space in the swings array - if (count >= ArraySize(swings)) - ArrayResize(swings, ArraySize(swings) + 10); - - swings[count].index = i; - swings[count].price = values[i]; - count++; - } - } - - // Final resize to actual number of swings found - ArrayResize(swings, count); -} - -//+------------------------------------------------------------------+ -//| Find and draw divergence | -//+------------------------------------------------------------------+ -void FindAndDrawDivergences(const datetime &time[], const double &close[]) -{ - static int lastAlertBar = 0; - int limit = MathMin(MaxBarsBack - 2, Bars(_Symbol, _Period)); - - for (int i = 0; i < ArraySize(priceSwings) - 1; i++) - { - for (int j = 0; j < ArraySize(rsiSwings) - 1; j++) - { - int p1 = priceSwings[i].index; - int p2 = priceSwings[i + 1].index; - int r1 = rsiSwings[j].index; - int r2 = rsiSwings[j + 1].index; - - if (MathAbs(p1 - r1) < 3 && MathAbs(p2 - r2) < 3) - { - double price1 = close[p1]; - double price2 = close[p2]; - double rsi1 = rsiBuffer[r1]; - double rsi2 = rsiBuffer[r2]; - - // Bullish Divergence - if (price2 < price1 && rsi2 > rsi1) - { - string name; - StringConcatenate(name, "BullishDiv", IntegerToString(p2)); - DrawArrow(name, time[p2], close[p2], clrLime); - // DrawLine("BullishLineP" + IntegerToString(p2), time[p2], close[p2], time[p1], close[p1], clrLime); - // DrawLine("BullishLineR" + IntegerToString(p2), time[p2], rsi2, time[p1], rsi1, clrLime); - } - - // Bearish Divergence - if (price2 > price1 && rsi2 < rsi1) - { - string name; - StringConcatenate(name, "BearishDiv", IntegerToString(p2)); - DrawArrow(name, time[p2], close[p2], clrRed); - // DrawLine("BearishLineP" + IntegerToString(p2), time[p2], close[p2], time[p1], close[p1], clrRed); - // DrawLine("BearishLineR" + IntegerToString(p2), time[p2], rsi2, time[p1], rsi1, clrRed); - } - } - } - } -} - -//+------------------------------------------------------------------+ -//| Draw arrow on chart | -//+------------------------------------------------------------------+ -void DrawArrow(string name, datetime time, double price, color col) -{ - ObjectCreate(0, name, OBJ_ARROW, 0, time, price); - ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233); // Up arrow - ObjectSetInteger(0, name, OBJPROP_COLOR, col); - ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false); -} - -//+------------------------------------------------------------------+ -//| Draw line | -//+------------------------------------------------------------------+ -void DrawLine(string name, datetime t1, double p1, datetime t2, double p2, color col) -{ - // Delete existing object if any - ObjectDelete(0, name); - - // Create trendline (use 1 for OBJ_TRENDLINE if undefined) - ObjectCreate(0, name, 1, 0, t1, p1, t2, p2); - - ObjectSetInteger(0, name, OBJPROP_COLOR, col); - ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DASHDOT); - ObjectSetInteger(0, name, OBJPROP_WIDTH, 1); - ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false); -} - -// \ No newline at end of file diff --git a/Documents/BKP/sample.mq5 b/Documents/BKP/sample.mq5 deleted file mode 100644 index a19cccf2..00000000 --- a/Documents/BKP/sample.mq5 +++ /dev/null @@ -1,2524 +0,0 @@ -// // -// // Now we Have to Detect Spike Breake Ruls ... -// // for Bullish: bar.low goes Below of pBar.low ... -// // for Bearish: bar.high goes Above of pBar.high ... -// for (int i = toIDX; i > pBarIndex; i--) -// { -// // -// // Initialize iBar ... -// result = iBar.Init( -// bar.symbol, -// bar.period, -// i // -// ); -// result = -// result && -// iBar.GetPreviousBar(iPBar); -// if (result) -// { -// // -// if (isBullish) -// { -// result = iBar.low < iPBar.low; -// } -// else if (isBearish) -// { -// result = iBar.high > iPBar.high; -// } - -// // -// if (result) -// { -// break; -// } -// } - -// // -// iBar.Clean(); -// iPBar.Clean(); -// } -// if (!result) -// { -// // -// ob.Clean(); -// fvg.Clean(); -// box.Clean(); -// pBar.Clean(); -// iBar.Clean(); -// iPBar.Clean(); -// swingBar.Clean(); -// liquidity.Clean(); - -// // -// return result; -// } - -// // -// // Update Box ... -// if (isBullish) -// { -// box.upper = MathMax(box.upper, iBar.GetDown()); -// } -// else if (isBearish) -// { -// box.lower = MathMin(box.lower, iBar.GetUp()); -// } - -bool IsTrigger( - XOHCL &bar, - XBoxZone &box, - XBoxZone &ob, - XBoxZone &fvg, - XBoxZone &liquidity, - XOHCL &swingBar, - int loopback = 10, - int hlDistance = 300, - double maxAlowedRange = 0.0, - bool forceOBOppositBar = true, - bool forceFVGBarType = true, - bool forceSwingBar = true, - bool forceGapBarBreakout = true, - bool forceCheckBarsSequence = true, - bool lookingEntry = false, - bool forceLiquidity = true, - bool forceLiquidityUsed = true, - bool forceEntryBar = true, - bool forceEntryBarPower = true - // -) -{ - // - bool result = false; - - // - // Normalize Args ... - ob.Clean(); - fvg.Clean(); - box.Clean(); - swingBar.Clean(); - liquidity.Clean(); - loopback = NormalizeInt(loopback, 5); - - // - // Validate Args ... - result = bar.IsValid(); - if (!result) - { - return result; - } - - // - XOHCL pBar; - XOHCL iBar; - XOHCL iPBar; - int barIndex; - int pBarIndex; - ENUM_X_DIRECTION iDir; - - // - result = bar.GetPreviousBar(pBar); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - barIndex = bar.Index(); - pBarIndex = pBar.Index(); - - // - // Loopback to Find a Block ... - for (int i = pBarIndex; i < pBarIndex + loopback; i++) - { - // - // Inital IBar ... - result = iBar.Init( - bar.symbol, - bar.period, - i // - ); - if (!result) - { - break; - } - - // - // Detect Block ... - result = IsOB( - iBar, - ob, - forceFVGBarType, - forceOBOppositBar // - ); - if (result) - { - // - // Validate Block Last Bars ... - if (forceOBOppositBar) - { - // - XOHCL fromBar; - XOHCL fromBarPrev; - result = ob.FromBar(fromBar); - result = - result && - fromBar.GetPreviousBar(fromBarPrev); - result = - result && - (ob.IsBullish() - ? fromBarPrev.IsBearish() - : fromBarPrev.IsBullish()); - if (result) - { - // - // Detect FVG ... - result = IsFVG( - iBar, - fvg, - forceFVGBarType // - ); - if (result) - { - // - box.Clone(ob); - box.type = "XTRG"; - box.from = fromBarPrev.time; - break; - } - } - - // - fromBar.Clean(); - fromBarPrev.Clean(); - } - - // - break; - } - - // - iBar.Clean(); - } - iBar.Clean(); - result = box.IsValid(); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - // Filter Using Max Allowed Range ... - if (maxAlowedRange > 0) - { - // - result = box.GetRange() <= (maxAlowedRange * GetPoints(bar.symbol)); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - } - - // - // Validate Gap Bar ... - if (forceGapBarBreakout) - { - // - // We Have to Check Gap Bar's Breakout ... - result = fvg.ToBar(iBar); - result = - result && - iBar.GetPreviousBar(iPBar); - result = - result && - (box.IsBullish() - ? iPBar.close > ob.upper - : iPBar.close < ob.lower); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - // Validate HH LL Distance ... - if (hlDistance > 0) - { - // - result = ob.FromBar(iBar); - if (result) - { - // - double ll = iBar.FindLowest(iBar.Index() + hlDistance, MODE_LOW); - double hh = iBar.FindHighest(iBar.Index() + hlDistance, MODE_HIGH); - - // - result = - ll > 0 && - hh > 0 && - ob.upper < hh && - ob.lower > ll; - } - - // - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - iBar.Clean(); - } - - // - int toIDX = box.ToIndex(); - int fromIDX = box.FromIndex(); - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - // We Have to Make sure Bars until Spikes Closed ... - // for Bullish: bars must Close Above box.upper ... - // for Bearish: bars must Close Below box.lower ... - for (int i = pBarIndex; i < toIDX; i++) - { - // - // Initialize iBar ... - result = iBar.Init( - bar.symbol, - bar.period, - i // - ); - result = - result && - (isBullish - ? iBar.close > box.upper - : iBar.close < box.lower); - - // - if (!result) - { - break; - } - - // - iBar.Clean(); - } - iBar.Clean(); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - // Detect Swing Bar ... - int swingBarIDX = -1; - int swingLoopback = fromIDX - pBarIndex; - if (isBullish) - { - // - // Looking for Swing Low ... - swingBarIDX = pBar.FindLowestIndex(swingLoopback, MODE_LOW); - } - else if (isBearish) - { - // - // Looking for Swing High ... - swingBarIDX = pBar.FindHighestIndex(swingLoopback, MODE_LOW); - } - result = IsValidIndex(swingBarIDX); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - // Initialize Swing Bar ... - result = swingBar.Init( - bar.symbol, - bar.period, - swingBarIDX // - ); - if (forceSwingBar) - { - // - result = - result && - IsSimpleSwing( - swingBar, - iDir // - ) && - iDir == fvg.dir; - } - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - // Update Trigger Box ... - if (isBullish) - { - box.lower = MathMin(box.lower, swingBar.GetDown()); - } - else if (isBearish) - { - box.upper = MathMin(box.upper, swingBar.GetUp()); - } - - // - // Validating Bar Sequence ... - if (forceCheckBarsSequence) - { - // - // Now we Have to Check Spike from Swing Bar Next till Current Bar ... - // To Validate Highs and Lows ... - for (int i = pBarIndex; i < pBarIndex + (swingBarIDX - pBarIndex) - 1; i++) - { - // - // Initialize iBar ... - result = iBar.Init( - bar.symbol, - bar.period, - i // - ); - result = - result && - iBar.GetPreviousBar(iPBar); - if (!result) - { - break; - } - - // - // Since we Go Backward Bars from Current Bar ... - // for Bullish: each Bar Low Must over Prev Bar Low ... - // for Bearish: each Bar High Must Under Prev Bar High ... - if (isBullish) - { - // - result = - result && - iBar.low > iPBar.low; - } - else if (isBearish) - { - // - result = - result && - iBar.high < iPBar.high; - } - if (!result) - { - break; - } - - // - iBar.Clean(); - iPBar.Clean(); - } - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - box.to = pBar.time; - - // - iBar.Clean(); - iPBar.Clean(); - } - - // - toIDX = box.ToIndex(); - fromIDX = box.FromIndex(); - - // - // Liquidity ... - if (forceLiquidity) - { - // - // Checking Swing Bar is Liquidity ... - result = IsRejected( - swingBar, - iDir, - true, // Force Bar Type ... - true // Foce Fibo Pressure ... - ) && - iDir == fvg.dir; - if (result) - { - // - // Filling Liquidity ... - liquidity.dir = iDir; - liquidity.to = box.to; - liquidity.type = "XLQ"; - liquidity.from = swingBar.time; - liquidity.symbol = swingBar.symbol; - liquidity.period = swingBar.period; - liquidity.upper = isBullish - ? swingBar.GetDown() - : swingBar.high; - liquidity.lower = isBullish - ? swingBar.low - : swingBar.GetUp(); - - // - result = liquidity.IsValid(); - } - result = liquidity.IsValid(); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - - // - // Check Liquidity Usage ... - if (forceLiquidityUsed) - { - // - // now We have to Ensure Detected Liqudity is Used ... - toIDX = box.ToIndex(); - fromIDX = liquidity.FromIndex(); - for (int i = fromIDX - 1; i >= toIDX; i--) - { - // - // Initialize iBar ... - result = iBar.Init( - bar.symbol, - bar.period, - i // - ); - result = - result && - (isBullish - ? iBar.low < liquidity.upper - : iBar.high > liquidity.lower); - if (result) - { - break; - } - - // - iBar.Clean(); - } - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - } - } - - // - // Looking for Entry ... - if (lookingEntry) - { - // - // Entry Bar ... - if (forceEntryBar) - { - // - // Validate Bar is Not Opposit Powered Bar ... - - // - // Momentum ... - bool isMomentum = IsMomentum( - bar, - iDir, - 1 // - ); - bool isBullishMomentum = - isMomentum && - IsBullish(iDir); - bool isBearishMomentum = - isMomentum && - IsBearish(iDir); - - // - // Engulfed ... - bool isEngulfed = IsEngulfed( - bar, - iDir // - ); - bool isBullishEngulfed = - isEngulfed && - IsBullish(iDir); - bool isBearishEngulfed = - isEngulfed && - IsBearish(iDir); - - // - // Rejected ... - bool isRejected = IsRejected( - bar, - iDir, - false, - true // - ); - bool isBullishRejected = - isRejected && - IsBullish(iDir); - bool isBearishRejected = - isRejected && - IsBearish(iDir); - - // - bool isBullishPowered = - isBullishMomentum || - isBullishEngulfed || - isBullishRejected; - - // - bool isBearishPowered = - isBearishMomentum || - isBearishEngulfed || - isBearishRejected; - - // - // Make Sure Entry Bar is a Valid Bar ... - result = - isBullish - ? !isBearishPowered && (!forceEntryBarPower - ? true - : isBullishPowered) - : !isBullishPowered && (!forceEntryBarPower - ? true - : isBearishPowered); - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - pBar.Clean(); - iBar.Clean(); - iPBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - - // - return result; - } - } - - // - // Check Entry Bar Sequences ... - if (forceCheckBarsSequence) - { - // - // if Sequences is Important ... - // we have to detect sequence Breaker Bar ... - result = - result && - (isBullish - ? bar.low < pBar.low - : bar.high > pBar.high); - } - - // - // Validate Bar Close ... - result = - result && - (isBullish - ? bar.close > box.lower - : bar.close < box.upper); - } - - // - if (!lookingEntry) - { - result = fvg.to == pBar.time; - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - pBar.Clean(); - iPBar.Clean(); - - // - if (!result) - { - // - ob.Clean(); - fvg.Clean(); - box.Clean(); - swingBar.Clean(); - swingBar.Clean(); - liquidity.Clean(); - } - - // - return result; -} - - -///////////////////////////////////// - - -// -void DetectTriggerZone( - int bar_index, // Selected Bar Index - const int prevCalculated, - const int ratesTotal, - const double &open[], - const double &high[], - const double &close[], - const double &low[], - const long &tickVolume[] // -) -{ - // - // Check Prev Bar ... - - // - int lastBarIndex = bar_index + 1; - int maxBarIndex = startCalculationForLastBars > 0 - ? startCalculationForLastBars - : ratesTotal; - bool isFirstBar = - bar_index == maxBarIndex; - - // - // Prevent Calculation ... - if (maxBarIndex - bar_index < minZoneLength) - { - return; - } - - // - int zIDX = 0; - int cIDX = 0; - int pIDX = 0; - int p2IDX = 0; - int p3IDX = 0; - int p4IDX = 0; - double ll = 0; - double hh = 0; - bool has = false; - ENUM_X_DIRECTION iDir; - - // - // Retrieve Required Bars ... - - // - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - XOHCL cBar; // Current Finished Bar which Start Detecting Structures based on it ( End of Block and FVG Bar ) ... - XOHCL pBar; // Determines Block Gap Bar (all Filtering must applied and Check using this Bar and it's Next Bar) ... - XOHCL p2Bar; // Determines FVG's Start Bar in a Block ... - XOHCL p3Bar; // First Verification of Block ... - XOHCL p4Bar; // Seccond Verification of Block ... - - // - has = zBar.Init( - _Symbol, - _Period, - bar_index // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - has = - has && - p2Bar.GetPreviousBar(p3Bar); - has = - has && - p3Bar.GetPreviousBar(p4Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Define Zone Structure ... - XBoxZone zone; - - // - // Detect Based Order Block using CBar ... - has = barAnalyser.IsOB( - cBar, - zone, - true, // Force FVG Bar Type ... - true // Force Block Two Bar Checking ... - ); - - // - // Ensure a Block is Detected ... - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - zIDX = zBar.Index(); - cIDX = cBar.Index(); - pIDX = pBar.Index(); - p2IDX = p2Bar.Index(); - p3IDX = p3Bar.Index(); - p4IDX = p4Bar.Index(); - - // - bool isBullish = - has && - zone.IsBullish(); - - // - bool isBearish = - has && - zone.IsBearish(); - - // - int toIDX = zone.ToIndex(); - int fromIDX = zone.FromIndex(); - - // - // Validating p2Bar and p3Bar Direction ... - if (has) - { - // - iDir = Opposit(zone.dir); - - // - has = - iDir == p3Bar.GetDirection() || - iDir == p4Bar.GetDirection(); - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Start Validating Block based on - // Detected One ... - - // - // Validating Using Max Range ... - has = maxZoneRangeInPoints > 0; - if (has) - { - // - double range = zone.GetRange(); - has = range <= maxZoneRangeInPoints * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Gap Endup with PinBar ... - has = forceHasPinBarEntry; - if (has) - { - // - bool isBullishRejected = - isBullish && - cBar.IsBullish() && - cBar.GetLowShadow() > cBar.GetHighShadow(); - - // - bool isBearishRejected = - isBearish && - cBar.IsBearish() && - cBar.GetLowShadow() < cBar.GetHighShadow(); - - // - has = isBullishRejected || - isBearishRejected; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Gap Bar must a Momentum Bar and - // Breakes out Zone's Directional Edge ... - // for Bullish: Upper - // for Bearish: Lower - has = forceGapBarsBreakout; - if (has) - { - // - // Gap Bar is PBar ... - - // - // Check Gap Bar is Momentum Bar ... - has = barAnalyser.IsMomentum( - pBar, - iDir // - ); - bool isBullishMomentum = - has && - IsBullish(iDir); - bool isBearishMomentum = - has && - IsBearish(iDir); - - // - // Check Gap Bar's Breakout ... - - // - bool isBullishBreakedout = - isBullish && - pBar.IsBullish() && - isBullishMomentum && - pBar.GetUp() > zone.upper && - pBar.GetDown() < zone.upper; - - // - bool isBearishBreakedout = - isBearish && - pBar.IsBearish() && - isBearishMomentum && - pBar.GetUp() > zone.lower && - pBar.GetDown() < zone.lower; - - // - has = isBullishBreakedout || - isBearishBreakedout; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validate Zone Has Propper Swing ... - // for Bullish: p2Bar or p3Bar must be a Swing Low ... - // for Bearish: p2Bar or p3Bar must be a Swing High ... - has = forceHasSwing; - if (has) - { - // - // p2Bar ... - bool isP2BarSwing = - barAnalyser - .IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarSwingLow = - isP2BarSwing && - IsBullish(iDir); - bool isP2BarSwingHigh = - isP2BarSwing && - IsBearish(iDir); - - // - // p3Bar ... - bool isP3BarSwing = - barAnalyser - .IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarSwingLow = - isP3BarSwing && - IsBullish(iDir); - bool isP3BarSwingHigh = - isP3BarSwing && - IsBearish(iDir); - - // - bool hasSwingLow = - isBullish && - (isP2BarSwingLow || - isP3BarSwingLow); - - // - bool hasSwingHigh = - isBearish && - (isP2BarSwingHigh || - isP3BarSwingHigh); - - // - has = - hasSwingLow || - hasSwingHigh; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Validating Using Swing Length ... - has = minZoneLength > 0; - if (has) - { - // - XOHCL fromBar; - has = zone.FromBar(fromBar); - if (has) - { - // - // Retrieve HH and LL ... - ll = fromBar.FindLowest(minZoneLength, MODE_LOW); - hh = fromBar.FindHighest(minZoneLength, MODE_HIGH); - - // - // Validate Using HH and LL ... - - // - bool isBullishValid = - isBullish && - ll >= zone.lower; - - // - bool isBearishValid = - isBearish && - hh <= zone.upper; - - // - has = isBullishValid || - isBearishValid; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - - // - // Update Zone's From Time ... - zone.from = GetBarTime( - zone.symbol, - zone.period, - fromBar.Index() + minZoneLength // - ); - } - - // - fromBar.Clean(); - } - - // - // Validate Max Allowed Entry Distance ... - has = maxAllowedEntryDistance > 0; - if (has) - { - // - double base = - isBullish - ? zone.upper - : zone.lower; - double entryDistance = MathAbs(zBar.open - base); - has = entryDistance <= maxAllowedEntryDistance * mPoints; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // Here we Ensure which have a Valid Zone using Different Applied Validations ... - // from now we are Going to Filtered Validate Zones ... - - // - // Check Exists Filters or not ... - has = filterBasedOnSar || - filterBasedOnRSI || - filterBasedOnADX || - filterBasedOnTrend; - if (has) - { - // - // Do Apply Several Exists Filters ... - - // - // SAR Filter ... - if (filterBasedOnSar) - { - // - // Reading Conditions Values ... - - // - double zSar = sarBuffer[zIDX]; - double cSar = sarBuffer[cIDX]; - double pSar = sarBuffer[pIDX]; - double p2Sar = sarBuffer[p2IDX]; - double p3Sar = sarBuffer[p3IDX]; - double p4Sar = sarBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFiltered = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // RSI Filter ... - if (filterBasedOnRSI) - { - // - // Reading Conditions Values ... - - // - double rsiTrend = (rsiOBLevel + rsiOSLevel) / 2; - - // - double zRSI = rsiBuffer[zIDX]; - double cRSI = rsiBuffer[cIDX]; - double pRSI = rsiBuffer[pIDX]; - double p2RSI = rsiBuffer[p2IDX]; - double p3RSI = rsiBuffer[p3IDX]; - double p4RSI = rsiBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI <= rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI >= rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > rsiOSLevel && - cRSI > rsiOSLevel && - pRSI > rsiOSLevel && - p2RSI <= rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < rsiOBLevel && - cRSI < rsiOBLevel && - pRSI < rsiOBLevel && - p2RSI >= rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // ADX Filter ... - if (filterBasedOnADX) - { - // - // Reading Conditions Values ... - - // - // ADX ... - double zADX = adxBuffer[zIDX]; - double cADX = adxBuffer[cIDX]; - double pADX = adxBuffer[pIDX]; - double p2ADX = adxBuffer[p2IDX]; - double p3ADX = adxBuffer[p3IDX]; - double p4ADX = adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = adxpBuffer[zIDX]; - double cADXP = adxpBuffer[cIDX]; - double pADXP = adxpBuffer[pIDX]; - double p2ADXP = adxpBuffer[p2IDX]; - double p3ADXP = adxpBuffer[p3IDX]; - double p4ADXP = adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = adxnBuffer[zIDX]; - double cADXN = adxnBuffer[cIDX]; - double pADXN = adxnBuffer[pIDX]; - double p2ADXN = adxnBuffer[p2IDX]; - double p3ADXN = adxnBuffer[p3IDX]; - double p4ADXN = adxnBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > adxThreshold; - bool isZADXBearish = zADX < adxThreshold; - - // - bool isCADXBullish = cADX > adxThreshold; - bool isCADXBearish = cADX < adxThreshold; - - // - bool isPADXBullish = pADX > adxThreshold; - bool isPADXBearish = pADX < adxThreshold; - - // - bool isP2ADXBullish = p2ADX > adxThreshold; - bool isP2ADXBearish = p2ADX < adxThreshold; - - // - bool isP3ADXBullish = p3ADX > adxThreshold; - bool isP3ADXBearish = p3ADX < adxThreshold; - - // - bool isP4ADXBullish = p4ADX > adxThreshold; - bool isP4ADXBearish = p4ADX < adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // TREND Filter ... - if (filterBasedOnTrend) - { - // - // Reading Conditions Values ... - - // - double zTrend = trendBuffer[zIDX]; - double cTrend = trendBuffer[cIDX]; - double pTrend = trendBuffer[pIDX]; - double p2Trend = trendBuffer[p2IDX]; - double p3Trend = trendBuffer[p3IDX]; - double p4Trend = trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = trendStateBuffer[zIDX]; - double cTrendState = trendStateBuffer[cIDX]; - double pTrendState = trendStateBuffer[pIDX]; - double p2TrendState = trendStateBuffer[p2IDX]; - double p3TrendState = trendStateBuffer[p3IDX]; - double p4TrendState = trendStateBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFiltered = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFiltered = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - has = - isBullishFiltered || - isBearishFiltered; - if (!has) - { - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - return; - } - } - - // - // SCORE Filter ... - - // - // VOLUME Filter ... - } - - // - // Detect Left Side of Box ... - XOHCL zoneLeftBar; - int idx = fromIDX + 1; - bool isBaseValid = true; - while (isBaseValid) - { - // - // Retrieve iteration Bar ... - has = zoneLeftBar.Init( - _Symbol, - _Period, - idx // - ); - if (!has) - { - // - zoneLeftBar.Clean(); - break; - } - - // - // Check Bar's Validation ... - - // - bool isBullishPassed = - isBullish && - zoneLeftBar.low >= zone.lower; - - // - bool isBearishPassed = - isBearish && - zoneLeftBar.high <= zone.upper; - - // - // Summarize Conditions ... - has = - isBullishPassed || - isBearishPassed; - if (!has) - { - break; - } - - // - idx++; - } - - // - // Ray to Left Side Zone, if Provided ... - if (rayLeft) - { - // - // Update Value ... - fromIDX = zone.FromIndex(); - - // - // Check Last Iteration Bar is Valid Bar ... - // then Update Zone from Time ... - has = zoneLeftBar.IsValid(); - if (has) - { - // - zone.from = zoneLeftBar.time; - fromIDX = zone.FromIndex(); - } - } - - // - // Draw Detected Zone ... - if (drawZones) - { - // - XCBoxObject *iZoneObj; - has = drawer.DrawBox( - zone, - iZoneObj // - ); - if (has) - { - // - ApplyStyle(iZoneObj, zone.dir); - - // - mObjects.Add(iZoneObj); - - // - // TODO: Enable This for Debugging ... - // string message = ToString(zone.dir) + " Zone Detected (" + cBar.time + ") ..."; - // Print(message); - } - ZeroMemory(iZoneObj); - } - - // - // Draw RR Tool ... - if (drawRRofZones) - { - // - double rr[]{ - 1, - 1.5, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10 // - }; - XCRRObject *iRRObj; - iRRObj = new XCRRObject(); - has = iRRObj.CreateBoxRR( - drawer.ChartIdentification(), - drawer.SubWindowIdentification(), - zone, - rr, - rrZoneLength // - ); - if (has) - { - // - int iWidth = 2; - ENUM_LINE_STYLE iStyle = STYLE_SOLID; - - // - iRRObj.TPWidth(iWidth); - iRRObj.SLWidth(iWidth); - iRRObj.EntryWidth(iWidth); - iRRObj.TargetWidth(iWidth); - - // - iRRObj.TPStyle(iStyle); - iRRObj.SLStyle(iStyle); - iRRObj.EntryStyle(iStyle); - iRRObj.TargetStyle(iStyle); - - // - iRRObj.TPColor(clrLime); - iRRObj.SLColor(clrRed); - iRRObj.EntryColor(clrYellow); - iRRObj.TargetColor(clrLightBlue); - - // - mObjects.Add(iRRObj); - } - ZeroMemory(iRRObj); - } - - // - // Handle Alerst ... - bool canAlert = - mEnableAlerts && - prevCalculated > 0; - bool canLogOnly = - mEnableAlerts && - prevCalculated == 0; - if (canAlert || canLogOnly) - { - // - string message = - zone.symbol + "," + - ToString(zone.period) + "> " + - ToString(zone.dir) + - " Zone Detected at: " + ToString(zone.to); - - // - if (canLogOnly) - { - alert.LogAlert(message); - } - else if (canAlert) - { - alert.SendAlert(message); - } - } - - // - // Cleanup Resources ... - - // - zone.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - zoneLeftBar.Clean(); -} - - - - // - // Detect Trigger Zone ... - // DetectTriggerZone( - // bar_index, - // prevCalculated, - // ratesTotal, - // open, - // high, - // close, - // low, - // tickVolume // - // ); - - - -// -// Implement all Volume and Delta Tests -// Here for Testing Purposes ... -void DoTest(int bar_index) -{ - // - int lastBarIndex = bar_index + 1; - bool isFirstBar = - startCalculationForLastBars > 0 - ? bar_index == startCalculationForLastBars - : bar_index == firstBarIndex; - - // - // Ignore Tests on First Bar ... - if (isFirstBar || - bar_index == firstBarIndex - 1) - { - return; - } - - // - bool has = false; - string iName = NULL; - color iClr = CLR_NONE; - datetime iTime = GetBarTime( - _Symbol, - _Period, - bar_index // - ); - ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; - - // - // Delta Testing ... - - // - double iDelta = deltaBuffer[bar_index]; - double iDeltaPrev = deltaBuffer[lastBarIndex]; - double iDeltaP2 = deltaBuffer[lastBarIndex + 1]; - - // - bool isDeltaUp = iDelta > iDeltaPrev; - bool isDeltaDown = iDelta < iDeltaPrev; - - // - double iDeltaSignal = deltaSignalBuffer[bar_index]; - double iDeltaSignalPrev = deltaSignalBuffer[lastBarIndex]; - - // - bool isDeltaSignalUp = iDeltaSignal > iDeltaSignalPrev; - bool isDeltaSignalDown = iDeltaSignal < iDeltaSignalPrev; - - // - bool isDeltaSwitchedToBullish = - isDeltaUp && - isDeltaSignalUp && - iDelta > iDeltaSignal && - iDeltaPrev < iDeltaSignalPrev; - - // - bool isDeltaSwitchedToBearish = - isDeltaDown && - isDeltaSignalDown && - iDelta < iDeltaSignal && - iDeltaPrev > iDeltaSignalPrev; - - // - if (false && - (isDeltaSwitchedToBullish || - isDeltaSwitchedToBearish)) - { - // - iDir = isDeltaSwitchedToBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - iClr = - IsBullish(iDir) - ? clrAqua - : clrMagenta; - - // - iName = ToString(iDir) + "_Delta_" + ToFormatString(iTime); - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - iTime // - ); - if (has) - { - // - // Style Object ... - iObj.Color(iClr); - - // - // Store Object ... - mObjects.Add(iObj); - } - } - - // - // Volume Testing ... - - // - double iBullishVolumeSignal = bullishVolumeSignalBuffer[bar_index]; - double iBullishVolumeSignalPrev = bullishVolumeSignalBuffer[lastBarIndex]; - - // - bool isBullishVolumeSignalUp = iBullishVolumeSignal > iBullishVolumeSignalPrev; - bool isBullishVolumeSignalDown = iBullishVolumeSignal < iBullishVolumeSignalPrev; - - // - double iBearishVolumeSignal = bearishVolumeSignalBuffer[bar_index]; - double iBearishVolumeSignalPrev = bearishVolumeSignalBuffer[lastBarIndex]; - - // - bool isBearishVolumeSignalUp = iBearishVolumeSignal > iBearishVolumeSignalPrev; - bool isBearishVolumeSignalDown = iBearishVolumeSignal < iBearishVolumeSignalPrev; - - // - bool isVolumeSwitchdToBullish = - isBullishVolumeSignalUp && - !isBearishVolumeSignalUp && - iBullishVolumeSignal > iBearishVolumeSignal && - iBullishVolumeSignalPrev < iBearishVolumeSignalPrev; - - // - bool isVolumeSwitchdToBearish = - isBearishVolumeSignalUp && - !isBullishVolumeSignalUp && - iBearishVolumeSignal > iBullishVolumeSignal && - iBearishVolumeSignalPrev < iBullishVolumeSignalPrev; - - // - if (false && - (isVolumeSwitchdToBullish || - isVolumeSwitchdToBearish)) - { - // - iDir = isVolumeSwitchdToBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - iClr = - IsBullish(iDir) - ? clrAqua - : clrMagenta; - - // - iName = ToString(iDir) + "_Volume_" + ToFormatString(iTime); - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - iTime // - ); - if (has) - { - // - // Style Object ... - iObj.Color(iClr); - - // - // Store Object ... - mObjects.Add(iObj); - } - } - - // - // Signal Bar ... - - // - double iSignalOpen = openSignalBuffer[bar_index]; - double iSignalOpenPrev = openSignalBuffer[lastBarIndex]; - - // - double iSignalClose = closeSignalBuffer[bar_index]; - double iSignalClosePrev = closeSignalBuffer[lastBarIndex]; - - // - bool isSignalBarBullish = iSignalOpen < iSignalClose; - bool isSignalBarBullishPrev = iSignalOpenPrev < iSignalClosePrev; - - // - bool isSignalBarBearish = iSignalOpen > iSignalClose; - bool isSignalBarBearishPrev = iSignalOpenPrev > iSignalClosePrev; - - // - bool isSignalBarSwitchedToBullish = - isSignalBarBullish && - !isSignalBarBullishPrev; - - // - bool isSignalBarSwitchedToBearish = - isSignalBarBearish && - !isSignalBarBearishPrev; - - // - // HK Signal Bar ... - - // - double iHKSignalOpen = openHKSignalBuffer[bar_index]; - double iHKSignalOpenPrev = openHKSignalBuffer[lastBarIndex]; - - // - double iHKSignalClose = closeHKSignalBuffer[bar_index]; - double iHKSignalClosePrev = closeHKSignalBuffer[lastBarIndex]; - - // - bool isHKSignalBarBullish = iHKSignalOpen < iHKSignalClose; - bool isHKSignalBarBullishPrev = iHKSignalOpenPrev < iHKSignalClosePrev; - - // - bool isHKSignalBarBearish = iHKSignalOpen > iHKSignalClose; - bool isHKSignalBarBearishPrev = iHKSignalOpenPrev > iHKSignalClosePrev; - - // - bool isHKSignalBarSwitchedToBullish = - isHKSignalBarBullish && - !isHKSignalBarBullishPrev; - - // - bool isHKSignalBarSwitchedToBearish = - isHKSignalBarBearish && - !isHKSignalBarBearishPrev; - - // - // SAR ... - - // - double iSarState = sarStateBuffer[bar_index]; - double iSarStatePrev = sarStateBuffer[lastBarIndex]; - - // - bool isSarBullish = iSarState > 0; - bool isSarBullishPrev = iSarStatePrev > 0; - - // - bool isSarBearish = iSarState < 0; - bool isSarBearishPrev = iSarStatePrev < 0; - - // - bool isSarSwitchedToBullish = - isSarBullish && - !isSarBullishPrev; - - // - bool isSarSwitchedToBearish = - isSarBearish && - !isSarBearishPrev; - - // - // Full Testing Senario ... - - // - bool isBullish = - isSarSwitchedToBullish && - isDeltaSwitchedToBullish && - isVolumeSwitchdToBullish && - isSignalBarSwitchedToBullish && - isHKSignalBarSwitchedToBullish; - - // - bool isBearish = - isSarSwitchedToBearish && - isDeltaSwitchedToBearish && - isVolumeSwitchdToBearish && - isSignalBarSwitchedToBearish && - isHKSignalBarSwitchedToBearish; - - // - if (true && - (isBullish || - isBearish)) - { - // - iDir = isBullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - iClr = - IsBullish(iDir) - ? clrAqua - : clrMagenta; - - // - iName = ToString(iDir) + "_BSB_" + ToFormatString(iTime); - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - iTime // - ); - if (has) - { - // - // Style Object ... - iObj.Color(iClr); - - // - // Store Object ... - mObjects.Add(iObj); - } - } -} diff --git a/Documents/BKP/test.1.mq5 b/Documents/BKP/test.1.mq5 deleted file mode 100644 index 77dd77b9..00000000 --- a/Documents/BKP/test.1.mq5 +++ /dev/null @@ -1,181 +0,0 @@ -#property copyright "Your Name" -#property link "https://www.yourwebsite.com" -#property version "1.02" -#property indicator_chart_window -#property indicator_buffers 2 -#property indicator_plots 2 - -//--- Input parameters -input int atr_period = 14; // ATR Period -input double atr_threshold = 0.0005; // ATR Threshold for Consolidation (e.g., 0.0005 for EURUSD, 5.0 for XAUUSD) -input int range_period = 20; // Period to check price range -input double range_multiplier = 2.0; // Price range multiplier (relative to ATR) -input bool enable_alerts = true; // Enable breakout alerts -input bool draw_rectangles = true; // Draw rectangles for consolidation zones - -//--- Indicator buffers -double UpperBuffer[]; -double LowerBuffer[]; - -//--- Global variables -int atr_handle = INVALID_HANDLE; -int zone_count = 0; // For unique rectangle names - -//+------------------------------------------------------------------+ -//| Custom indicator initialization function | -//+------------------------------------------------------------------+ -int OnInit() -{ - //--- Set indicator buffers - SetIndexBuffer(0, UpperBuffer, INDICATOR_DATA); - SetIndexBuffer(1, LowerBuffer, INDICATOR_DATA); - PlotIndexSetString(0, PLOT_LABEL, "Upper Consolidation"); - PlotIndexSetString(1, PLOT_LABEL, "Lower Consolidation"); - PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_LINE); - PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_LINE); - PlotIndexSetInteger(0, PLOT_LINE_STYLE, STYLE_SOLID); - PlotIndexSetInteger(1, PLOT_LINE_STYLE, STYLE_SOLID); - PlotIndexSetInteger(0, PLOT_LINE_COLOR, clrRed); - PlotIndexSetInteger(1, PLOT_LINE_COLOR, clrBlue); - - //--- Create ATR handle - atr_handle = iATR(_Symbol, _Period, atr_period); - if(atr_handle == INVALID_HANDLE) - { - Print("Failed to create ATR handle, error: ", GetLastError()); - return(INIT_FAILED); - } - - //--- Check available bars - int available_bars = Bars(_Symbol, _Period); - if(available_bars < range_period + atr_period) - { - Print("Insufficient bars: ", available_bars, ", required: ", range_period + atr_period); - return(INIT_FAILED); - } - - //--- Log initialization - Print("Indicator initialized. Symbol: ", _Symbol, ", Timeframe: ", Period(), - ", ATR Period: ", atr_period, ", Range Period: ", range_period); - - return(INIT_SUCCEEDED); -} - -//+------------------------------------------------------------------+ -//| Custom indicator deinitialization function | -//+------------------------------------------------------------------+ -void OnDeinit(const int reason) -{ - if(atr_handle != INVALID_HANDLE) - IndicatorRelease(atr_handle); - ObjectsDeleteAll(0, "Consolidation_"); // Remove all rectangles - Print("Indicator deinitialized, reason: ", reason); -} - -//+------------------------------------------------------------------+ -//| Custom indicator iteration function | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[]) -{ - //--- Ensure enough bars - if(rates_total < range_period + atr_period) - { - Print("Not enough bars: ", rates_total, ", required: ", range_period + atr_period); - return(0); - } - - //--- Set arrays as series - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(time, true); - ArraySetAsSeries(UpperBuffer, true); - ArraySetAsSeries(LowerBuffer, true); - - //--- Calculate ATR - double atr[]; - ArraySetAsSeries(atr, true); - ArrayResize(atr, rates_total); - if(CopyBuffer(atr_handle, 0, 0, rates_total, atr) <= 0) - { - Print("Failed to copy ATR buffer, error: ", GetLastError()); - return(0); - } - - //--- Initialize buffers for first calculation - if(prev_calculated == 0) - { - ArrayInitialize(UpperBuffer, EMPTY_VALUE); - ArrayInitialize(LowerBuffer, EMPTY_VALUE); - } - - //--- Loop through bars - int start = prev_calculated == 0 ? range_period : MathMax(range_period, prev_calculated - 1); - for(int i = start; i < rates_total && !IsStopped(); i++) - { - //--- Calculate range over range_period - int max_idx = ArrayMaximum(high, i - range_period + 1, range_period); - int min_idx = ArrayMinimum(low, i - range_period + 1, range_period); - if(max_idx == -1 || min_idx == -1) - { - Print("Error: Invalid array index at bar ", i); - continue; - } - double max_high = high[max_idx]; - double min_low = low[min_idx]; - double price_range = max_high - min_low; - - //--- Log values for debugging - if(i == rates_total - 1) // Log only for the latest bar - { - Print("Bar ", i, ": ATR = ", DoubleToString(atr[i], _Digits), - ", Price Range = ", DoubleToString(price_range, _Digits), - ", Threshold = ", DoubleToString(atr_threshold, _Digits), - ", Range Limit = ", DoubleToString(atr[i] * range_multiplier, _Digits)); - } - - //--- Check for consolidation - if(atr[i] < atr_threshold && price_range < atr[i] * range_multiplier) - { - UpperBuffer[i] = max_high; - LowerBuffer[i] = min_low; - - //--- Draw rectangle for the consolidation zone - if(draw_rectangles && i >= range_period) - { - string obj_name = "Consolidation_" + IntegerToString(zone_count++) + "_" + TimeToString(time[i]); - ObjectCreate(0, obj_name, OBJ_RECTANGLE, 0, time[i], max_high, time[i - range_period + 1], min_low); - ObjectSetInteger(0, obj_name, OBJPROP_COLOR, clrRed); - ObjectSetInteger(0, obj_name, OBJPROP_STYLE, STYLE_SOLID); - ObjectSetInteger(0, obj_name, OBJPROP_WIDTH, 1); - ObjectSetInteger(0, obj_name, OBJPROP_FILL, false); - ObjectSetInteger(0, obj_name, OBJPROP_BACK, false); - } - - //--- Check for breakout (on latest bar only) - if(enable_alerts && i == rates_total - 1) - { - if(close[i] > UpperBuffer[i] && (i == 0 || close[i-1] <= UpperBuffer[i-1])) - Alert("Breakout Up at ", TimeToString(time[i]), ": Price = ", DoubleToString(close[i], _Digits)); - if(close[i] < LowerBuffer[i] && (i == 0 || close[i-1] >= LowerBuffer[i-1])) - Alert("Breakout Down at ", TimeToString(time[i]), ": Price = ", DoubleToString(close[i], _Digits)); - } - } - else - { - UpperBuffer[i] = EMPTY_VALUE; - LowerBuffer[i] = EMPTY_VALUE; - } - } - - return(rates_total); -} \ No newline at end of file diff --git a/Documents/BKP/test.mq5 b/Documents/BKP/test.mq5 deleted file mode 100644 index 4f4eed7e..00000000 --- a/Documents/BKP/test.mq5 +++ /dev/null @@ -1,137 +0,0 @@ -//+------------------------------------------------------------------+ -//| VPattern.mq5 | -//| Copyright 2023, MetaQuotes Software Corp. | -//| https://www.metaquotes.net/ | -//+------------------------------------------------------------------+ -#property copyright "Copyright 2023, MetaQuotes Software Corp." -#property link "https://www.metaquotes.net/" -#property version "1.00" -#property indicator_chart_window -#property indicator_buffers 4 -#property indicator_plots 2 -#property indicator_label1 "V Pattern Top" -#property indicator_type1 DRAW_ARROW -#property indicator_color1 clrGreen -#property indicator_width1 2 -#property indicator_label2 "V Pattern Bottom" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrRed -#property indicator_width2 2 - -//--- Input parameters -input int LookbackPeriod=20; // Bars to analyze for pattern -input double MinDeclinePercent=2.0; // Minimum decline percentage -input double MinRisePercent=2.0; // Minimum rise percentage -input bool ShowAlerts=true; // Show alert messages -input color ArrowUpColor=clrGreen; // Up arrow color -input color ArrowDownColor=clrRed; // Down arrow color - -//--- Indicator buffers -double VTopBuffer[]; -double VBottomBuffer[]; -double TempHighBuffer[]; -double TempLowBuffer[]; - -//+------------------------------------------------------------------+ -//| Custom indicator initialization function | -//+------------------------------------------------------------------+ -int OnInit() - { -//--- indicator buffers mapping - SetIndexBuffer(0, VTopBuffer, INDICATOR_DATA); - SetIndexBuffer(1, VBottomBuffer, INDICATOR_DATA); - SetIndexBuffer(2, TempHighBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(3, TempLowBuffer, INDICATOR_CALCULATIONS); - -//--- setting arrow codes - PlotIndexSetInteger(0, PLOT_ARROW, 233); // Up arrow - PlotIndexSetInteger(1, PLOT_ARROW, 234); // Down arrow - -//--- setting arrow colors - PlotIndexSetInteger(0, PLOT_LINE_COLOR, ArrowUpColor); - PlotIndexSetInteger(1, PLOT_LINE_COLOR, ArrowDownColor); - -//--- setting buffer values as EMPTY_VALUE - ArrayInitialize(VTopBuffer, EMPTY_VALUE); - ArrayInitialize(VBottomBuffer, EMPTY_VALUE); - -//--- name for DataWindow and indicator subwindow label - IndicatorSetString(INDICATOR_SHORTNAME, "V-Pattern Detector ("+string(LookbackPeriod)+")"); - - return(INIT_SUCCEEDED); - } -//+------------------------------------------------------------------+ -//| Custom indicator iteration function | -//+------------------------------------------------------------------+ -int OnCalculate(const int rates_total, - const int prev_calculated, - const datetime &time[], - const double &open[], - const double &high[], - const double &low[], - const double &close[], - const long &tick_volume[], - const long &volume[], - const int &spread[]) - { -//--- check for minimum bars required - if(rates_total < LookbackPeriod) - return(0); - -//--- start calculation from bar determined by prev_calculated - int start; - if(prev_calculated == 0) - start = LookbackPeriod; - else - start = prev_calculated - 1; - -//--- main calculation loop - for(int i=start; i= MinDeclinePercent && risePercent >= MinRisePercent) - { - // Check if the low is in the middle third of the lookback period - int lowPosition = lowestBar - (i-LookbackPeriod+1); - if(lowPosition > LookbackPeriod/3 && lowPosition < 2*LookbackPeriod/3) - { - // Mark the pattern on chart - VTopBuffer[highBeforeLow] = high[highBeforeLow]; - VBottomBuffer[lowestBar] = low[lowestBar]; - VTopBuffer[highAfterLow] = high[highAfterLow]; - - // Show alert if enabled - if(ShowAlerts && i == rates_total-1) - { - string alertText = StringFormat("V-Pattern detected! Decline: %.2f%%, Rise: %.2f%%", - declinePercent, risePercent); - Alert(alertText); - Comment(alertText); - } - } - } - } - - return(rates_total); - } -//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/Documents/BKP/tmp-1.mql4 b/Documents/BKP/tmp-1.mql4 deleted file mode 100644 index fc3bd654..00000000 --- a/Documents/BKP/tmp-1.mql4 +++ /dev/null @@ -1,770 +0,0 @@ - // hasTB && - // tb.IsBullish() && - // - // isPeakOverLast && - // isSarBullishStart - // && - // isTrendBullishStart && - // isADXBullishStart && - // && - // isSBarBullishStart - // && - // isHKSBarBullishStart - // - - - // - // hasTB && - // tb.IsBearish() && - // - // isValeUnderLast && - // isSarBearishStart - // && - // isTrendBearishStart && - // isADXBearishStart && - // && - // isSBarBearishStart - // && - // isHKSBarBearishStart - // - - - -bool DetectTriggerBlock( - XCPOIDrawer *drawer, - XCX121XCatbHelper *helper, - XCBarAnalyser *barAnalyser, - X121XCatbConditions &conditions, - XTriggerBlock &tb, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - tb.Clean(); - conditions.Clean(); - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 0); - - // - // Validate Args ... - result = helper != NULL; - if (!result) - { - return result; - } - - // - // Reading Market Conditions ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - tb.Clean(); - conditions.Clean(); - } - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - // Checking Conditions ... - - // - // Detect Bar Verifications ... - - // - ENUM_X_DIRECTION iDir; - - // - // Rejected ... - bool isRejected = - barAnalyser - .IsRejected( - conditions.bars[cIDX], - iDir // - ); - bool isBullishRejected = - isRejected && - IsBullish(iDir); - bool isBearishRejected = - isRejected && - IsBearish(iDir); - - // - // Engulfed ... - bool isEngulfed = - barAnalyser - .IsEngulfed( - conditions.bars[cIDX], - iDir // - ); - bool isBullishEngulfed = - isEngulfed && - IsBullish(iDir); - bool isBearishEngulfed = - isEngulfed && - IsBearish(iDir); - - // - // Momentum ... - bool isMomentum = - barAnalyser - .IsMomentum( - conditions.bars[cIDX], - iDir // - ); - bool isBullishMomentum = - isMomentum && - IsBullish(iDir); - bool isBearishMomentum = - isMomentum && - IsBearish(iDir); - - // - bool isBarBullishPressured = - isBullishRejected || - isBullishEngulfed || - isBullishMomentum; - - // - bool isBarBearishPressured = - isBearishRejected || - isBearishEngulfed || - isBearishMomentum; - - // - // Detect Indicator Base Start Directional Movement ... - - // - // SAR ... - - // - bool isSarBullishStart = - // - ( - // - // Current SAR is Directional ... - conditions.isSarBullish && - // - // Previous InDirectional Sar Exists ... - helper.lastSarBearish.IsValid() && - // - // Current Close is Over previous Sar ... - conditions.bars[cIDX].close > helper.lastSarBearish.after && - // - // Before Close is not Over previous Sar ... - conditions.bars[pIDX].close <= helper.lastSarBearish.after - // - ) - // - ; - - // - bool isSarBearishStart = - // - ( - // - // Current SAR is Directional ... - conditions.isSarBearish && - // - // Previous InDirectional Sar Exists ... - helper.lastSarBullish.IsValid() && - // - // Current Close is Under previous ... - conditions.bars[cIDX].close < helper.lastSarBullish.after && - // - // Before Close is not Under previous ... - conditions.bars[pIDX].close >= helper.lastSarBullish.after - // - ) - // - ; - - // - // TREND ... - - // - bool isTrendBullishStart = - // - ( - // - // Current Trend is Directional ... - conditions.isTrendBullish && - // - // Previous InDirectiona; Trend Exists ... - helper.lastTrendBearish.IsValid() && - // - // Current Close is Over previous ... - conditions.bars[cIDX].close > helper.lastTrendBearish.after && - // - // Before close is not Over previous ... - conditions.bars[pIDX].close <= helper.lastTrendBearish.after - // - ) - // - ; - - // - bool isTrendBearishStart = - // - ( - // - // Current Trend is Directional ... - conditions.isTrendBearish && - // - // Previous InDirectiona; Trend Exists ... - helper.lastTrendBullish.IsValid() && - // - // Current Close is Under previous ... - conditions.bars[cIDX].close < helper.lastTrendBullish.after && - // - // Before close is not Under previous ... - conditions.bars[pIDX].close >= helper.lastTrendBullish.after - // - ) - // - ; - - // - // ADX ... - - // - bool isADXBullishStart = - // - ( - // - // ADX Value is Switched to Strong ... - conditions.adxBuffer[cIDX] > conditions.adxThreshold && - conditions.adxBuffer[pIDX] <= conditions.adxThreshold && - // - // ADX must Up ... - conditions.adxBuffer[cIDX] > conditions.adxBuffer[pIDX] && - // - // ADX +DI is Bigger than -DI ... - conditions.adxpBuffer[cIDX] > conditions.adxnBuffer[cIDX] && - // - // ADX +DI is Up ... - conditions.adxpBuffer[cIDX] > conditions.adxpBuffer[pIDX] - // - ) - // - ; - - // - bool isADXBearishStart = - // - ( - // - // ADX Value is Switched to Strong ... - conditions.adxBuffer[cIDX] > conditions.adxThreshold && - conditions.adxBuffer[pIDX] <= conditions.adxThreshold && - // - // ADX must Up ... - conditions.adxBuffer[cIDX] > conditions.adxBuffer[pIDX] && - // - // ADX -DI is Bigger than +DI ... - conditions.adxnBuffer[cIDX] > conditions.adxpBuffer[cIDX] && - // - // ADX -DI is Up ... - conditions.adxnBuffer[cIDX] > conditions.adxnBuffer[pIDX] - // - ) - // - ; - - // - // DELTA ... - - // - bool isDeltaBullishStart = - // - // Check State ... - ( - // - // Delta is Up ... - conditions.deltaBuffer[cIDX] > conditions.deltaBuffer[pIDX] && - // - // Delta Signal is Up ... - conditions.deltaSignalBuffer[cIDX] > conditions.deltaSignalBuffer[pIDX] && - // - // Delta Crossed Over Delta Signal ... - conditions.deltaBuffer[cIDX] > conditions.deltaSignalBuffer[cIDX] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastDeltaBearish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close > helper.lastDeltaBearish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close <= helper.lastDeltaBearish.after - // - ; - - // - bool isDeltaBearishStart = - // - // Check State ... - ( - // - // Delta is Down ... - conditions.deltaBuffer[cIDX] < conditions.deltaBuffer[pIDX] && - // - // Delta Signal is Down ... - conditions.deltaSignalBuffer[cIDX] < conditions.deltaSignalBuffer[pIDX] && - // - // Delta Crossed Under Delta Signal ... - conditions.deltaBuffer[cIDX] < conditions.deltaSignalBuffer[cIDX] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastDeltaBullish.IsValid() && - // - // Current Close is Under last ... - conditions.bars[cIDX].close < helper.lastDeltaBullish.after && - // - // Before Close is not Under last ... - conditions.bars[pIDX].close >= helper.lastDeltaBullish.after - // - ; - - // - // VOLUME ... - - // - bool isVolumeBullishStart = - // - ( - // - // - // Volume is Up ... - conditions.bullishVolumeBuffer[1] > conditions.bullishVolumeBuffer[2] && - // - // Volume Signal is Up ... - conditions.bullishVolumeSignalBuffer[1] > conditions.bullishVolumeSignalBuffer[2] && - // - // Volume Signals Crossed Over ... - conditions.bullishVolumeSignalBuffer[1] > conditions.bearishVolumeSignalBuffer[1] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastVolumeBearish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close > helper.lastVolumeBearish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close <= helper.lastVolumeBearish.after - // - ; - - // - bool isVolumeBearishStart = - // - ( - // - // - // Volume is Up ... - conditions.bearishVolumeBuffer[1] > conditions.bearishVolumeBuffer[2] && - // - // Volume Signal is Up ... - conditions.bearishVolumeSignalBuffer[1] > conditions.bearishVolumeSignalBuffer[2] && - // - // Volume Signals Crossed Over ... - conditions.bearishVolumeSignalBuffer[1] > conditions.bullishVolumeSignalBuffer[1] - // - ) - // - && - // - // Check Last InDirectional Exists ... - helper.lastVolumeBullish.IsValid() && - // - // Current Close is Over last ... - conditions.bars[cIDX].close < helper.lastVolumeBullish.after && - // - // Before Close is not Over last ... - conditions.bars[pIDX].close >= helper.lastVolumeBullish.after - // - ; - - // - // SIGNAL Bar ... - - // - bool isSBarBullishStart = - // - ( - // - // Check Direction ... - conditions.isSBarBullish && - // - // Previous InDirectional Exists ... - helper.lastSignalBarBearish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.sBarCloseBuffer[cIDX] > helper.lastSignalBarBearish.after && - // - // Prev Signal Bar not close over prev ... - conditions.sBarCloseBuffer[pIDX] <= helper.lastSignalBarBearish.after - // - ) - // - ; - - // - bool isSBarBearishStart = - // - ( - // - // Check Direction ... - conditions.isSBarBearish && - // - // Previous InDirectional Exists ... - helper.lastSignalBarBullish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.sBarCloseBuffer[cIDX] < helper.lastSignalBarBullish.after && - // - // Prev Signal Bar not close over prev ... - conditions.sBarCloseBuffer[pIDX] >= helper.lastSignalBarBullish.after - // - ) - // - ; - - // - // HKSIGNAL Bar ... - - // - bool isHKSBarBullishStart = - // - ( - // - // Check Direction ... - conditions.isHKSBarBullish && - // - // Previous InDirectional Exists ... - helper.lastHKSignalBarBearish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.hkSBarCloseBuffer[cIDX] > helper.lastHKSignalBarBearish.after && - // - // Prev Signal Bar not close over prev ... - conditions.hkSBarCloseBuffer[pIDX] <= helper.lastHKSignalBarBearish.after - // - ) - // - ; - - // - bool isHKSBarBearishStart = - // - ( - // - // Check Direction ... - conditions.isHKSBarBearish && - // - // Previous InDirectional Exists ... - helper.lastHKSignalBarBullish.IsValid() && - // - // Current Signal Bar close over prev ... - conditions.hkSBarCloseBuffer[cIDX] < helper.lastHKSignalBarBullish.after && - // - // Prev Signal Bar not close over prev ... - conditions.hkSBarCloseBuffer[pIDX] >= helper.lastHKSignalBarBullish.after - // - ) - // - ; - - // - // Check for Vale and Peak ... - - // - bool isPeakOverLast = - // - (conditions.peakBuffer[cIDX] > conditions.peakBuffer[pIDX] && - conditions.peakBuffer[pIDX] <= conditions.peakBuffer[p2IDX] && - conditions.bars[cIDX].close > conditions.peakBuffer[pIDX]) - // - || - // - (conditions.peakBuffer[pIDX] > conditions.peakBuffer[p2IDX] && - conditions.peakBuffer[p2IDX] <= conditions.peakBuffer[p3IDX] && - conditions.bars[pIDX].close > conditions.peakBuffer[p2IDX]) - // - || - // - (conditions.peakBuffer[p2IDX] > conditions.peakBuffer[p3IDX] && - conditions.peakBuffer[p3IDX] <= conditions.peakBuffer[p4IDX] && - conditions.bars[p2IDX].close > conditions.peakBuffer[p3IDX]) - // - ; - - // - bool isValeUnderLast = - // - (conditions.valeBuffer[cIDX] < conditions.valeBuffer[pIDX] && - conditions.valeBuffer[pIDX] >= conditions.valeBuffer[p2IDX] && - conditions.bars[cIDX].close < conditions.valeBuffer[pIDX]) - // - || - // - (conditions.valeBuffer[pIDX] < conditions.valeBuffer[p2IDX] && - conditions.valeBuffer[p2IDX] >= conditions.valeBuffer[p3IDX] && - conditions.bars[pIDX].close < conditions.valeBuffer[p2IDX]) - // - || - // - (conditions.valeBuffer[p2IDX] < conditions.valeBuffer[p3IDX] && - conditions.valeBuffer[p3IDX] >= conditions.valeBuffer[p4IDX] && - conditions.bars[p2IDX].close < conditions.valeBuffer[p3IDX]) - // - ; - - // - // if (isValeUnderLast) - // { - // Print("SALAM"); - // } - - // - // Try to Summarize Conditions ... - - // - bool isBullishPassed = - // - (isPeakOverLast && - isDeltaBullishStart && - isVolumeBullishStart && - isBarBullishPressured) - // - ; - - // - bool isBearishPassed = - (isValeUnderLast && - isDeltaBearishStart && - isVolumeBearishStart && - isBarBearishPressured) - // - ; - - // - // Try to Detect Trigger Block ... - bool hasTB = false; - int tbLoopback = 100; - X121XCatbInputs mInputs = helper.GetInputs(); - for (int i = barIndex; i < barIndex + tbLoopback; i++) - { - // - // Update Helper ... - helper.Update(i); - - // - // Check TB ... - hasTB = DetectTriggerBlock( - // - conditions.symbol, - conditions.period, - // - tb, - // - drawer, - barAnalyser, - // - // Required Buffers ... - helper.atrBuffer, - helper.rsiBuffer, - helper.adxBuffer, - helper.adxpBuffer, - helper.adxnBuffer, - helper.peakBuffer, - helper.valeBuffer, - helper.deltaBuffer, - helper.sarBuffer, - helper.sarStateBuffer, - helper.trendBuffer, - helper.trendStateBuffer, - helper.atrUpperBuffer, - helper.atrLowerBuffer, - helper.sBarOpenBuffer, - helper.sBarCloseBuffer, - helper.hkSBarOpenBuffer, - helper.hkSBarCloseBuffer, - helper.peakGoldenBuffer, - helper.valeGoldenBuffer, - helper.deltaSignalBuffer, - helper.bullishVolumeSignalBuffer, - helper.bearishVolumeSignalBuffer, - // - i + 1, - // - // Signalling ... - mInputs.signalR2R, - mInputs.slAtrMultiplier, - // - // Configs ... - mInputs.rsiOBLevel, - mInputs.rsiOSLevel, - mInputs.adxThreshold, - // - // Validators ... - mInputs.forceObBarType, - mInputs.forceOBFVGBarType, - mInputs.forceHasSwing, - mInputs.forceHasFLiquidity, - mInputs.forceHasRLiquidity, - mInputs.validateGapSequence, - mInputs.validateBlockEdgeBreakout, - // - // Filters ... - mInputs.filterBasedOnPV, - mInputs.filterBasedOnSar, - mInputs.filterBasedOnRSI, - mInputs.filterBasedOnADX, - mInputs.filterBasedOnATR, - mInputs.filterBasedOnTrend, - mInputs.filterBasedOnDelta, - mInputs.filterBasedOnVolume, - mInputs.filterBasedOnSignalBar, - mInputs.filterBasedOnHKSignalBar // - ); - - // - // Checking Trigger Block Validation ... - hasTB = - // - hasTB && - // - ( - // - (isBullishPassed && - tb.IsBullish()) - // - || - // - (isBearishPassed && - tb.IsBearish()) - // - ); - if (hasTB) - { - // - break; - } - - // - tb.Clean(); - } - - // - // isBullishPassed = false; - // isBearishPassed = false; - - // - // Draw Line for Detect Conditions States on Chart ... - if (hasTB && (isBullishPassed || - isBearishPassed)) - { - // - color iColor = isBullishPassed - ? clrAqua - : clrMagenta; - - // - datetime iTime = conditions.bars[cIDX].time; - - // - string iName = "VL_" + ToFormatString(iTime); - - // - long chartID = drawer.ChartIdentification(); - int subWindow = drawer.SubWindowIdentification(); - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - bool isDrawn = iObj.Create( - chartID, - iName, - subWindow, - iTime // - ); - if (isDrawn) - { - // - iObj.Color(iColor); - } - - // - CArrayObj *tbObjects = new CArrayObj(); - DrawTriggerBlock( - tb, - drawer, - tbObjects, - conditions.bars[0].time // - ); - - // - tb.Clean(); - } - - // - // Summarizing result ... - - // - result = (isBullishPassed || - isBearishPassed); - - // - // Cleanup Resources ... - - // - if (!result) - { - // - tb.Clean(); - conditions.Clean(); - } - - // - return result; -} - - - // - // has = DetectTriggerBlock( - // eaDrawer, - // eaHelper, - // eaBarAnalyser, - // iConditions, - // iTB, - // barIndex, - // 10 // - // ); diff --git a/Documents/BKP/tmp.guards.mq5 b/Documents/BKP/tmp.guards.mq5 deleted file mode 100644 index 8bcb4212..00000000 --- a/Documents/BKP/tmp.guards.mq5 +++ /dev/null @@ -1,1167 +0,0 @@ - // - // Guards ... - - // - // Do All Provided Guards ... - void DoGuards(XGuard &guards[]) - { - // - int guardsCount = ArraySize(guards); - if (guardsCount <= 0) - { - return; - } - - // - for (int i = 0; i < guardsCount; i++) - { - // - XGuard iGuard = guards[i]; - - // - switch (iGuard.action) - { - // - // Hedge In Profit Specified Positions ... - case X_GUARD_ACTION_HEDGE: - HandleGuardHedgeAction( - iGuard.provider, - iGuard.symbol, - iGuard.type, - iGuard.period); - break; - - // - // Trail Stop Loss in Specified Positions ... - case X_GUARD_ACTION_TRAIL_STOP: - HandleGuardTrailingStopAction( - iGuard.provider, - iGuard.symbol, - iGuard.type, - iGuard.period, - iGuard.dblPayLoad); - break; - - // - // Force Close Specified Positions ... - case X_GUARD_ACTION_FORCE_CLOSE: - HandleGuardForceCloseAction( - iGuard.provider, - iGuard.symbol, - iGuard.type, - iGuard.period); - break; - - // - // Generate and Place Support Signals ... - case X_GUARD_ACTION_ADD_SUPPORT_SIGNAL: - HandleGuardAddSupportPositionAction( - iGuard.provider, - iGuard.symbol, - iGuard.type, - iGuard.period); - break; - - // - // Delete All Placed Pending Orders ... - case X_GUARD_ACTION_CANCEL_PENDING_ORDERS: - HandleGuardCancelPendingOrdersAction( - iGuard.provider, - iGuard.symbol, - iGuard.type, - iGuard.period); - break; - } - } - } - - // - // Close All Specified Provider's Positions in Profit Summary ... - void HandleGuardHedgeAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - double minProfitForHedging = 1 // Specified Profit for Hedge - ) - { - // - XPosition positions[]; - int positionsCount = mTrader - .GetPositions( - positions, - symbol, - provider, - period, - type - // - ); - if (positionsCount <= 1) - { - return; - } - - // - double profit = CalculatePositionsProfit(positions); - double requiredProfit = CalculateRequiredProfitForHedge(positions); - - // - bool isReadyForHedge = profit >= requiredProfit; - if (!isReadyForHedge) - { - return; - } - - // - string comment = "Guard Hedge " + provider; - int closed = mTrader.Close( - positions, - comment - // - ); - if (closed > 0) - { - // - string message = "Guard Hedge " + provider + "'s Positions on Profit: " + ToString(profit); - - // - mAlert.Alert(message); - } - } - - // - // Close Max In Profit Trade Guard Action ... - void HandleGuardCloseInProfitAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method - ) - { - // - XPosition positions[]; - int positionsCount = mTrader - .GetInProfitPositions( - positions, - symbol, - provider, - period, - type, - method - // - ); - if (positionsCount <= 0) - { - return; - } - - // - string comment = "Close InProfit ..."; - mTrader.Close( - positions, - comment - // - ); - - // - string message = "Guard Close (" + ToString(positionsCount) + ") Postion(s) In Profit ..."; - - // - mAlert.Alert(message); - } - - // - // Close Max In Drawdown Trade Guard Action ... - void HandleGuardCloseInDrawdownAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method - ) - { - // - XPosition positions[]; - int positionsCount = mTrader - .GetInDrawdownPositions( - positions, - symbol, - provider, - period, - type, - method - // - ); - if (positionsCount <= 0) - { - return; - } - - // - string comment = "Close InDrawdown ..."; - mTrader.Close( - positions, - comment - // - ); - - // - string message = "Guard Close (" + ToString(positionsCount) + ") Position(s) In Drawdown ..."; - - // - mAlert.Alert(message); - } - - // - // Force Close Specified Set Of Position ... - void HandleGuardForceCloseAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - ulong ticket = 0 // Specific Ticket - ) - { - // - string comment = ""; - - // - // Close All Positions ... - if (ticket == 0) - { - // - XPosition positions[]; - int positionsCount = mTrader.GetPositions( - positions, - symbol, - provider, - period, - type - // - ); - if (positionsCount <= 0) - { - return; - } - - // - comment = provider + " Force Close Guard ..."; - - // - mTrader.Close( - positions, - comment - // - ); - } - // - // Close Specific Position ... - else - { - // - XPosition position; - bool hasPosition = mTrader - .GetPosition( - ticket, - position - // - ); - - // - if (hasPosition) - { - // - comment = provider + "(" + ToString(ticket) + ")" + " Force Close Guard ..."; - - // - mTrader.Close( - ticket, - comment - // - ); - } - } - - // - if (IsValid(comment)) - { - mAlert.Alert(comment); - } - } - - // - // Trailing Specified Set Of Positions Stop Losses ... - void HandleGuardTrailingStopAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - double sl // Desired SL Value ... - ) - { - // - if (sl <= 0) - { - return; - } - - // - NormalizePrice( - sl, - symbol - // - ); - - // - XPosition positions[]; - int positionsCount = mTrader - .GetPositions( - positions, - symbol, - provider, - period, - type - // - ); - if (positionsCount <= 0) - { - return; - } - - // - int modified = 0; - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - string comment = PrepareSLTrailTag(iPosition.comment); - - // - if (iPosition.sl == sl) - { - continue; - } - - // - bool isModified = mTrader.Modify( - iPosition.ticket, - sl, - iPosition.tp, - comment); - if (isModified) - { - modified++; - } - } - - // - if (modified > 0) - { - // - string message = "(" + ToString(modified) + ") Position's Stop Trailed Successfully ..."; - - // - mAlert.Alert(message); - } - } - - // - // Add Support Signal for Specified Positions ... - void HandleGuardAddSupportPositionAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period // Specified Time Frame - ) - { - // - XSignal support; - bool hasSupport = RequestForSupport( - support, - provider, - symbol, - type, - period - // - ); - - // - if (!hasSupport || !support.IsValid()) - { - return; - } - - // - // TODO: May be need to add Support Tag to comments ... - - // - ENUM_X_SIGNAL_EXECUTION_RESULT reason = NULL; - bool isExecuted = mTrader.ExecuteSignal( - support, - reason); - - // - string comment = NULL; - if (!isExecuted) - { - comment = "Support Execution Failed doue " + ToString(reason); - } - else - { - comment = "Guard Support Signal Executed Successfully ..."; - } - - // - if (IsValid(comment)) - { - mAlert.Alert(comment); - } - } - - // - // Cancel all Placed Orders ... - void HandleGuardCancelPendingOrdersAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_POSITION_TYPE type, // Trading Type - ENUM_TIMEFRAMES period // Specified Time Frame - ) - { - // - XOrder orders[]; - int ordersCount = mTrader.GetOrders( - orders, - symbol, - provider, - period, - ToOrderType(type), - ORDER_STATE_PLACED, - true // Filter by Magic ... - // - ); - if (ordersCount <= 0) - { - return; - } - - // - int canceledOrdersCount = mTrader.CancelOrders(orders); - - // - if (canceledOrdersCount > 0) - { - // - string message = "Guard Cancel (" + ToString(canceledOrdersCount) + ") Pending Orders ..."; - - // - mAlert.Alert(message); - } - } - -////////////////////////////////////////////////////////////////// - - /** - * Handle Guard Actions ... - * - * @param guards: X121SMCGuard instance Collection ... - */ - void HandleGuards(X121SMCGuard &guards[]) - { - // - int count = ArraySize(guards); - if (!IsValidSize(guards)) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - X121SMCGuard iGuard = guards[i]; - - // - if (!iGuard.IsValid()) - { - continue; - } - - // - // Here we Have to Handle Guard Actions ... - - // - // Close ... - bool canClose = - NotEmpty(iGuard.ticket) && - iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE; - - // - // Close All ... - bool canCloseAll = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_ALL; - - // - // Close Longs ... - bool canCloseLongs = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_LONGS; - - // - // Close Shorts ... - bool canCloseShorts = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_SHORTS; - - // - // Partial Close ... - bool canPartialClose = - NotEmpty(iGuard.ticket) && - iGuard.volumeMultiplier > 0 && - iGuard.action == X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE; - - // - // Trail Stop ... - bool canTrailStop = - iGuard.sl > 0 && - NotEmpty(iGuard.ticket) && - iGuard.action == X_121_SMC_GUARD_ACTION_TRAIL_STOP; - - // - // Trail Target ... - bool canTrailTarget = - iGuard.tp > 0 && - NotEmpty(iGuard.ticket) && - iGuard.action == X_121_SMC_GUARD_ACTION_TRAIL_TARGET; - - // - // Hedge ... - bool canHedge = iGuard.action == X_121_SMC_GUARD_ACTION_HEDGE; - - // - // Check is Guard Valid ... - bool isValidGuardAction = - canHedge || - canClose || - canCloseAll || - canTrailStop || - canCloseLongs || - canTrailTarget || - canCloseShorts || - canPartialClose; - if (!isValidGuardAction) - { - continue; - } - - // - // Now we Sure to Have a Valid Guard ... - // Start to o Guard Actions ... - - // - // Close All ... - if (canCloseAll) - { - // - XPosition positions[]; - int positionsCount = - mTrader - .GetPositions( - positions, // Result ... - iGuard.symbol, - iGuard.provider, - NULL, // Period ... - X_POSITION_TYPE_ALL, // All Types ... - true // Filter by Magic ... - ); - if (IsValidSize(positionsCount)) - { - // - string comment = "Guard Close All ..."; - string message = "Guard Close All (" + ToString(positionsCount) + ") Positions Successfully ..."; - int forceClosed = mTradeHandler.ForceClose( - positions, - comment, - message // - ); - - // - if (forceClosed) - { - RestEA(120 * 60); - } - } - } - - // - // Close Longs ... - if (canCloseLongs) - { - // - XPosition longPositions[]; - XPosition shortPositions[]; - mTrader - .GetPositions( - longPositions, // Result ... - shortPositions, // Result ... - iGuard.symbol, - iGuard.provider, - NULL, // Period ... - true // Filter by Magic ... - ); - - // - int longPositionsCount = ArraySize(longPositions); - bool hasLongPositions = IsValidSize(longPositionsCount); - - // - int shortPositionsCount = ArraySize(shortPositions); - bool hasShortPositions = IsValidSize(shortPositionsCount); - - // - if (hasLongPositions) - { - // - string comment = "Guard Close Longs ..."; - string message = "Guard Close (" + ToString(longPositionsCount) + ") Long Positions Successfully ..."; - bool isClosed = mTradeHandler.ForceClose( - longPositions, - comment, - message // - ); - - // - if (isClosed) - { - RestEA(120 * 60); - } - } - } - - // - // Close Shorts ... - if (canCloseShorts) - { - // - XPosition longPositions[]; - XPosition shortPositions[]; - mTrader - .GetPositions( - longPositions, // Result ... - shortPositions, // Result ... - iGuard.symbol, - iGuard.provider, - NULL, // Period ... - true // Filter by Magic ... - ); - - // - int longPositionsCount = ArraySize(longPositions); - bool hasLongPositions = IsValidSize(longPositionsCount); - - // - int shortPositionsCount = ArraySize(shortPositions); - bool hasShortPositions = IsValidSize(shortPositionsCount); - - // - if (hasShortPositions) - { - // - string comment = "Guard Close Shorts ..."; - string message = "Guard Close (" + ToString(shortPositionsCount) + ") Short Positions Successfully ..."; - bool isClosed = mTradeHandler.ForceClose( - shortPositions, - comment, - message // - ); - - // - if (isClosed) - { - RestEA(120 * 60); - } - } - } - - // - // Close ... - if (canClose) - { - // - XPosition iPosition; - bool hasPosition = mTrader.GetPosition( - iGuard.ticket, - iPosition // - ); - - // - bool isLong = IsLong(iPosition.type); - - // - if (hasPosition) - { - // - XPosition positions[]; - AddRef( - iPosition, - positions // - ); - - // - string comment = "Guard Close ..."; - string message = "Guard Close " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Successfully ..."; - bool isClosed = mTradeHandler.ForceClose( - positions, - comment, - message // - ); - - // - if (isClosed) - { - RestEA(120 * 60); - } - } - } - - // - // Partial Close ... - if (canPartialClose) - { - // - XPosition iPosition; - bool hasPosition = mTrader.GetPosition( - iGuard.ticket, - iPosition // - ); - - // - bool isLong = IsLong(iPosition.type); - - // - if (hasPosition) - { - // - // Normalize Volume Multiplier ... - double vMult = iGuard.volumeMultiplier; - if (vMult > 0.5) - { - vMult = 0.5; - } - if (vMult < 0) - { - vMult = 0.5; - } - - // - // Calculate and Normalize Volume ... - double volume = iPosition.volume * iGuard.volumeMultiplier; - volume = NormalizeVolume( - volume, - iPosition.symbol // - ); - - // - string comment = "Guard Partially Closed: " + ToString(volume) + " ..."; - string message = "Guard Partially Closed " + (isLong ? "Long" : "Short") + ": " + ToString(volume) + " Successfully ..."; - bool isModified = mTrader.ClosePartial( - iPosition.ticket, - volume, - comment // - ); - if (isModified) - { - // - mTradeHandler.Alert(message); - - // - if (volume == iPosition.volume) - { - // - mTradeHandler.Finish( - iPosition.ticket, - iPosition, - comment // - ); - - // - RestEA(120 * 60); - } - } - } - } - - // - // Hedge ... - if (canHedge) - { - // - XPosition positions[]; - int positionsCount = - mTrader - .GetPositions( - positions, // Result ... - iGuard.symbol, - iGuard.provider, - NULL, // Period ... - X_POSITION_TYPE_ALL, // All Types ... - true // Filter by Magic ... - ); - if (IsValidSize(positionsCount)) - { - // - int longs = 0; - double longProfits = 0; - double longVolumes = 0; - - // - int shorts = 0; - double shortProfits = 0; - double shortVolumes = 0; - CountPositions( - positions, - longs, - longProfits, - longVolumes, - shorts, - shortProfits, - shortVolumes // - ); - - // - int count = longs + shorts; - double profits = longProfits + shortProfits; - double volumes = longVolumes + shortVolumes; - - // - bool canDoHedge = - count > 0 && - profits > 0 && - volumes > 0; - if (canDoHedge) - { - // - string comment = "Guard Hedge ..."; - string message = "Guard Hedge (" + ToString(count) + ") Positions by: (" + ToString(profits) + ") Successfully ..."; - bool isClosed = mTradeHandler.ForceClose( - positions, - comment, - message // - ); - - // - if (isClosed) - { - RestEA(120 * 60); - } - } - } - } - - // - // Trail Stop ... - if (canTrailStop) - { - // - XPosition iPosition; - bool hasPosition = mTrader.GetPosition( - iGuard.ticket, - iPosition // - ); - - // - bool isLong = IsLong(iPosition.type); - - // - bool canDoTrail = - hasPosition && - iPosition.profit > 0 && - isLong - ? iPosition.price > iGuard.sl && - (iPosition.sl == 0 || - iPosition.sl < iGuard.sl) - : iPosition.price < iGuard.sl && - (iPosition.sl == 0 || - iPosition.sl > iGuard.sl); - if (canDoTrail) - { - // - string comment = "Guard Trail Stop ..."; - string message = "Guard Trail " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Stop Successfully ..."; - bool isModified = mTrader.Modify( - iPosition.ticket, - iGuard.sl, - iPosition.tp, - comment // - ); - if (isModified) - { - mTradeHandler.Alert(message); - } - } - } - - // - // Trail Target ... - if (canTrailTarget) - { - // - XPosition iPosition; - bool hasPosition = mTrader.GetPosition( - iGuard.ticket, - iPosition // - ); - - // - bool isLong = IsLong(iPosition.type); - - // - bool canDoTrail = - hasPosition && - iGuard.tp != iPosition.tp && - isLong - ? iGuard.tp > iPosition.price - : iGuard.tp < iPosition.price; - if (canDoTrail) - { - // - string comment = "Guard Trail Target ..."; - string message = "Guard Trail " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Target Successfully ..."; - bool isModified = mTrader.Modify( - iPosition.ticket, - iPosition.sl, - iGuard.tp, - comment // - ); - if (isModified) - { - mTradeHandler.Alert(message); - } - } - } - } - - // - Clean(guards); - ArrayFree(guards); - } - -////////////////////////////////////////////////////////////////// - - - // // - // eaTB.Clean(); - // eaSignal.Clean(); - // eaConditions.Clean(); - // eaCatbConditions.Clean(); - - // // - // bool has = false; - // int barIndex = 0; - // int cBarIndex = 0; - - // // - // // Check Bar Processing ... - // if (!eaBarTraker.CanProcessBar()) - // { - // return; - // } - - // // - // eaHelper.Check(barIndex); - - // // - // // Reading Required Bars ... - // XOHCL zBar; - // XOHCL cBar; - // has = zBar.Init( - // _Symbol, - // _Period, - // barIndex // - // ); - // has = - // has && - // zBar.GetPreviousBar(cBar); - // if (!has) - // { - // // - // zBar.Clean(); - // cBar.Clean(); - - // // - // return; - // } - - // // - // cBarIndex = barIndex + 1; - - // // - // // Update All Required Buffers ... - // eaHelper.Update(cBarIndex); - - // // - // // Check Trigger Block Detected or Not ... - // if (tradeUsingTriggerBlock) - // { - // // - // // Trigger Block Detection ... - // has = DetectTriggerBlock1( - // eaHelper, - // eaBarAnalyser, - // eaTB, - // eaCatbConditions, - // eaValidations, - // eaFilters, - // barIndex, - // 10 // Loopback ... - // ); - - // // - // if (has) - // { - // // - // // Wait for Next Bar for anything ... - // eaBarTraker.Waits(); - - // // - // // Prepare Target ... - // double targets[]; - // for (int i = 1; i <= eaSignalR2R; i++) - // { - // // - // Add( - // (double)i, - // targets // - // ); - // } - - // // - // // Calculate SL Additions ... - // double iATR = 0; - // if (barIndex > 0 && - // barIndex < ArraySize(eaHelper.atrBuffer)) - // { - // iATR = eaHelper.atrBuffer[barIndex]; - // } - // double slAdditional = eaSLAtrMultiplier * iATR; - - // // - // // Preparing Signal ... - // has = ToSignal( - // eaTB.trigger, - // eaTB.signal, - // targets, - // slAdditional // - // ); - - // // - // // Draw Trigger Block ... - // DrawTriggerBlock( - // eaTB, - // eaDrawer, - // eaObjects, - // NULL // - // ); - - // // - // // Attach Signal ... - // eaSignal = eaTB.signal; - - // // - // // Check Signal Type ... - // bool isLong = IsLong(eaSignal.type); - - // // - // // Update Entry ... - // eaSignal.entry = GetEntry( - // eaSignal.symbol, - // eaSignal.type // - // ); - - // // - // // Update Signal Targets ... - // UpdateSignalTargets(eaSignal); - - // // - // // Handle Volume Management ... - // double iVolume = eaVolume.CalculateVolume(eaSignal); - // if (iVolume > X_MIN_VOLUME && - // iVolume != eaSignal.volume) - // { - // eaSignal.volume = iVolume; - // } - - // // - // eaConditions.sl = eaSignal.sl; - // eaConditions.tp = eaSignal.tp; - // eaConditions.pivot = eaSignal.sl; - // eaConditions.time = eaSignal.time; - // eaConditions.reward = eaSignalR2R; - // eaConditions.point = eaSignal.entry; - // eaConditions.entry = eaSignal.entry; - // eaConditions.symbol = eaSignal.symbol; - // eaConditions.period = eaSignal.period; - // eaConditions.setupTime = eaSignal.time; - // eaConditions.triggerTime = eaSignal.time; - // eaConditions.decisionZone = eaTB.trigger; - // eaConditions.provider = eaSignal.provider; - // eaConditions.conditions = eaCatbConditions; - // eaConditions.type = ToPositionType(eaSignal.type); - // eaConditions.dir = - // isLong - // ? X_DIRECTION_BULLISH - // : X_DIRECTION_BEARISH; - // Copy( - // eaSignal.targets, - // eaConditions.targets // - // ); - // eaSignal.conditions = - // eaCatbConditions - // .GenerateSummary( - // false, // Commons ... - // true, // Conditions ... - // true, // Scores ... - // false // Ignore Falses ... - // ); - - // // - // // Execute Signal ... - // has = eaTradeManager.Execute( - // eaSignal, - // eaConditions // - // ); - // } - - // // - // eaTB.Clean(); - // } - - // // - // // Trade Using Market Conditions ... - // if (tradeUsingMarketConditions1) - // { - // // - // XBoxZone signalZone; - // X121XCatbConditions conditions; - // has = DetectSignalZone( - // eaDrawer, - // eaHelper, - // eaBarAnalyser, - // signalZone, - // conditions, - // barIndex // - // ); - // if (has) - // { - // // - // // Convert Box to Signal ... - // } - // } - - // // - // // Cleanup Resources ... - - // // - // zBar.Clean(); - // cBar.Clean(); - // eaTB.Clean(); - // eaSignal.Clean(); - // eaConditions.Clean(); - // eaCatbConditions.Clean(); diff --git a/Documents/BKP/x-signal.tmp.mq5 b/Documents/BKP/x-signal.tmp.mq5 deleted file mode 100644 index f8521623..00000000 --- a/Documents/BKP/x-signal.tmp.mq5 +++ /dev/null @@ -1,2011 +0,0 @@ -// -bool Prepare( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - ENUM_POSITION_TYPE mType, // Long (Buy) or Short (Sell) - ENUM_X_ORDER_MODES mMode, // Execution Mode - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - bool result = false; - - // - result = - // - IsValid(mMode) && - IsValid(mSymbol) && - IsValid(mPeriod) && - NotEmpty(mEntry) && - NotEmpty(mVolume) && - IsValid(mProvider) - // - ; - if (!result) - { - return result; - } - - // - if (mTP < 0) - { - mTP = 0; - } - - // - if (mSL < 0) - { - mSL = 0; - } - - // - type = mType; - mode = mMode; - symbol = mSymbol; - period = mPeriod; - provider = mProvider; - - // - // Normalization Values ... - sl = NormalizePrice(mSL, mSymbol); - tp = NormalizePrice(mTP, mSymbol); - mEntry = NormalizePrice(mEntry, mSymbol); - mVolume = NormalizeVolume(mVolume, mSymbol); - - // - entry = mEntry; - volume = mVolume; - - // - result = Normalize(); - - // - return result; -} - -// -bool PrepareComplex( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - ENUM_POSITION_TYPE mType, // Long (Buy) or Short (Sell) - ENUM_X_ORDER_MODES mMode, // Execution Mode - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - // - // TP ... - double mFullTPLevel = 0, // Full TP Level - double mPartialCloseOnTPLevel = 0, // Partial Close On TP Level - double mPartialCloseMultiplier = 0, // Partial Close Multiplier - // - // RF ... - bool mRiskFreeOnBreakEven = false, // Risk Free Signal On Break Even ... - double mTpLevelForBreakEven = 0, // TP Level for Break Even ... - // - // SL Trail ... - bool mTrailSL = false, // Trail SL - double mTrailSLStartOnReachTPLevel = 0 // Trail SL Starts after Reached TP Level -) -{ - // - bool result = false; - - // - // Validate Args ... - result = - // - // Common ... - mSL > 0 && - mEntry > 0 && - mVolume > 0 && - IsValid(mSymbol) && - IsValid(mPeriod) && - IsValid(mProvider) && - mMode != X_ORDER_MODE_NOTHING - // - && - // - // TP ... - mFullTPLevel > 0 - // - ; - if (!result) - { - return result; - } - - // - // Prepare Regular Signal Values ... - double _risk = MathAbs(mEntry - mSL); - double _reward = _risk * mFullTPLevel; - - // - bool isLong = IsLong(mType); - - // - sl = mSL; - type = mType; - mode = mMode; - entry = mEntry; - symbol = mSymbol; - period = mPeriod; - volume = mVolume; - provider = mProvider; - fullTPLevel = mFullTPLevel; - tp = isLong - ? mEntry + _reward - : mEntry - _reward; - - // - result = Normalize(); - if (!result) - { - return result; - } - - // - // Calculate Other Conditions ... - - // - bool canPartialClose = - // - mPartialCloseOnTPLevel > 0 && - mPartialCloseMultiplier > 0 && - mPartialCloseOnTPLevel < mFullTPLevel - // - ; - if (canPartialClose) - { - // - partialCloseOnTPLevel = mPartialCloseOnTPLevel; - partialCloseMultiplier = mPartialCloseMultiplier; - } - - // - bool canRFOnBEP = - // - mRiskFreeOnBreakEven && - mTpLevelForBreakEven > 0 - // - ; - if (canRFOnBEP) - { - // - riskFreeOnBreakEven = mRiskFreeOnBreakEven; - tpLevelForBreakEven = mTpLevelForBreakEven; - } - - // - bool canTrailSL = - // - mTrailSL && - mTrailSLStartOnReachTPLevel > 0 && - mTrailSLStartOnReachTPLevel < mFullTPLevel - // - ; - if (canTrailSL) - { - // - trailSL = mTrailSL; - trailSLStartOnReachTPLevel = mTrailSLStartOnReachTPLevel; - } - - // - result = IsValid(); - - // - return result; -} - -// -bool PrepareLong( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - ENUM_X_ORDER_MODES mMode, // Execution Mode - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return Prepare( - mSymbol, - mProvider, - mPeriod, - POSITION_TYPE_BUY, - mMode, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -bool PrepareShort( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - ENUM_X_ORDER_MODES mMode, // Execution Mode - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return Prepare( - mSymbol, - mProvider, - mPeriod, - POSITION_TYPE_SELL, - mMode, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -// Market Mode ... - -// -bool PrepareMarketLong( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareLong( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_MARKET, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -bool PrepareMarketShort( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareShort( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_MARKET, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -// Stop Mode ... - -// -bool PrepareStopLong( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareLong( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_STOP, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -bool PrepareStopShort( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareShort( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_STOP, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -// Limit Mode ... - -// -bool PrepareLimitLong( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareLong( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_LIMIT, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -bool PrepareLimitShort( - string mSymbol, // Trading Symbol - string mProvider, // Signal Provider - ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame - double mEntry, // Entry Price - double mVolume, // Volume - double mSL = 0, // Stop Loss - double mTP = 0 // Take Profit -) -{ - // - return PrepareShort( - mSymbol, - mProvider, - mPeriod, - X_ORDER_MODE_LIMIT, - mEntry, - mVolume, - mSL, - mTP - // - ); -} - -// -// Generate Opposit Direction ... -bool GenerateOpposit( - XSignal &mSignal // Oppsoit Signal -) -{ - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - ENUM_POSITION_TYPE mType = Opposit(this.type); - double mEntry = GetExit(this.symbol, mType); - - // - bool isLong = IsLong(mType); - - // - // Calculate Risk Reward Ratio ... - double risk = GetRisk(); - double reward = GetReward(); - - // - double mSL = isLong - ? mEntry - risk - : mEntry + risk; - - // - double mTP = isLong - ? mEntry + reward - : mEntry - reward; - - // - result = mSignal.Prepare( - this.symbol, - this.provider, - this.period, - mType, - this.mode, - mEntry, - this.volume, - mSL, - mTP // - ); - - // - return result; -} - -// -// Prepare Opposit Signal based On a Position ... -bool PrepareOpposit( - XPosition &source // Source Data -) -{ - // - bool result = false; - - // - ENUM_POSITION_TYPE mType = Opposit(source.type); - double mEntry = GetEntry(source.symbol, mType); - - // - bool isLong = IsLong(mType); - - // - double risk = source.GetRisk(); - double reward = source.GetReward(); - - // - double mSL = isLong - ? mEntry - risk - : mEntry + risk; - - // - double mTP = isLong - ? mEntry + reward - : mEntry - reward; - - // - return Prepare( - source.symbol, - source.provider, - source.period, - mType, - X_ORDER_MODE_MARKET, - mEntry, - source.volume, - mSL, - mTP // - ); - - // - result = IsValid(); - - // - return result; -} - -///////////////////////////////////////////////////////////////////////////// - -// -// Handle Executing Support Signals ... -int supportsCount = ArraySize(mSignal.supports); -if (supportsCount > 0) -{ - // - int executed = 0; - for (int i = 0; i < supportsCount; i++) - { - // - XSignal iSupport = mSignal.supports[i]; - - // - int supIndex = i + 1; - string iComment = GenerateSupportTag(ticket); - iSupport.comment = iComment; - - // - bool isExecuted = ExecuteSignal( - iSupport, - state, - lifetime, - expiration - // - ); - if (isExecuted) - { - executed++; - } - } - - // - result = executed == supportsCount; -} - -/////////////////////////////////////////////////////////////////////////////////// - -// -// Handle Partial Close on Specified Targets ... -has = !trades[idx].signal.isPartiallyClosed && - trades[idx].signal.partialCloseOnTPLevel > 0 && - trades[idx].signal.partialCloseMultiplier > 0; -if (has) -{ - // - // Check Reward Touched ... - double iCurrReward = iPosition.CalculateTouchedReward(); - has = iCurrReward >= trades[idx].signal.partialCloseOnTPLevel; - if (has) - { - // - // Check Volume Multiplier ... - double volumeMultiplier = trades[idx].signal.partialCloseMultiplier; - has = volumeMultiplier > 0 && - volumeMultiplier <= 1; - if (has) - { - // - // Do Partial Closing ... - double volume = iPosition.volume * volumeMultiplier; - - // - // Normalizing Volume ... - volume = NormalizeVolume( - volume, - iPosition.symbol // - ); - - // - string comment = "PC On Target ..."; - has = trader.ClosePartial( - iPosition.ticket, - volume, - comment // - ); - if (has) - { - // - // Update Model ... - trades[idx].signal.isPartiallyClosed = true; - - // - string message = prefix + - ToString(iPosition.type) + - " Position: " + - ToString(iPosition.ticket) + - " PC (" + ToString(volume) + ") On Traget: " + ToString(iCurrReward) + - " Successfully ..."; - HandleReportProtector(message); - } - } - } -} - -/////////////////////////////////////////////////////////////////////////////////// - -// -// Check Different Trigger Conditions ... - -// -// Checking Trigger Cond 0 ... -bool canTriggerCond0 = false; -// CanTriggerCond0( -// helper, -// conditions.decisionZone, -// triggerDir, -// sl, -// tp, -// barIndex // -// ); - -// -// Checking Trigger Cond 1 ... -bool canTriggerCond1 = false; -if (isTooLarge) -{ - // - canTriggerCond1 = CanTriggerCond1( - helper, - conditions.decisionZone, - triggerDir, - sl, - targets, - iObjects, - barIndex // - ); -} - -// -// Checking Trigger Cond 2 ... -bool canTriggerCond2 = false; -if (!isTooLarge) -{ - // - canTriggerCond2 = CanTriggerCond2( - helper, - conditions.decisionZone, - decisionOBs, - triggerDir, - sl, - targets, - iObjects, - barIndex // - ); -} - -// -// Checking Trigger Cond 3 ... -bool canTriggerCond3 = false; -// CanTriggerCond3( -// helper, -// conditions.decisionZone, -// triggerDir, -// sl, -// tp, -// iObjects, -// barIndex // -// ); - -/////////////////////////////////////////////////////////////////////////////////// - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCond0( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - CArrayObj *drawns, - int barIndex = 0, - int loopback = 5, - double scorePassMultiplier = 1 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - // Scores ... - double bullScores[]; - double bearScores[]; - - // - // Volumes ... - double bullVolumes[]; - double bearVolumes[]; - - // - // Create a Loop through Loopack ... - XOHCL iBar; - bool has = false; - int start = barIndex; - XCAEAConditions iConditions; - int end = barIndex + loopback; - for (int i = end; i >= start; i--) - { - // - // Retrieve Bar ... - has = iBar.Init( - box.symbol, - box.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Conditions ... - has = helper.GetConditions( - iConditions, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Scores ... - double iBullScore = 0; - double iBearScore = 0; - iConditions - .GenerateScore( - iBullScore, - iBearScore // - ); - Add( - iBullScore, - bullScores // - ); - Add( - iBearScore, - bearScores // - ); - - // - // Retrieve Volumes ... - double iBullVolume = 0; - double iBearVolume = 0; - helper - .barAnalyser - .CalculateRangeVolume( - iBar, - iBullVolume, - iBearVolume, - 2 // Loopback ... - ); - Add( - iBullVolume, - bullVolumes // - ); - Add( - iBearVolume, - bearVolumes // - ); - - // - iBar.Clean(); - iConditions.Clean(); - } - - // - // Calculating Requirements ... - - // - // Scores ... - - // - // Bullish ... - double bullScore = GetSum(bullScores); - double bullScoreMax = GetMax(bullScores); - double bullScoreMin = GetMin(bullScores); - - // - // Bearish ... - double bearScore = GetSum(bearScores); - double bearScoreMax = GetMax(bearScores); - double bearScoreMin = GetMin(bearScores); - - // - // Volumes ... - - // - // Bullish ... - double bullVolume = GetSum(bullVolumes); - double bullVolumeMax = GetMax(bullVolumes); - double bullVolumeMin = GetMin(bullVolumes); - - // - // Bearish ... - double bearVolume = GetSum(bearVolumes); - double bearVolumeMax = GetMax(bearVolumes); - double bearVolumeMin = GetMin(bearVolumes); - - // - // Creating Result Conditions ... - - // - bool isBullishPassed = - isBullish && - bullScore >= (scorePassMultiplier * bearScore) && - bullVolume >= (scorePassMultiplier * bearVolume); - - // - bool isBearishPassed = - isBearish && - bearScore >= (scorePassMultiplier * bullScore) && - bearVolume >= (scorePassMultiplier * bullVolume); - - // - result = isBullishPassed || - isBearishPassed; - if (!result) - { - // - iBar.Clean(); - Clean(bullScores); - Clean(bearScores); - Clean(bullVolumes); - Clean(bearVolumes); - iConditions.Clean(); - - // - return result; - } - - // - // Validating Box to Find a Rejection ... - - // - // Validating Box to Has a Gap ... - - // - // Validating Box to Has a Block ... - - // - bool isPassed = - isBullishPassed || - isBearishPassed; - if (isPassed) - { - // - // Preparing TP and SL ... - - // - sl = isBullishPassed - ? box.lower - : box.upper; - - // - tp = 0; - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullishPassed; - - // - bool canTriggerShort = - isBearishPassed; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - Clean(bullScores); - Clean(bearScores); - Clean(bullVolumes); - Clean(bearVolumes); - iConditions.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -bool CanTriggerCond1( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Check Box is Faked Breaked Out ... - - // - XBoxZone validatorFVG; - - // - bool isBullishFakedBreakedOut = IsBoxFakedBreakout( - helper, - box, - validatorFVG, - X_DIRECTION_BULLISH, - barIndex, - 100, // Loopback For FVG ... - true, // Force FVg Validation ... - true // Force FVG Bar Type ... - ); - - // - bool isBearishFakedBreakedOut = IsBoxFakedBreakout( - helper, - box, - validatorFVG, - X_DIRECTION_BEARISH, - barIndex, - 100, // Loopback For FVG ... - true, // Force FVg Validation ... - true // Force FVG Bar Type ... - ); - - // - bool isFakeBreaked = - isBullishFakedBreakedOut || - isBearishFakedBreakedOut; - if (isFakeBreaked) - { - // - // Preparing TP and SL ... - - // - sl = isBullishFakedBreakedOut - ? validatorFVG.lower - : validatorFVG.upper; - - // - tp = isBullishFakedBreakedOut - ? box.upper - : box.lower; - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullishFakedBreakedOut; - - // - bool canTriggerShort = - isBearishFakedBreakedOut; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - validatorFVG.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -// Using OB inside Boxes ... -bool CanTriggerCond2( - XCXCAEAHelper *helper, - XBoxZone &decisionZone, - XBoxZone &decisionPivots[], - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = decisionZone.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - string symbol = helper.GetSymbol(); - bool isBullish = decisionZone.IsBullish(); - bool isBearish = decisionZone.IsBearish(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int p2Index = pIndex + 1; - - // - // Extract Bars ... - XOHCL zBar; - XOHCL cBar; - result = zBar.Init( - symbol, - period, - cIndex // - ); - result = - result && - zBar.GetPreviousBar(cBar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - - // - return result; - } - - // - bool has = false; - XBoxZone selectedPivot; - bool hasPivots = HasChild(decisionPivots); - int pivotsCount = ArraySize(decisionPivots); - - // - // Select Activated Pivot ... - if (hasPivots) - { - // - for (int i = 0; i < pivotsCount; i++) - { - // - // Check Rejection of Block ... - has = - isBullish - ? cBar.IsBullish() && - decisionPivots[i].IsBullish() && - cBar.low < decisionPivots[i].upper && - cBar.low > decisionPivots[i].lower && - cBar.close > decisionPivots[i].upper - : cBar.IsBearish() && - decisionPivots[i].IsBearish() && - cBar.high > decisionPivots[i].lower && - cBar.high < decisionPivots[i].upper && - cBar.close < decisionPivots[i].lower; - if (has) - { - selectedPivot = decisionPivots[i]; - } - - // // - // // Draw Pivot ... - // XCBoxObject *iObj; - - // // - // has = helper.poiDrawer.DrawBox( - // decisionPivots[i], - // iObj // - // ); - // if (has) - // { - // drawns.Add(iObj); - // } - - // // - // ZeroMemory(iObj); - } - } - - // - // Check Selected Pivot is Exists or not ... - bool hasSelectedPivot = selectedPivot.IsValid(); - - // - // Detect Liquidity For Selected Pivot ... - double ssl = 0; - double bsl = 0; - bool hasSSL = false; - bool hasBSL = false; - if (hasSelectedPivot) - { - // - // Required Info ... - // int toIDX = selectedPivot.ToIndex(); - // int fromIDX = selectedPivot.FromIndex(); - - // // - // // SSL ... - // datetime sslTo = NULL; - // datetime sslFrom = NULL; - - // // - // // BSL ... - // datetime bslTo = NULL; - // datetime bslFrom = NULL; - - // // - // // Loop ... - // XOHCL iBar; - // for (int i = fromIDX; i > toIDX; i--) - // { - // // - // hasSSL = - // ssl > 0 && - // IsValid(sslTo) && - // IsValid(sslFrom); - - // // - // hasBSL = - // bsl > 0 && - // IsValid(bslTo) && - // IsValid(bslFrom); - - // // - // iBar.Clean(); - - // // - // if (hasSSL && hasBSL) - // { - // break; - // } - // } - // iBar.Clean(); - } - - // - // Draw Selected Pivot ... - if (hasSelectedPivot) - { - // - // Draw Pivot ... - XCBoxObject *iObj; - - // - has = helper.poiDrawer.DrawBox( - selectedPivot, - iObj // - ); - if (has) - { - // - color iColor = - isBullish - ? clrAqua - : clrMagenta; - - // - iObj.BoxWidth(2); - iObj.BoxColor(iColor); - iObj.BoxStyle(STYLE_SOLID); - - // - drawns.Add(iObj); - } - - // - ZeroMemory(iObj); - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullish && - hasSelectedPivot && - selectedPivot.IsBullish(); - - // - bool canTriggerShort = - isBearish && - hasSelectedPivot && - selectedPivot.IsBearish(); - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - // - // Preparing TP and SL ... - - // - sl = canTriggerLong - ? selectedPivot.lower // activatedFVG.lower - : selectedPivot.upper; // activatedFVG.upper; - - // - // Since Here TP Must Calculated - // Using R2R we Ignore Target ... - tp = 0; - // if (isBullish && zBar.close < decisionZone.upper) - // { - // tp = decisionZone.upper; - // } - // else if (isBearish && zBar.close > decisionZone.lower) - // { - // tp = decisionZone.lower; - // } - } - - // - // Cleanup Resources ... - zBar.Clean(); - cBar.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -// Block Based Triggering ... -bool CanTriggerCond3( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - XTarget &targets[], - CArrayObj *drawns, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - bool has = false; - int swingLoopback = 7; - ENUM_TIMEFRAMES period = helper.GetPeriod(); - string symbol = helper.GetSymbol(); - int toIDX = box.ToIndex(period); - int fromIDX = box.FromIndex(period); - datetime cTime = GetBarTime( - symbol, - period, - barIndex // - ); - - // - // Initialize iBar ... - XOHCL iBar; - result = iBar.Init( - symbol, - period, - barIndex // - ); - if (!result) - { - // - iBar.Clean(); - - // - return result; - } - - // - // Validate Box ... - // For Box Validating we use 50% of Box Range ... - // if Price Touched Box 50% rate we Invalidate Box ... - // r if Prce Touched Leg 2 of Box Size ... - double boxLeg2 = box.GetLeg(2); - - // - // Draw Box Leg2 ... - string iLeg2Name = box.GetMiddleTag(); - StringReplace( - iLeg2Name, - "Mid", - "Leg2" // - ); - CChartObjectTrend *iLeg2Obj; - iLeg2Obj = new CChartObjectTrend(); - has = iLeg2Obj.Create( - helper.poiDrawer.ChartIdentification(), - iLeg2Name, - helper.poiDrawer.SubWindowIdentification(), - box.from, - boxLeg2, - box.to, - boxLeg2 // - ); - if (has) - { - // - iLeg2Obj.Color(clrYellow); - - // - drawns.Add(iLeg2Obj); - } - ZeroMemory(iLeg2Obj); - - // - bool isBoxValid = - isBullish - ? iBar.close < boxLeg2 - : iBar.close > boxLeg2; - result = isBoxValid; - if (!result) - { - // - box.Clean(); - iBar.Clean(); - - // - return result; - } - iBar.Clean(); - - // - // Detect Box FVG ... - - // - // we Have to Detect a Broken Liquidity for Box ... - - // - XBoxZone fvg; - XBoxZone fvgs[]; - for (int i = fromIDX + loopback; i > barIndex; i--) - { - // - // Initialize iBar ... - XOHCL iBar; - has = iBar.Init( - symbol, - period, - i // - ); - if (!has) - { - // - iBar.Clean(); - - // - break; - } - - // - // Check iBar Has FVG ... - XBoxZone iFVG; - has = helper - .barAnalyser - .IsFVG( - iBar, - iFVG, - true // - ); - has = - // - // Check FVG Exists ... - has && - // - // Check FVG Direction ... - iFVG.dir == box.dir && - // - // Check FVG not Breaked ... - !IsBoxBreaked( - helper, - iFVG, - barIndex // - ) && - // - // Check FVG Placement ... - (iFVG.IsBullish() - ? iFVG.lower < box.upper - : iFVG.upper > box.lower); - if (has) - { - // - iFVG.to = cTime; - - // - AddRef( - iFVG, - fvgs // - ); - } - - // - iBar.Clean(); - iFVG.Clean(); - } - - // - // Detecting Target FVG ... - int idx = isBullish - ? GetHighest(fvgs) - : GetLowest(fvgs); - has = IsValidIndex(idx); - if (has) - { - // - fvg = fvgs[idx]; - - // - fvg.to = cTime; - } - - // - // Ensure FVG must Exists ... - result = fvg.IsValid(); - if (!result) - { - // - fvg.Clean(); - Clean(fvgs); - - // - return result; - } - - // - // Check FVg Break ... - bool isBreaked = IsBoxBreaked( - helper, - fvg, - barIndex // - ); - result = !isBreaked; - if (!result) - { - // - fvg.Clean(); - Clean(fvgs); - - // - return result; - } - - // - // Draw FVG ... - XCBoxObject *iObj; - has = helper.poiDrawer.DrawBox( - fvg, - iObj // - ); - if (has) - { - // - color fvgColor = - isBullish - ? clrLime - : clrRed; - - // - iObj.BoxWidth(2); - iObj.BoxColor(fvgColor); - iObj.Style(STYLE_SOLID); - - // - drawns.Add(iObj); - } - ZeroMemory(iObj); - - // - // Detecting Liquiidties ... - XCAEALQSweep iLQ; - XCAEALQSweep lqs[]; - toIDX = fvg.ToIndex(); - fromIDX = fvg.FromIndex(); - XCAEAConditions iConditions; - double fvgPrice = isBullish - ? fvg.upper - : fvg.lower; - double fvgReversePrice = isBullish - ? fvg.lower - : fvg.upper; - for (int i = fromIDX; i > toIDX; i--) - { - // - // Initialize iBar ... - has = iBar.Init( - symbol, - period, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Reading Conditions ... - has = helper.GetConditions( - iConditions, - i, - 5 // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - break; - } - - // - double iSweep = - isBullish - ? iConditions.valeBuffer[1] - : iConditions.peakBuffer[1]; - double iSweepP = - isBullish - ? iConditions.valeBuffer[2] - : iConditions.peakBuffer[2]; - double iSweepP2 = - isBullish - ? iConditions.valeBuffer[3] - : iConditions.peakBuffer[3]; - double iReverse = - isBullish - ? iConditions.peakBuffer[1] - : iConditions.valeBuffer[1]; - - // - bool isSweepContinue = - iSweepP == iSweep && - (isBullish - ? iSweep > fvgPrice - : iSweep < fvgPrice); - - // - bool isSweepContinueP = - iSweepP2 == iSweepP && - (isBullish - ? iSweepP > fvgPrice - : iSweepP < fvgPrice); - - // - bool isSweepStart = - isSweepContinue && - !isSweepContinueP; - - // - bool isSweepFinished = - !isSweepContinue && - isSweepContinueP; - - // - if (isSweepStart) - { - // - iLQ.Clean(); - - // - iLQ.symbol = iBar.symbol; - iLQ.period = iBar.period; - iLQ.type = isBullish - ? XCAEA_LQ_TYPE_VALE - : XCAEA_LQ_TYPE_PEAK; - iLQ.to = iBar.time; - iLQ.from = iBar.time; - - // - iLQ.length = 1; - iLQ.sweeped = iSweep; - iLQ.reverse = iReverse; - } - - // - if (isSweepContinue) - { - // - iLQ.length++; - iLQ.to = iBar.time; - iLQ.sweeped = iSweep; - iLQ.reverse = MathMin(iLQ.reverse, iReverse); - } - - // - if (isSweepFinished) - { - // - AddRef( - iLQ, - lqs // - ); - - // - iLQ.Clean(); - } - - // - iBar.Clean(); - iConditions.Clean(); - } - - // - // Retrieve Bar and Conditions ... - has = iBar.Init( - symbol, - period, - barIndex // - ); - has = has && - helper.GetConditions( - iConditions, - barIndex, - loopback // - ); - result = has; - if (!result) - { - // - Clean(lqs); - fvg.Clean(); - iLQ.Clean(); - Clean(fvgs); - iBar.Clean(); - iConditions.Clean(); - - // - return result; - } - - // - // Select Peak/Vale Value Based on Box ... - double iPV = isBullish - ? iConditions.valeBuffer[1] - : iConditions.peakBuffer[1]; - double iPVReverse = isBullish - ? iConditions.peakBuffer[1] - : iConditions.valeBuffer[1]; - - // - // Validate Liquidities Exists ... - result = HasChild(lqs); - if (!result) - { - // - Clean(lqs); - fvg.Clean(); - iLQ.Clean(); - Clean(fvgs); - iBar.Clean(); - iConditions.Clean(); - - // - return result; - } - - // - // Draw Liquidities ... - for (int i = 0; i < ArraySize(lqs); i++) - { - // - iLQ = lqs[i]; - - // - CChartObjectTrend *iTrend; - iTrend = new CChartObjectTrend(); - string itName = iLQ.GetTag(); - has = iTrend.Create( - 0, - itName, - 0, - iLQ.from, - iLQ.sweeped, - iLQ.to, - iLQ.sweeped // - ); - if (has) - { - // - color itColor = - isBullish - ? clrLime - : clrRed; - - // - iTrend.Width(2); - iTrend.Color(itColor); - iTrend.Style(STYLE_SOLID); - - // - drawns.Add(iTrend); - } - - // - ZeroMemory(iTrend); - } - - // - // PV Must go Inside FVG ... - has = - isBullish - ? iPV < fvgPrice - : iPV > fvgPrice; - result = has; - if (!result) - { - // - Clean(lqs); - fvg.Clean(); - iLQ.Clean(); - Clean(fvgs); - iBar.Clean(); - iConditions.Clean(); - - // - return result; - } - - // - // Detect a Traget for SL based on Activated FVG ... - XBoxZone slTarget; - double fvgValidatorPrice = - isBullish - ? fvg.lower - : fvg.upper; - for (int i = 0; i < ArraySize(fvgs); i++) - { - // - XBoxZone iFVG = fvgs[i]; - - // - double iFVGPrice = - isBullish - ? iFVG.upper - : iFVG.lower; - - // - // Validate Placement ... - has = iFVGPrice > fvgValidatorPrice; - if (!has) - { - // - iFVG.Clean(); - - // - continue; - } - - // - // Set slTarget ... - double slTargetPrice = (isBullish - ? slTarget.upper - : slTarget.lower); - has = - !slTarget.IsValid() - ? true - : (isBullish - ? slTargetPrice < iFVGPrice - : slTargetPrice > iFVGPrice); - if (has) - { - slTarget = iFVG; - } - } - - // - // Ensure SL Target Exists ... - result = slTarget.IsValid(); - if (!result) - { - // - Clean(lqs); - fvg.Clean(); - iLQ.Clean(); - Clean(fvgs); - iBar.Clean(); - iConditions.Clean(); - - // - return result; - } - - // - // Darw SL Target Zone ... - slTarget.to = cTime; - XCBoxObject *iSLObj; - has = helper.poiDrawer.DrawBox( - slTarget, - iSLObj // - ); - if (has) - { - // - color slTargetColor = - isBullish - ? clrAqua - : clrMagenta; - - // - iSLObj.BoxWidth(1); - iSLObj.BoxColor(slTargetColor); - - // - drawns.Add(iSLObj); - } - ZeroMemory(iSLObj); - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullish && - fvg.IsBullish() && - slTarget.IsBullish(); - - // - bool canTriggerShort = - isBearish && - fvg.IsBearish() && - slTarget.IsBearish(); - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - // Preparing TP and SL ... - - // - sl = isBullish - ? slTarget.lower - : slTarget.upper; - - // - // Since Here TP Must Calculated - // Using R2R we Ignore Target ... - tp = 0; - - // - // Add Target if price is Inside Analyse Box ... - double price = iBar.close; - double target = - isBullish - ? box.upper - : box.lower; - has = - isBullish - ? price < target - : price > target; - if (has) - { - tp = target; - } - } - - // - // Cleanup Resources ... - - // - Clean(lqs); - fvg.Clean(); - iLQ.Clean(); - Clean(fvgs); - iBar.Clean(); - iConditions.Clean(); - - // - return result; -} - -/////////////////////////////////////////////////////////////////////////////////// diff --git a/Documents/BKP/xcaea.signaller.non-analyser.lib.mq5 b/Documents/BKP/xcaea.signaller.non-analyser.lib.mq5 deleted file mode 100644 index e640c863..00000000 --- a/Documents/BKP/xcaea.signaller.non-analyser.lib.mq5 +++ /dev/null @@ -1,2496 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCAEASignaller Lib -// Description: Library for XCAEA Signaller ... -// -// -// 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 Library for XCAEA Signaller" -#property strict - -// -// Imports ... -#include "../../Libraries/x-saherelm.common.lib.mq5" -#include "../../Libraries/x-saherelm.x-poi.lib.mq5" -#include "../../Libraries/x-saherelm.x-trade.lib.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" -#include "../Classes/xcaea.x-poi.drawer.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Enumeration ... - -// -// Guard Actions ... -enum ENUM_GUARD_ACTIONS -{ - X_GUARD_ACTION_NONE, // Nothing to Do - X_GUARD_ACTION_CLOSE, // Close Specified Position - X_GUARD_ACTION_CLOSE_ALL, // Close All Positions - X_GUARD_ACTION_CLOSE_LONGS, // Close All Long Positions - X_GUARD_ACTION_CLOSE_SHORTS, // Close All Short Position - X_GUARD_ACTION_PARTIAL_CLOSE, // Partial Close Specified Position - X_GUARD_ACTION_TRAIL_STOP, // Trail Stop of Specified Position - X_GUARD_ACTION_TRAIL_TARGET, // Trail Target of Specified Position - X_GUARD_ACTION_HEDGE, // Hedge Specified Positions -}; - -// -// Definitions ... - -// -// Conditions Struct ... -struct XCAEAStrategyConditions -{ - // - // Props ... - - // - string symbol; - ENUM_TIMEFRAMES period; - - // - // Setup Props ... - - // - double sl; - double tp; - double pivot; - double point; - double entry; - double reward; - string provider; - double targets[]; - - // - datetime time; - datetime setupTime; - datetime triggerTime; - - // - double partialCloseOnTPLevel; - double partialCloseMultiplier; - - // - ENUM_X_DIRECTION dir; - XBoxZone decisionZone; - ENUM_X_POSITION_TYPES type; - XCAEAConditions conditions; - - // - // Constructor ... - XCAEAStrategyConditions() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleaning Up ... - */ - void Clean() - { - // - sl = 0; - tp = 0; - pivot = 0; - point = 0; - entry = 0; - reward = 0; - - // - symbol = NULL; - period = NULL; - provider = NULL; - - // - time = NULL; - setupTime = NULL; - triggerTime = NULL; - - // - partialCloseOnTPLevel = 0; - partialCloseMultiplier = 0; - - // - Clean(targets); - - // - conditions.Clean(); - decisionZone.Clean(); - - // - dir = X_DIRECTION_NONE; - type = X_POSITION_TYPE_NONE; - - // - ZeroMemory(this); - } - - // - // Signalling ... - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = IsSpecifiedValid(symbol) && - IsSpecifiedValid(period) && - IsSpecifiedValid(time); - - // - return result; - } - - /** - * Check Conditions Has Valid Bullish Signal ... - * - * @return ( bool ) - */ - bool HasBullishSignal() - { - // - bool result = false; - - // - result = - (sl > 0 || - tp > 0) && - IsValid() && - HasDirection(dir); - if (!result) - { - return result; - } - - // - result = - IsBullish(dir); - - // - return result; - } - - /** - * Check Conditions Has Valid Bearish Signal ... - * - * @return ( bool ) - */ - bool HasBearishSignal() - { - // - bool result = false; - - // - result = - (sl > 0 || - tp > 0) && - IsValid() && - HasDirection(dir); - if (!result) - { - return result; - } - - // - result = - IsBearish(dir); - - // - return result; - } - - // - // Setting Up and Triggering Up ... - - /** - * Check Condition is Setting Up ... - * - * @param dir: ENUM_X_DIRECTION member, Setting Up Direction ... - * - * @return ( bool ) - */ - bool IsSetuped() - { - // - bool result = false; - - // - result = IsValid(setupTime) && - HasDirection(dir); - if (!result) - { - return result; - } - - // - return result; - } - - /** - * Calculate Setup Age ... - * - * @return ( int ) - */ - int GetSetupAge() - { - // - int result = 0; - - // - if (!IsSetuped()) - { - return result; - } - - // - result = (int)(TimeCurrent() - setupTime) / PeriodSeconds(period); - - // - return result; - } - - /** - * Detect How we Can Trigger Signal ... - * - * @return ( bool ) - */ - bool CanTrigger() - { - // - bool result = false; - - // - result = - // - sl > 0 && - IsValid(symbol) && - IsValid(period) && - IsValid(triggerTime) && - type != X_POSITION_TYPE_ALL && - type != X_POSITION_TYPE_NONE - // - ; - - // - return result; - } - - // -}; - -// -// Model a Guard Action ... -struct XCAEAGuard -{ - // - // Props ... - ENUM_GUARD_ACTIONS action; - datetime time; - - // - string symbol; - string provider; - - // - // Specified Position ... - ulong ticket; - - // - // Partial Close ... - double volumeMultiplier; - - // - // SL Trial ... - double sl; - - // - // TP Trial ... - double tp; - - // - // Constructor ... - XCAEAGuard() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - time = NULL; - action = X_GUARD_ACTION_NONE; - - // - symbol = NULL; - provider = NULL; - - // - ticket = 0; - - // - volumeMultiplier = 0; - - // - sl = 0; - tp = 0; - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(time) && - IsValid(symbol) && - IsValid(provider) && - action != X_GUARD_ACTION_NONE - // - ; - if (!result) - { - return result; - } - - // - // Validate Model Based On Specified Guard Actions ... - - // - return result; - } -}; - -/** - * Add Guard to Collection ... - * - * @param guard: XCAEAGuard instance ... - * @param guards: XCAEAGuard instance Collection ... - * - * @return ( int ) - */ -int AddGuard( - XCAEAGuard &guard, - XCAEAGuard &guards[] // -) -{ - // - int result = 0; - - // - if (!guard.IsValid()) - { - return result; - } - - // - AddRef( - guard, - guards // - ); - - // - result = ArraySize(guards); - - // - return result; -} - -// -// Detect Decision Zone ... -bool DetectDecisionZone( - XCXCAEAHelper *helper, - XCXCAEAPOIDrawer *drawer, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - XCAEAConditions &conditions, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - int idx = -1; - int count = 0; - bool has = false; - - // - box.Clean(); - conditions.Clean(); - dir = X_DIRECTION_NONE; - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 5); - - // - // Retrieve Some Requirements ... - string symbol = helper.GetSymbol(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - double points = GetPoints(symbol); - - // - // Retrieve Conditions for Processing ... - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - box.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Define IDXses ... - int zIDX = barIndex; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - XOHCL p4Bar; - result = zBar.Init( - symbol, - period, - zIDX // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - pBar.GetPreviousBar(p2Bar); - result = - result && - p2Bar.GetPreviousBar(p3Bar); - result = - result && - p3Bar.GetPreviousBar(p4Bar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - box.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Bars Conditions ... - - // - // Score ... - - // - double bullishScore = 0; - double bearishScore = 0; - conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - bool isScoreBullish = - bullishScore > bearishScore; - - // - bool isScoreBearish = - bearishScore > bullishScore; - - // - bool isScoreNeutural = MathAbs(bullishScore - bearishScore) == 0; - - // - // Calculating Range Volumes ... - - // - double bullishVolume = 0; - double bearishVolume = 0; - helper.barAnalyser.CalculateRangeVolume( - cBar, - bullishVolume, - bearishVolume, - loopback // - ); - - // - bool isVolumeNeutural = MathAbs(bullishVolume - bearishVolume) == 0; - - // - // Checking OB ... - XBoxZone ob; - bool isOB = helper - .barAnalyser - .IsOrderBlock( - cBar, - ob, - false, // Force FVG Bar Type - true // Force Two Bar Start ... - ); - bool isBullishOB = - isOB && - ob.IsBullish(); - bool isBearishOB = - isOB && - ob.IsBearish(); - - // - // Reading Values ... - - // - // SAR ... - double zSar = conditions.sarBuffer[zIDX]; - double cSar = conditions.sarBuffer[cIDX]; - double pSar = conditions.sarBuffer[pIDX]; - double p2Sar = conditions.sarBuffer[p2IDX]; - double p3Sar = conditions.sarBuffer[p3IDX]; - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - double p3Peak = conditions.peakBuffer[p3IDX]; - double p4Peak = conditions.peakBuffer[p4IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - double p3Vale = conditions.valeBuffer[p3IDX]; - double p4Vale = conditions.valeBuffer[p4IDX]; - - // - // SWING Low ... - double zSWL = conditions.swingLowBuffer[zIDX]; - double cSWL = conditions.swingLowBuffer[cIDX]; - double pSWL = conditions.swingLowBuffer[pIDX]; - double p2SWL = conditions.swingLowBuffer[p2IDX]; - double p3SWL = conditions.swingLowBuffer[p3IDX]; - - // - // SWING High ... - double zSWH = conditions.swingHighBuffer[zIDX]; - double cSWH = conditions.swingHighBuffer[cIDX]; - double pSWH = conditions.swingHighBuffer[pIDX]; - double p2SWH = conditions.swingHighBuffer[p2IDX]; - double p3SWH = conditions.swingHighBuffer[p3IDX]; - - // - // SUPPORT ... - double zSupport = conditions.supportBuffer[zIDX]; - double cSupport = conditions.supportBuffer[cIDX]; - double pSupport = conditions.supportBuffer[pIDX]; - double p2Support = conditions.supportBuffer[p2IDX]; - double p3Support = conditions.supportBuffer[p3IDX]; - - // - // RESISTANCE ... - double zResistance = conditions.resistanceBuffer[zIDX]; - double cResistance = conditions.resistanceBuffer[cIDX]; - double pResistance = conditions.resistanceBuffer[pIDX]; - double p2Resistance = conditions.resistanceBuffer[p2IDX]; - double p3Resistance = conditions.resistanceBuffer[p3IDX]; - - // - // MAH ... - double zMAH = conditions.mahBuffer[zIDX]; - double cMAH = conditions.mahBuffer[cIDX]; - double pMAH = conditions.mahBuffer[pIDX]; - double p2MAH = conditions.mahBuffer[p2IDX]; - double p3MAH = conditions.mahBuffer[p3IDX]; - - // - // MAL ... - double zMAL = conditions.malBuffer[zIDX]; - double cMAL = conditions.malBuffer[cIDX]; - double pMAL = conditions.malBuffer[pIDX]; - double p2MAL = conditions.malBuffer[p2IDX]; - double p3MAL = conditions.malBuffer[p3IDX]; - - // - // MAC ... - double zMAC = conditions.macBuffer[zIDX]; - double cMAC = conditions.macBuffer[cIDX]; - double pMAC = conditions.macBuffer[pIDX]; - double p2MAC = conditions.macBuffer[p2IDX]; - double p3MAC = conditions.macBuffer[p3IDX]; - - // - // FIBO Level 1 ... - double zFib1 = conditions.fiboLevel1Buffer[zIDX]; - double cFib1 = conditions.fiboLevel1Buffer[cIDX]; - double pFib1 = conditions.fiboLevel1Buffer[pIDX]; - double p2Fib1 = conditions.fiboLevel1Buffer[p2IDX]; - double p3Fib1 = conditions.fiboLevel1Buffer[p3IDX]; - - // - // FIBO Level 2 ... - double zFib2 = conditions.fiboLevel2Buffer[zIDX]; - double cFib2 = conditions.fiboLevel2Buffer[cIDX]; - double pFib2 = conditions.fiboLevel2Buffer[pIDX]; - double p2Fib2 = conditions.fiboLevel2Buffer[p2IDX]; - double p3Fib2 = conditions.fiboLevel2Buffer[p3IDX]; - - // - // FIBO Level 3 ... - double zFib3 = conditions.fiboLevel3Buffer[zIDX]; - double cFib3 = conditions.fiboLevel3Buffer[cIDX]; - double pFib3 = conditions.fiboLevel3Buffer[pIDX]; - double p2Fib3 = conditions.fiboLevel3Buffer[p2IDX]; - double p3Fib3 = conditions.fiboLevel3Buffer[p3IDX]; - - // - // FIBO Level 4 ... - double zFib4 = conditions.fiboLevel4Buffer[zIDX]; - double cFib4 = conditions.fiboLevel4Buffer[cIDX]; - double pFib4 = conditions.fiboLevel4Buffer[pIDX]; - double p2Fib4 = conditions.fiboLevel4Buffer[p2IDX]; - double p3Fib4 = conditions.fiboLevel4Buffer[p3IDX]; - - // - // FIBO Level 5 ... - double zFib5 = conditions.fiboLevel5Buffer[zIDX]; - double cFib5 = conditions.fiboLevel5Buffer[cIDX]; - double pFib5 = conditions.fiboLevel5Buffer[pIDX]; - double p2Fib5 = conditions.fiboLevel5Buffer[p2IDX]; - double p3Fib5 = conditions.fiboLevel5Buffer[p3IDX]; - - // - // FAST ... - double zFast = conditions.fastBuffer[zIDX]; - double cFast = conditions.fastBuffer[cIDX]; - double pFast = conditions.fastBuffer[pIDX]; - double p2Fast = conditions.fastBuffer[p2IDX]; - double p3Fast = conditions.fastBuffer[p3IDX]; - - // - // FAST State ... - double zFastState = conditions.fastStateBuffer[zIDX]; - double cFastState = conditions.fastStateBuffer[cIDX]; - double pFastState = conditions.fastStateBuffer[pIDX]; - double p2FastState = conditions.fastStateBuffer[p2IDX]; - double p3FastState = conditions.fastStateBuffer[p3IDX]; - - // - // RSI ... - double zRSI = conditions.rsiBuffer[zIDX]; - double cRSI = conditions.rsiBuffer[cIDX]; - double pRSI = conditions.rsiBuffer[pIDX]; - double p2RSI = conditions.rsiBuffer[p2IDX]; - double p3RSI = conditions.rsiBuffer[p3IDX]; - - // - // Create Custom Conditions ... - - // - // Bar and Fibo Conditions ... - - // - // Bearish ... - - // - // Strong Reversal ... - bool isZBarOnFiboStrongBearish = zBar.low > zFib5; - bool isCBarOnFiboStrongBearish = cBar.low > cFib5; - bool isPBarOnFiboStrongBearish = pBar.low > pFib5; - bool isP2BarOnFiboStrongBearish = p2Bar.low > p2Fib5; - bool isP3BarOnFiboStrongBearish = p3Bar.low > p3Fib5; - - // - // Golden Zone Reversal ... - bool isZBarOnFiboGoldenBearish = zBar.low > zFib3 && - zBar.high < zFib4; - bool isCBarOnFiboGoldenBearish = cBar.low > cFib3 && - cBar.high < cFib4; - bool isPBarOnFiboGoldenBearish = pBar.low > pFib3 && - pBar.high < pFib4; - bool isP2BarOnFiboGoldenBearish = p2Bar.low > p2Fib3 && - p2Bar.high < p2Fib4; - bool isP3BarOnFiboGoldenBearish = p3Bar.low > p3Fib3 && - p3Bar.high < p3Fib4; - - // - // Bullish ... - - // - // Strong Reversal ... - bool isZBarOnFiboStrongBullish = zBar.high < zFib1; - bool isCBarOnFiboStrongBullish = cBar.high < cFib1; - bool isPBarOnFiboStrongBullish = pBar.high < pFib1; - bool isP2BarOnFiboStrongBullish = p2Bar.high < p2Fib1; - bool isP3BarOnFiboStrongBullish = p3Bar.high < p3Fib1; - - // - // Golden Zone Reversal ... - bool isZBarOnFiboGoldenBullish = zBar.low > zFib2 && - zBar.high < zFib3; - bool isCBarOnFiboGoldenBullish = cBar.low > cFib2 && - cBar.high < cFib3; - bool isPBarOnFiboGoldenBullish = pBar.low > pFib2 && - pBar.high < pFib3; - bool isP2BarOnFiboGoldenBullish = p2Bar.low > p2Fib2 && - p2Bar.high < p2Fib3; - bool isP3BarOnFiboGoldenBullish = p3Bar.low > p3Fib2 && - p3Bar.high < p3Fib3; - - // - // Score and Volume Conditions ... - - // - bool isScoreVolumeNeutural = isScoreNeutural || - isVolumeNeutural; - - // - bool isScoreVolumeNeuturalInFiboStrongBullish = - isScoreNeutural && - isCBarOnFiboStrongBullish; - - // - bool isScoreVolumeNeuturalInFiboGoldenBullish = - isScoreNeutural && - isCBarOnFiboGoldenBullish; - - // - bool isScoreVolumeNeuturalInFiboStrongBearish = - isScoreNeutural && - isCBarOnFiboStrongBearish; - - // - bool isScoreVolumeNeuturalInFiboGoldenBearish = - isScoreNeutural && - isCBarOnFiboGoldenBearish; - - // - bool isScoreVolumeNeuturalBullishPowered = - isScoreVolumeNeuturalInFiboStrongBullish || - isScoreVolumeNeuturalInFiboGoldenBullish; - - // - bool isScoreVolumeNeuturalBearishPowered = - isScoreVolumeNeuturalInFiboStrongBearish || - isScoreVolumeNeuturalInFiboGoldenBearish; - - // - // PEAK and VALES ... - - // - // PEAK Pivot ... - bool isZIsPeakPivot = - zPeak == cPeak && - zPeak == zSWH && - zPeak == zResistance && - isZBarOnFiboStrongBearish; - bool isCIsPeakPivot = - cPeak == pPeak && - cPeak == cSWH && - cPeak == cResistance && - isCBarOnFiboStrongBearish; - bool isPIsPeakPivot = - pPeak == p2Peak && - pPeak == pSWH && - pPeak == pResistance && - isPBarOnFiboStrongBearish; - bool isP2IsPeakPivot = - p2Peak == p3Peak && - p2Peak == p2SWH && - p2Peak == p2Resistance && - isP2BarOnFiboStrongBearish; - bool isP3IsPeakPivot = - p3Peak == p4Peak && - p3Peak == p3SWH && - p3Peak == p3Resistance && - isP3BarOnFiboStrongBearish; - - // - // VALE Pivot ... - bool isZIsValePivot = - zVale == cVale && - zVale == zSWL && - zVale == zSupport && - isZBarOnFiboStrongBullish; - bool isCIsValePivot = - cVale == pVale && - cVale == cSWL && - cVale == cSupport && - isCBarOnFiboStrongBullish; - bool isPIsValePivot = - pVale == p2Vale && - pVale == pSWL && - pVale == pSupport && - isPBarOnFiboStrongBullish; - bool isP2IsValePivot = - p2Vale == p3Vale && - p2Vale == p2SWL && - p2Vale == p2Support && - isP2BarOnFiboStrongBullish; - bool isP3IsValePivot = - p3Vale == p4Vale && - p3Vale == p3SWL && - p3Vale == p3Support && - isP3BarOnFiboStrongBullish; - - // - // FIBO Section Change Detection ... - bool isFiboSectionChanged = - // - (cFib1 != pFib1 && - cFib2 != pFib2 && - cFib3 != pFib3 && - cFib4 != pFib4 && - cFib5 != pFib5) - // - && - // - (conditions.isPeakUnderLast || - conditions.isValeOverLast || - conditions.isSwingLowOverLast || - conditions.isSwingHighUnderLast) - // - ; - - // - // SAR Change ... - - // - bool isSarSwitchedInFiboStrongBullish = - isCBarOnFiboStrongBullish && - conditions.isSarSwitchedToBullish; - - // - bool isSarSwitchedInFiboGoldenBullish = - isCBarOnFiboGoldenBullish && - conditions.isSarSwitchedToBullish; - - // - bool isSarSwitchedInFiboStrongBearish = - isCBarOnFiboStrongBearish && - conditions.isSarSwitchedToBearish; - - // - bool isSarSwitchedInFiboGoldenBearish = - isCBarOnFiboGoldenBearish && - conditions.isSarSwitchedToBearish; - - // - bool isSarSwitchedToBullish = - cFastState > 0 && - isSarSwitchedInFiboStrongBullish; - - // - bool isSarSwitchedToBearish = - cFastState < 0 && - isSarSwitchedInFiboStrongBearish; - - // - // RSI Conditions ... - - // - bool isRSICrossedOverOS = - p3RSI < conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel; - - // - bool isRSICrossedUnderOB = - p3RSI > conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel; - - // - // Testing Conditions ... - - // - // Detect Fibo Section Changed ... - if (isFiboSectionChanged) - { - // Print("Fibo Section Changed ..."); - } - - // - // PVPivot Conditions ... - if (isCIsPeakPivot || - isCIsValePivot) - { - // // - // ENUM_X_DIRECTION iPVPivotDir = - // isCIsValePivot - // ? X_DIRECTION_BULLISH - // : X_DIRECTION_BEARISH; - - // // - // int timeOffset = (int)cBar.time; - // string iName = ToString(iPVPivotDir) + "_PVPVT_" + ToString(timeOffset); - // color iColor = isCIsValePivot - // ? clrAqua - // : clrMagenta; - // ENUM_LINE_STYLE iStyle = STYLE_DOT; - - // // - // CChartObjectVLine *iObj; - // iObj = new CChartObjectVLine(); - // has = iObj.Create( - // 0, - // iName, - // 0, - // cBar.time // - // ); - // if (has) - // { - // // - // iObj.Color(iColor); - // iObj.Style(iStyle); - // } - - // // - // Print("Conditions Finder ..."); - } - - // - // Testing Sar Changes ... - if (isSarSwitchedToBullish || - isSarSwitchedToBearish) - { - // - // ENUM_X_DIRECTION iSarChangeDir = - // isSarSwitchedToBullish - // ? X_DIRECTION_BULLISH - // : X_DIRECTION_BEARISH; - - // // - // int timeOffset = (int)cBar.time; - // string iName = ToString(iSarChangeDir) + "_SAR_" + ToString(timeOffset); - // color iColor = isSarSwitchedToBullish - // ? clrAqua - // : clrMagenta; - // ENUM_LINE_STYLE iStyle = STYLE_DOT; - - // // - // CChartObjectVLine *iObj; - // iObj = new CChartObjectVLine(); - // has = iObj.Create( - // 0, - // iName, - // 0, - // cBar.time // - // ); - // if (has) - // { - // // - // iObj.Color(iColor); - // iObj.Style(iStyle); - // } - - // - // Print("Conditions Finder ..."); - } - - // - // Score and Volume Conditions ... - if (isScoreVolumeNeuturalBullishPowered || - isScoreVolumeNeuturalBearishPowered) - { - // - // ENUM_X_DIRECTION iScoreVolumeDir = - // isScoreVolumeNeuturalBullishPowered - // ? X_DIRECTION_BULLISH - // : X_DIRECTION_BEARISH; - - // // - // int timeOffset = (int)cBar.time; - // string iName = ToString(iScoreVolumeDir) + "_SCVM_" + ToString(timeOffset); - // color iColor = isScoreVolumeNeuturalBullishPowered - // ? clrAqua - // : clrMagenta; - // ENUM_LINE_STYLE iStyle = STYLE_DOT; - - // - // CChartObjectVLine *iObj; - // iObj = new CChartObjectVLine(); - // has = iObj.Create( - // 0, - // iName, - // 0, - // cBar.time // - // ); - // if (has) - // { - // // - // iObj.Color(iColor); - // iObj.Style(iStyle); - // } - - // // - // Print("Conditions Finder ..."); - } - - // - // Custom Senarios ... - - // - bool isCond1Bullish = - isBullishOB && - isCIsValePivot && - isRSICrossedOverOS && - !isFiboSectionChanged && - isSarSwitchedToBullish; - - // - bool isCond1Bearish = - isBearishOB && - isCIsPeakPivot && - isRSICrossedUnderOB && - !isFiboSectionChanged && - isSarSwitchedToBearish; - - // - bool isCond1 = - isCond1Bullish || - isCond1Bearish; - if (isCond1) - { - // - ENUM_X_DIRECTION iCond1Dir = - isCond1Bullish - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - - // - int timeOffset = (int)cBar.time; - string iName = ToString(iCond1Dir) + "_COND1_" + ToString(timeOffset); - color iColor = isCond1Bullish - ? clrAqua - : clrMagenta; - ENUM_LINE_STYLE iStyle = STYLE_DOT; - - // - CChartObjectVLine *iObj; - iObj = new CChartObjectVLine(); - has = iObj.Create( - 0, - iName, - 0, - cBar.time // - ); - if (has) - { - // - iObj.Color(iColor); - iObj.Style(iStyle); - } - - // - // Create Signal Box Based on Cond1 ... - - // - double upper = - isCond1Bullish - ? cBar.FindHighest(5, MODE_HIGH) - : MathMax(cPeak, cSWH); - - // - double lower = - isCond1Bullish - ? MathMin(cVale, cSWL) - : cBar.FindLowest(5, MODE_LOW); - - // - int toIDX = cBar.Index(); - int fromIDX = cBar.Index() + 5; - - // - datetime toTime = GetBarTime( - symbol, - period, - toIDX // - ); - datetime fromTime = GetBarTime( - symbol, - period, - fromIDX // - ); - - // - XBoxZone iBox; - - // - iBox.to = toTime; - iBox.upper = upper; - iBox.lower = lower; - iBox.type = "COND1"; - iBox.symbol = symbol; - iBox.period = period; - iBox.dir = iCond1Dir; - iBox.from = fromTime; - - // - has = iBox.IsValid(); - if (has) - { - // - XCBoxObject *iObj; - has = helper - .poiDrawer - .DrawBox( - iBox, - iObj // - ); - if (has) - { - // - // Style Object ... - Print("Salam"); - } - } - - // - box = iBox; - dir = iBox.dir; - - // - iBox.Clean(); - - // - // Print("Conditions Finder ..."); - } - - // - // bool isCond2 = isFiboSectionChanged; - // if (isCond2) - // { - // // - // Print("Decision Zone Full Cond1"); - // } - - // - // Summarise Result ... - - // - bool isBullish = - false || - isCond1Bullish; - - // - bool isBearish = - false || - isCond1Bearish; - - // - result = isBullish || - isBearish; - if (result) - { - // - // Do Signal Preparing ... - - // - // Check Box is Prepared or Not ... - result = box.IsValid(); - } - - // - // Cleaning Up ... - - // - ob.Clean(); - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - if (!result) - { - // - box.Clean(); - conditions.Clean(); - } - - // - return result; -} - -// -// Trigger Conditions ... - -// -// Detect Trigger Based On Decision Zone's -// Volume and Score ... -bool CanTriggerCond0( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - double &tp, - int barIndex = 0, - int loopback = 5, - double scorePassMultiplier = 1 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - // Scores ... - double bullScores[]; - double bearScores[]; - - // - // Volumes ... - double bullVolumes[]; - double bearVolumes[]; - - // - // Create a Loop through Loopack ... - XOHCL iBar; - bool has = false; - int start = barIndex; - XCAEAConditions iConditions; - int end = barIndex + loopback; - for (int i = end; i >= start; i--) - { - // - // Retrieve Bar ... - has = iBar.Init( - box.symbol, - box.period, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Conditions ... - has = helper.GetConditions( - iConditions, - i // - ); - if (!has) - { - // - iBar.Clean(); - iConditions.Clean(); - - // - continue; - } - - // - // Retrieve Scores ... - double iBullScore = 0; - double iBearScore = 0; - iConditions - .GenerateScore( - iBullScore, - iBearScore // - ); - Add( - iBullScore, - bullScores // - ); - Add( - iBearScore, - bearScores // - ); - - // - // Retrieve Volumes ... - double iBullVolume = 0; - double iBearVolume = 0; - helper - .barAnalyser - .CalculateRangeVolume( - iBar, - iBullVolume, - iBearVolume, - 2 // Loopback ... - ); - Add( - iBullVolume, - bullVolumes // - ); - Add( - iBearVolume, - bearVolumes // - ); - - // - iBar.Clean(); - iConditions.Clean(); - } - - // - // Calculating Requirements ... - - // - // Scores ... - - // - // Bullish ... - double bullScore = GetSum(bullScores); - double bullScoreMax = GetMax(bullScores); - double bullScoreMin = GetMin(bullScores); - - // - // Bearish ... - double bearScore = GetSum(bearScores); - double bearScoreMax = GetMax(bearScores); - double bearScoreMin = GetMin(bearScores); - - // - // Volumes ... - - // - // Bullish ... - double bullVolume = GetSum(bullVolumes); - double bullVolumeMax = GetMax(bullVolumes); - double bullVolumeMin = GetMin(bullVolumes); - - // - // Bearish ... - double bearVolume = GetSum(bearVolumes); - double bearVolumeMax = GetMax(bearVolumes); - double bearVolumeMin = GetMin(bearVolumes); - - // - // Creating Result Conditions ... - - // - bool isBullishPassed = - isBullish && - bullScore >= (scorePassMultiplier * bearScore) && - bullVolume >= (scorePassMultiplier * bearVolume); - - // - bool isBearishPassed = - isBearish && - bearScore >= (scorePassMultiplier * bullScore) && - bearVolume >= (scorePassMultiplier * bullVolume); - - // - result = isBullishPassed || - isBearishPassed; - if (!result) - { - // - iBar.Clean(); - Clean(bullScores); - Clean(bearScores); - Clean(bullVolumes); - Clean(bearVolumes); - iConditions.Clean(); - - // - return result; - } - - // - // Validating Box to Find a Rejection ... - - // - // Validating Box to Has a Gap ... - - // - // Validating Box to Has a Block ... - - // - bool isPassed = - isBullishPassed || - isBearishPassed; - if (isPassed) - { - // - // Preparing TP and SL ... - - // - sl = isBullishPassed - ? box.lower - : box.upper; - - // - tp = 0; - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullishPassed; - - // - bool canTriggerShort = - isBearishPassed; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - Clean(bullScores); - Clean(bearScores); - Clean(bullVolumes); - Clean(bearVolumes); - iConditions.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -// Fake Breaked out ... -bool CanTriggerCond1( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - double &tp, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - // Check Box is Faked Breaked Out ... - - // - XBoxZone validatorFVG; - - // - bool isBullishFakedBreakedOut = IsBoxFakedBreakout( - helper, - box, - validatorFVG, - X_DIRECTION_BULLISH, - barIndex, - 100, // Loopback For FVG ... - true, // Force FVg Validation ... - true // Force FVG Bar Type ... - ); - - // - bool isBearishFakedBreakedOut = IsBoxFakedBreakout( - helper, - box, - validatorFVG, - X_DIRECTION_BEARISH, - barIndex, - 100, // Loopback For FVG ... - true, // Force FVg Validation ... - true // Force FVG Bar Type ... - ); - - // - bool isFakeBreaked = - isBullishFakedBreakedOut || - isBearishFakedBreakedOut; - if (isFakeBreaked) - { - // - // Preparing TP and SL ... - - // - sl = isBullishFakedBreakedOut - ? validatorFVG.lower - : validatorFVG.upper; - - // - tp = isBullishFakedBreakedOut - ? box.upper - : box.lower; - } - - // - // Summarizing ... - - // - bool canTriggerLong = - isBullishFakedBreakedOut; - - // - bool canTriggerShort = - isBearishFakedBreakedOut; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - validatorFVG.Clean(); - - // - return result; -} - -// -// Detect Trigger Based On Decision Zone's -// Box Starts With FVG ... -bool CanTriggerCond2( - XCXCAEAHelper *helper, - XBoxZone &box, - ENUM_X_DIRECTION &dir, - double &sl, - double &tp, - int barIndex = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - sl = 0; - tp = 0; - dir = X_DIRECTION_NONE; - loopback = NormalizeInt(loopback, 5); - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - XBoxZone activatedFVG; - bool hasActivatedFVG = IsBoxHasActivatedFVG( - helper, - box, - activatedFVG, - barIndex, - loopback // - ); - - // - bool hasBullishActivatedFVG = - hasActivatedFVG && - activatedFVG.IsBullish(); - - // - bool hasBearishActivatedFVG = - hasActivatedFVG && - activatedFVG.IsBearish(); - - // - if (hasActivatedFVG) - { - // - // Preparing TP and SL ... - - // - sl = hasBullishActivatedFVG - ? box.lower // activatedFVG.lower - : box.upper; // activatedFVG.upper; - - // - // Since Here TP Must Calculated - // Using R2R we Ignore Target ... - tp = 0; - } - - // - // Summarizing ... - - // - bool canTriggerLong = - hasBullishActivatedFVG; - - // - bool canTriggerShort = - hasBearishActivatedFVG; - - // - result = canTriggerLong || - canTriggerShort; - if (result) - { - // - dir = canTriggerLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - } - - // - // Cleanup Resources ... - - // - return result; -} - -// -// Helper Functions ... - -// -// Check a Box is Breaked or Not ... -bool IsBoxBreaked( - XCXCAEAHelper *helper, - XBoxZone &box, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Validate Args ... - result = - box.IsValid() && - helper != NULL; - if (!result) - { - // - // Assume Box Invalid and Breaked - // When Args not Valid ... - result = true; - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - // Assume Box Invalid and Breaked - // When Args not Valid ... - result = true; - - // - return result; - } - - // - // Check Box is Breaked or not ... - // a Box Assume Breakes when at least 3 Bars Close over / under applied Price ... - - // - double appliedPrice = - isBullish - ? box.lower - : box.upper; - - // - bool isBullishBreaked = - isBullish && - cBar.close < appliedPrice && - pBar.close < appliedPrice && - p2Bar.close < appliedPrice; - - // - bool isBearishBreaked = - isBearish && - cBar.close > appliedPrice && - pBar.close > appliedPrice && - p2Bar.close > appliedPrice; - - // - result = isBullishBreaked || - isBearishBreaked; - - // - // Cleanup Resources ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -// Detect Fake Breakout ... -bool IsBoxFakedBreakout( - XCXCAEAHelper *helper, - XBoxZone &box, - XBoxZone &validatorFVG, - ENUM_X_DIRECTION forDir, - int barIndex = 0, - int loopback = 100, - bool forceFVGValidating = false, - bool forceFVGBarType = false // -) -{ - // - bool result = false; - - // - validatorFVG.Clean(); - - // - // Normalizing Args ... - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 10); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL && - (HasDirection(forDir)); - if (!result) - { - return result; - } - - // - double points = GetPoints(box.symbol); - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - - // - // Bar Conditions ... - - // - ENUM_X_DIRECTION barDir; - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - barDir // - ); - bool isCBarBullishEngulfed = - isCBarEngulfed && - IsBullish(barDir); - bool isCBarBearishEngulfed = - isCBarEngulfed && - IsBearish(barDir); - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - barDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isCBarBullishRejected = - isCBarRejected && - IsBullish(barDir); - bool isCBarBearishRejected = - isCBarRejected && - IsBearish(barDir); - - // - bool isCBarHasBullishPower = isCBarBullishRejected || - isCBarBullishEngulfed; - - // - bool isCBarHasBearishPower = isCBarBearishRejected || - isCBarBearishEngulfed; - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - - // - bool lookForBullish = IsBullish(forDir); - bool lookForBearish = IsBearish(forDir); - - // - // Calculate each Direction Breake Price ... - double bullishAppliedPrice = box.lower; - double bearishAppliedPrice = box.upper; - - // - bool isCBarPressedForBullish = - // - isCBarHasBullishPower && - cBar.low < bullishAppliedPrice && - cBar.close > bullishAppliedPrice - // - ; - - // - bool isCBarPressedForBearish = - // - isCBarHasBearishPower && - cBar.high > bearishAppliedPrice && - cBar.close < bearishAppliedPrice - // - ; - - // - bool isPBarBreakedBullishAppliedPrice = - pBar.low < bullishAppliedPrice && - pBar.high > bullishAppliedPrice; - - // - bool isPBarBreakedBearishAppliedPrice = - pBar.low < bearishAppliedPrice && - pBar.high > bearishAppliedPrice; - - // - bool isP2BarBreakedBullishAppliedPrice = - p2Bar.low < bullishAppliedPrice && - p2Bar.high > bullishAppliedPrice; - - // - bool isP2BarBreakedBearishAppliedPrice = - p2Bar.low < bearishAppliedPrice && - p2Bar.high > bearishAppliedPrice; - - // - bool isBullishAppliedPriceBreaked = - isPBarBreakedBullishAppliedPrice || - isP2BarBreakedBullishAppliedPrice; - - // - bool isBearishAppliedPriceBreaked = - isPBarBreakedBearishAppliedPrice || - isP2BarBreakedBearishAppliedPrice; - - // - bool isBullishFakeBreakedOut = - lookForBullish && - isCBarPressedForBullish && - isBullishAppliedPriceBreaked; - - // - bool isBearishFakeBreakedOut = - lookForBearish && - isCBarPressedForBearish && - isBearishAppliedPriceBreaked; - - // - result = isBullishFakeBreakedOut || - isBearishFakeBreakedOut; - - // - // Validating Using FVG if necessary ... - if (forceFVGValidating) - { - // - // Detecting All FVGs Which Placed in Box till Loopback ... - XBoxZone fvg; - - // - XOHCL iBar; - bool has = false; - int start = cBar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - // Initialize Bar ... - has = iBar.Init( - cBar.symbol, - cBar.period, - i // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check FVG ... - has = helper - .barAnalyser - .IsFVG( - iBar, - fvg, - forceFVGBarType // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - bool isBullishFVG = - fvg.IsBullish() && - isBullishFakeBreakedOut; - - // - bool isBearishFVG = - fvg.IsBearish() && - isBearishFakeBreakedOut; - - // - // Checking FVG Dir ... - has = isBullishFVG || - isBearishFVG; - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check CBar Must Inside FVG ... - - // - bool isFVGBullishBreaked = - isBullishFVG && - cBar.low < fvg.upper && - cBar.close > fvg.upper && - isBullishFakeBreakedOut; - - // - bool isFVGBearishBreaked = - isBearishFVG && - cBar.high > fvg.lower && - cBar.close < fvg.lower && - isBearishFakeBreakedOut; - - // - has = - isFVGBullishBreaked || - isFVGBearishBreaked; - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - result = - result && - fvg.IsValid(); - if (result) - { - // - fvg.to = cBar.time; - - // - // Check FVG Size ... - double fvgRange = fvg.upper - fvg.lower; - bool canApplyLastBar = fvgRange < (5 * points); - if (canApplyLastBar) - { - // - // Retrieve FVG Start Bar ... - XOHCL fvgStartBar; - has = fvgStartBar.Init( - cBar.symbol, - cBar.period, - cBar.Index() + 3 // - ); - if (has) - { - // - if (fvg.IsBullish()) - { - fvg.lower = fvgStartBar.low; - } - else - { - fvg.upper = fvgStartBar.high; - } - } - - // - fvgStartBar.Clean(); - } - - // - validatorFVG = fvg; - - // - XCBoxObject *iObj; - has = helper.poiDrawer.DrawBox( - fvg, - iObj // - ); - ZeroMemory(iObj); - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - // Cleanup Resources ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -// Detect Activated FVG ... -bool IsBoxHasActivatedFVG( - XCXCAEAHelper *helper, - XBoxZone &box, - XBoxZone &fvg, - int barIndex = 0, - int loopback = 10, - bool forceFVGBarType = false // -) -{ - // - bool result = false; - - // - fvg.Clean(); - - // - // Normalize Args ... - barIndex = NormalizeInt(barIndex, 0); - loopback = NormalizeInt(loopback, 10); - - // - // Validate Decision Box ... - result = box.IsValid() && - helper != NULL; - if (!result) - { - return result; - } - - // - bool isBullish = box.IsBullish(); - bool isBearish = box.IsBearish(); - double points = GetPoints(box.symbol); - - // - // Retrieve Conditions ... - XCAEAConditions conditions; - result = helper.GetConditions( - conditions, - barIndex, - loopback // - ); - if (!result) - { - // - conditions.Clean(); - - // - return result; - } - - // - // Extract Bars ... - - // - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - - // - result = cBar.Init( - box.symbol, - box.period, - barIndex + 1 // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - conditions.Clean(); - - // - return result; - } - - // - // Find FVG ... - - // - XOHCL iBar; - bool has = false; - int start = cBar.Index(); - int end = start + loopback; - for (int i = start; i < end; i++) - { - // - // Initialize Bar ... - has = iBar.Init( - cBar.symbol, - cBar.period, - i // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - }; - - // - // Check FVG ... - has = helper - .barAnalyser - .IsFVG( - iBar, - fvg, - forceFVGBarType // - ); - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Validate FVG ... - has = - // - fvg.IsValid() && - fvg.dir == box.dir && - fvg.from > box.from && - fvg.upper <= box.upper && - fvg.lower >= box.lower - // - ; - if (!has) - { - // - fvg.Clean(); - iBar.Clean(); - - // - continue; - } - - // - // Check CBar FVG Validations ... - - // - bool isCBarBullishRejected = - isBullish && - cBar.low < fvg.upper && - cBar.close > fvg.upper; - - // - bool isCBarBearishRejected = - isBearish && - cBar.high > fvg.lower && - cBar.close < fvg.lower; - - // - has = isCBarBullishRejected || - isCBarBearishRejected; - if (has) - { - // - iBar.Clean(); - - // - break; - } - - // - fvg.Clean(); - iBar.Clean(); - } - - // - result = fvg.IsValid(); - if (result) - { - // - fvg.to = cBar.time; - - // - // Check FVG Size ... - double fvgRange = fvg.upper - fvg.lower; - bool canApplyLastBar = true; - // fvgRange < (5 * points); - if (canApplyLastBar) - { - // - // Retrieve FVG Start Bar ... - XOHCL fvgStartBar; - has = fvgStartBar.Init( - cBar.symbol, - cBar.period, - cBar.Index() + 4 // - ); - if (has) - { - // - if (fvg.IsBullish()) - { - fvg.lower = fvgStartBar.low; - } - else - { - fvg.upper = fvgStartBar.high; - } - } - - // - fvgStartBar.Clean(); - } - - // - XCBoxObject *iObj; - helper.poiDrawer.DrawBox( - fvg, - iObj // - ); - ZeroMemory(iObj); - } - - // - // Cleanup Resources ... - - // - iBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - conditions.Clean(); - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/xcaea.trigger.block.lib.mq5 b/Documents/BKP/xcaea.trigger.block.lib.mq5 deleted file mode 100644 index 82abbc74..00000000 --- a/Documents/BKP/xcaea.trigger.block.lib.mq5 +++ /dev/null @@ -1,1487 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCAEAHelper Lib -// Description: Library for XCAEA Signaller ... -// -// -// 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 Library for XCAEA Helper" -#property strict - -// -// Imports ... -#include "../../Libraries/x-saherelm.common.lib.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Definitions ... -enum ENUM_XCAEA_TIGGER_TYPE -{ - XCA_TRIGGER_NONE, // None - XCA_TRIGGER_BULL, // TriggerBull - XCA_TRIGGER_BEAR, // TriggerBear -}; - -// -bool IsValid(ENUM_XCAEA_TIGGER_TYPE value) -{ - return value != XCA_TRIGGER_NONE; -} - -// -string ToString(ENUM_XCAEA_TIGGER_TYPE value) -{ - return EnumToString(value); -} - -// -ENUM_XCAEA_TIGGER_TYPE GetType(string type) -{ - // - ENUM_XCAEA_TIGGER_TYPE result = XCA_TRIGGER_NONE; - - // - bool isTriggerBull = type == ToString(XCA_TRIGGER_BULL); - bool isTriggerBear = type == ToString(XCA_TRIGGER_BEAR); - - // - if (isTriggerBull) - { - result = XCA_TRIGGER_BULL; - } - else if (isTriggerBear) - { - result = XCA_TRIGGER_BEAR; - } - - // - return result; -} - -// -ENUM_X_DIRECTION GetDirection(ENUM_XCAEA_TIGGER_TYPE value) -{ - return value == XCA_TRIGGER_BULL - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; -} - -// -// Structues ... -struct XCAEATriggerBlockConfiguration -{ - // - // Props ... - - // - // Trigger Detection ... - - // - double maxAllowedRange; // Maximum Allowed Range - int minAllowedBlockEdgeLength; // Minimum Required Block Edge Length - - // - // Validation ... - bool forceOBOppositBar; // Force OB to Start by Opposit Bars - bool forceFVGBarType; // Force FVG to Has Same Type of Bars - bool forceGapBarBreakout; // Force FVG's Gap Bar to Breakeout OB Edge Side - bool forceHasSwingBar; // Force Has Propper Swing - bool forceHasLiquidity; // Force Has Following Liquidity Zone - bool forceHasReversalLiquidity; // Force Has Reversal Liquidity Zone - - // - // Filtering ... - bool filterBasedOnSar; // Filter Trigger Block Based on Sar - bool filterBasedOnRSI; // Filter Trigger Block Based on RSI - bool filterBasedOnADX; // Filter Trigger Block Based on ADX - bool filterBasedOnTrend; // Filter Trigger Block Based on Trend - bool filterBasedOnScores; // Filter Trigger Block Based on Scores - bool filterBasedOnVolumes; // Filter Trigger Block Based on Volumes - - // - double targets[]; // Targets Collection for R:R on Signal Preparation - - // - // Constructor ... - XCAEATriggerBlockConfiguration() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - // Validating ... - maxAllowedRange = false; - minAllowedBlockEdgeLength = false; - - // - forceOBOppositBar = false; - forceFVGBarType = false; - forceGapBarBreakout = false; - forceHasSwingBar = false; - forceHasLiquidity = false; - forceHasReversalLiquidity = false; - - // - // Filtering ... - filterBasedOnSar = false; - filterBasedOnRSI = false; - filterBasedOnADX = false; - filterBasedOnTrend = false; - filterBasedOnScores = false; - filterBasedOnVolumes = false; - - // - Clean(targets); - - // - ZeroMemory(this); - } - - // - // Preset Configurations ... - - // -}; - -// -struct XTriggerBlock -{ - // - // Props ... - XBoxZone ob; // Order Block - XBoxZone fvg; // Fair Value Gap - XOHCL swingBar; // Swing of Trigger - XBoxZone trigger; // Trigger Block - XBoxZone rLiquidity; // Reversal Liquidity - XBoxZone fLiquidity; // Following Liquidity - XCAEAConditions conditions; // Market Conditions - XCAEATriggerBlockConfiguration configuration; // Detection Configuration - - // - XSignal signal; // Pepared Signal - - // - // Constructor ... - XTriggerBlock() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - ob.Clean(); - fvg.Clean(); - signal.Clean(); - trigger.Clean(); - swingBar.Clean(); - rLiquidity.Clean(); - fLiquidity.Clean(); - conditions.Clean(); - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = ob.IsValid() && - fvg.IsValid() && - trigger.IsValid(); - - // - return result; - } - - // -}; - -// -// Extensions ... - -/** - * Detect Trigger Block ... - * - * @param trigger: XTriggerBlock instance Reference, hold founded Trigger Block - * @param helper: XCXCAEAHelper instance Reference Pointer, XCAEA Market nalyser Helper for acc Drawer - * @param config: XCAEATriggerBlockConfiguration instance Reference, Trigger Block Detecting Configuration - * @param bar_index: int, Bar Index to Start Detecting - * @param loopback: int, Loopback Bars Count - * - * @return ( bool ) - */ -bool DetectTriggerBlock( - XTriggerBlock &trigger, - XCXCAEAHelper *helper, - XCAEATriggerBlockConfiguration &config, - int bar_index = 0, - int loopback = 10, - double slAdditionalPoint = 0, - double slATRMultiplier = 0 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - trigger.Clean(); - loopback = NormalizeInt(loopback, 10); - bar_index = NormalizeInt(bar_index, 0); - - // - // Validate Args ... - result = helper != NULL; - if (!result) - { - return result; - } - - // - // Extract Required Informations ... - - // - string symbol = helper.GetSymbol(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - double points = GetPoints(symbol); - - // - // Retrieve Indexed Bar ... - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - result = zBar.Init( - symbol, - period, - bar_index // - ); - result = result && - zBar.GetPreviousBar(cBar); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - // Check Trigger Block Exists ... - result = - result && - helper - .barAnalyser - .IsTrigger( - zBar, - trigger.trigger, - trigger.ob, - trigger.fvg, - trigger.rLiquidity, - trigger.fLiquidity, - trigger.swingBar, - loopback, - config.maxAllowedRange, - config.minAllowedBlockEdgeLength, - config.forceOBOppositBar, - config.forceFVGBarType, - config.forceGapBarBreakout, - config.forceHasSwingBar, - config.forceHasLiquidity, - config.forceHasReversalLiquidity // - ); - - // - // Now we Have to Implement Required Validations ... - - // - bool isBullish = trigger.trigger.IsBullish(); - bool isBearish = trigger.trigger.IsBearish(); - - // - // First Reading Market Conditions ... - result = - result && - helper.GetConditions( - trigger.conditions, - bar_index, - loopback // - ); - - // - // All Custom andAdditional Validations and Filters - // Applied here ... - - // - // SAR Filter ... - if (config.filterBasedOnSar) - { - // - if (result) - { - // - // Reading Values ... - - // - double zSar = trigger.conditions.sarBuffer[zIDX]; - double cSar = trigger.conditions.sarBuffer[cIDX]; - double pSar = trigger.conditions.sarBuffer[pIDX]; - double p2Sar = trigger.conditions.sarBuffer[p2IDX]; - double p3Sar = trigger.conditions.sarBuffer[p3IDX]; - double p4Sar = trigger.conditions.sarBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFilterd = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // RSI Filter ... - if (config.filterBasedOnRSI) - { - // - if (result) - { - // - // Reading Values ... - - // - double rsiTrend = (trigger.conditions.rsiOBLevel + trigger.conditions.rsiOSLevel) / 2; - - // - double zRSI = trigger.conditions.rsiBuffer[zIDX]; - double cRSI = trigger.conditions.rsiBuffer[cIDX]; - double pRSI = trigger.conditions.rsiBuffer[pIDX]; - double p2RSI = trigger.conditions.rsiBuffer[p2IDX]; - double p3RSI = trigger.conditions.rsiBuffer[p3IDX]; - double p4RSI = trigger.conditions.rsiBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > trigger.conditions.rsiOSLevel && - cRSI > trigger.conditions.rsiOSLevel && - pRSI <= trigger.conditions.rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < trigger.conditions.rsiOBLevel && - cRSI < trigger.conditions.rsiOBLevel && - pRSI >= trigger.conditions.rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > trigger.conditions.rsiOSLevel && - cRSI > trigger.conditions.rsiOSLevel && - pRSI > trigger.conditions.rsiOSLevel && - p2RSI <= trigger.conditions.rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < trigger.conditions.rsiOBLevel && - cRSI < trigger.conditions.rsiOBLevel && - pRSI < trigger.conditions.rsiOBLevel && - p2RSI >= trigger.conditions.rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // ADX Filter ... - if (config.filterBasedOnADX) - { - // - if (result) - { - // - // Reading Values ... - - // - // ADX ... - double zADX = trigger.conditions.adxBuffer[zIDX]; - double cADX = trigger.conditions.adxBuffer[cIDX]; - double pADX = trigger.conditions.adxBuffer[pIDX]; - double p2ADX = trigger.conditions.adxBuffer[p2IDX]; - double p3ADX = trigger.conditions.adxBuffer[p3IDX]; - double p4ADX = trigger.conditions.adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = trigger.conditions.adxpBuffer[zIDX]; - double cADXP = trigger.conditions.adxpBuffer[cIDX]; - double pADXP = trigger.conditions.adxpBuffer[pIDX]; - double p2ADXP = trigger.conditions.adxpBuffer[p2IDX]; - double p3ADXP = trigger.conditions.adxpBuffer[p3IDX]; - double p4ADXP = trigger.conditions.adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = trigger.conditions.adxnBuffer[zIDX]; - double cADXN = trigger.conditions.adxnBuffer[cIDX]; - double pADXN = trigger.conditions.adxnBuffer[pIDX]; - double p2ADXN = trigger.conditions.adxnBuffer[p2IDX]; - double p3ADXN = trigger.conditions.adxnBuffer[p3IDX]; - double p4ADXN = trigger.conditions.adxnBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > trigger.conditions.adxThreshold; - bool isZADXBearish = zADX < trigger.conditions.adxThreshold; - - // - bool isCADXBullish = cADX > trigger.conditions.adxThreshold; - bool isCADXBearish = cADX < trigger.conditions.adxThreshold; - - // - bool isPADXBullish = pADX > trigger.conditions.adxThreshold; - bool isPADXBearish = pADX < trigger.conditions.adxThreshold; - - // - bool isP2ADXBullish = p2ADX > trigger.conditions.adxThreshold; - bool isP2ADXBearish = p2ADX < trigger.conditions.adxThreshold; - - // - bool isP3ADXBullish = p3ADX > trigger.conditions.adxThreshold; - bool isP3ADXBearish = p3ADX < trigger.conditions.adxThreshold; - - // - bool isP4ADXBullish = p4ADX > trigger.conditions.adxThreshold; - bool isP4ADXBearish = p4ADX < trigger.conditions.adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // TREND Filter ... - if (config.filterBasedOnTrend) - { - // - if (result) - { - // - // Reading Values ... - - // - double zTrend = trigger.conditions.trendBuffer[zIDX]; - double cTrend = trigger.conditions.trendBuffer[cIDX]; - double pTrend = trigger.conditions.trendBuffer[pIDX]; - double p2Trend = trigger.conditions.trendBuffer[p2IDX]; - double p3Trend = trigger.conditions.trendBuffer[p3IDX]; - double p4Trend = trigger.conditions.trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = trigger.conditions.trendStateBuffer[zIDX]; - double cTrendState = trigger.conditions.trendStateBuffer[cIDX]; - double pTrendState = trigger.conditions.trendStateBuffer[pIDX]; - double p2TrendState = trigger.conditions.trendStateBuffer[p2IDX]; - double p3TrendState = trigger.conditions.trendStateBuffer[p3IDX]; - double p4TrendState = trigger.conditions.trendStateBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // SCORE Filter ... - if (config.filterBasedOnScores) - { - // - if (result) - { - // - // Reading Values ... - - // - double bullishScore = 0; - double bearishScore = 0; - - // - trigger.conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - // Preparing Conditions ... - - // - bool isScoreBullish = bullishScore > bearishScore; - bool isScoreBearish = bearishScore > bullishScore; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - isScoreBullish; - - // - bool isBearishFilterd = - isBearish && - isScoreBearish; - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // VOLUME Filter ... - if (config.filterBasedOnVolumes) - { - // - if (result) - { - // - // Reading Values ... - - // - double bullishVolume = 0; - double bearishVolume = 0; - - // - helper - .barAnalyser - .CalculateRangeVolume( - zBar, - bullishVolume, - bearishVolume, - loopback // - ); - - // - // Preparing Conditions ... - - // - bool isVolumeBullish = bullishVolume > bearishVolume; - bool isVolumeBearish = bearishVolume > bullishVolume; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - isVolumeBullish; - - // - bool isBearishFilterd = - isBearish && - isVolumeBearish; - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - - // - if (!result) - { - trigger.Clean(); - } - - // - // Attach Configuration if Trigger Block Founded ... - if (result) - { - // - trigger.configuration = config; - - // - // Prepare Trigger Signal ... - if (HasChild(config.targets)) - { - // - // Calculating Additional SL Value for Signals ... - double additionalSL = 0; - if (slATRMultiplier > 0) - { - // - double cATR = trigger.conditions.atrBuffer[cIDX]; - additionalSL += (cATR * slATRMultiplier); - } - if (slAdditionalPoint > 0) - { - additionalSL += (slAdditionalPoint * points); - } - - // - ToSignal( - trigger.trigger, - trigger.signal, - config.targets, - additionalSL // - ); - } - } - - // - return result; -} - -/** - * Draw Specified Trigger Block ... - * - * @param trigger: XTriggerBlock instance Reference, specified Trigger Block to Draw - * @param objects: CArrayObj instance Reference Pointer, Objects Array for Providing Drawn Objects - * @param helper: XCXCAEAHelper instance Reference Pointer, XCAEA Market nalyser Helper for acc Drawer - * @param to: datetime, specified Time for update Trigger parts - * - * @return ( bool ) - */ -bool DrawTriggerBlock( - XTriggerBlock &trigger, - CArrayObj *&objects, - XCXCAEAHelper *helper, - datetime to = NULL, - int rrZoneLength = 10 // -) -{ - // - bool result = false; - - // - // Validate Args ... - result = helper != NULL && - trigger.IsValid(); - if (!result) - { - return result; - } - - // - // Update To ... - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - // - trigger.trigger.to = to; - trigger.rLiquidity.to = to; - trigger.fLiquidity.to = to; - } - - // - // Draw OB ... - if (trigger.ob.IsValid()) - { - // - XCBoxObject *iOBObj; - result = helper.poiDrawer.DrawBox( - trigger.ob, - iOBObj // - ); - if (result) - { - objects.Add(iOBObj); - } - ZeroMemory(iOBObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw FVG ... - if (trigger.fvg.IsValid()) - { - // - XCBoxObject *iFVGObj; - result = helper.poiDrawer.DrawBox( - trigger.fvg, - iFVGObj // - ); - if (result) - { - // - // Style Object ... - color clr = - trigger.fvg.IsBullish() - ? clrAqua - : clrMagenta; - iFVGObj.BoxWidth(2); - iFVGObj.BoxColor(clr); - iFVGObj.BoxStyle(STYLE_SOLID); - - // - // Store Object ... - objects.Add(iFVGObj); - } - ZeroMemory(iFVGObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Trigger ... - if (trigger.trigger.IsValid()) - { - // - XCBoxObject *iTriggerObj; - result = helper.poiDrawer.DrawBox( - trigger.trigger, - iTriggerObj // - ); - if (result) - { - objects.Add(iTriggerObj); - } - ZeroMemory(iTriggerObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Liquidities ... - - // - // Reversla Liquidity ... - if (trigger.rLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = helper.poiDrawer.DrawBox( - trigger.rLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Following Liquidity ... - if (trigger.fLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = helper.poiDrawer.DrawBox( - trigger.fLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Swing Bar ... - if (trigger.swingBar.IsValid()) - { - // - color swingColor = - trigger.fvg.IsBullish() - ? clrAqua - : clrMagenta; - ENUM_X_PRICE swingPType = - trigger.fvg.IsBullish() - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - XCBarArrowObject *swingObj; - result = helper.poiDrawer.CreateBarArrow( - trigger.swingBar, - swingObj, - swingPType, - 159, - swingColor // - ); - if (result) - { - objects.Add(swingObj); - } - ZeroMemory(swingObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw RR of Signal ... - if (trigger.signal.IsValid() && - rrZoneLength > 0) - { - // - XCRRObject *iRRObj; - iRRObj = new XCRRObject(); - result = iRRObj.Create( - helper.poiDrawer.ChartIdentification(), - helper.poiDrawer.SubWindowIdentification(), - trigger.signal, - rrZoneLength // - ); - if (result) - { - // - int iWidth = 2; - ENUM_LINE_STYLE iStyle = STYLE_SOLID; - - // - iRRObj.TPWidth(iWidth); - iRRObj.SLWidth(iWidth); - iRRObj.EntryWidth(iWidth); - iRRObj.TargetWidth(iWidth); - - // - iRRObj.TPStyle(iStyle); - iRRObj.SLStyle(iStyle); - iRRObj.EntryStyle(iStyle); - iRRObj.TargetStyle(iStyle); - - // - iRRObj.TPColor(clrLime); - iRRObj.SLColor(clrRed); - iRRObj.EntryColor(clrYellow); - iRRObj.TargetColor(clrLightBlue); - - // - objects.Add(iRRObj); - } - ZeroMemory(iRRObj); - - // - if (result) - { - return result; - } - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/xcaea.trigger.block.lib.old.mq5 b/Documents/BKP/xcaea.trigger.block.lib.old.mq5 deleted file mode 100644 index c3b7877f..00000000 --- a/Documents/BKP/xcaea.trigger.block.lib.old.mq5 +++ /dev/null @@ -1,4122 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCAEAHelper Lib -// Description: Library for XCAEA Signaller ... -// -// -// 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 Library for XCAEA Helper" -#property strict - -// -// Imports ... -#include "../../Libraries/x-saherelm.common.lib.mq5" -#include "../Classes/xcaea.x-poi.detector.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Definitions ... -enum ENUM_XCAEA_TIGGER_TYPE -{ - XCA_TRIGGER_NONE, // None - XCA_TRIGGER_BULL, // TriggerBull - XCA_TRIGGER_BEAR, // TriggerBear -}; - -// -bool IsValid(ENUM_XCAEA_TIGGER_TYPE value) -{ - return value != XCA_TRIGGER_NONE; -} - -// -string ToString(ENUM_XCAEA_TIGGER_TYPE value) -{ - return EnumToString(value); -} - -// -ENUM_XCAEA_TIGGER_TYPE GetType(string type) -{ - // - ENUM_XCAEA_TIGGER_TYPE result = XCA_TRIGGER_NONE; - - // - bool isTriggerBull = type == ToString(XCA_TRIGGER_BULL); - bool isTriggerBear = type == ToString(XCA_TRIGGER_BEAR); - - // - if (isTriggerBull) - { - result = XCA_TRIGGER_BULL; - } - else if (isTriggerBear) - { - result = XCA_TRIGGER_BEAR; - } - - // - return result; -} - -// -ENUM_X_DIRECTION GetDirection(ENUM_XCAEA_TIGGER_TYPE value) -{ - return value == XCA_TRIGGER_BULL - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; -} - -// -// Structues ... -struct XCAEATriggerBlockConfiguration -{ - // - // Props ... - - // - // Trigger Detection ... - - // - double maxAllowedRange; // Maximum Allowed Range - int minAllowedBlockEdgeLength; // Minimum Required Block Edge Length - - // - bool forceOBOppositBar; // Force OB to Start by Opposit Bars - bool forceFVGBarType; // Force FVG to Has Same Type of Bars - bool forceGapBarBreakout; // Force FVG's Gap Bar to Breakeout OB Edge Side - bool forceHasSwingBar; // Force Has Propper Swing - bool forceHasLiquidity; // Force Has Following Liquidity Zone - bool forceHasReversalLiquidity; // Force Has Reversal Liquidity Zone - - // - // Validating ... - int minZoneLength; // Minimum Length of Consolidation Zone - bool forceHasSwing; // Force Zone's Has Propper Swing - bool forceHasPinBarEntry; // Force Zone's Ends with a Pin Bar - bool forceGapBarsBreakout; // Force Zone's Gap Bar's Breakes Out - double maxZoneRangeInPoints; // Max Zone Range in Point - double maxAllowedEntryDistance; // Max Allowed Entry Distance - - // - // Filtering ... - bool filterBasedOnSar; // Filter Trigger Block Based on Sar - bool filterBasedOnRSI; // Filter Trigger Block Based on RSI - bool filterBasedOnADX; // Filter Trigger Block Based on ADX - bool filterBasedOnTrend; // Filter Trigger Block Based on Trend - bool filterBasedOnScores; // Filter Trigger Block Based on Scores - bool filterBasedOnVolumes; // Filter Trigger Block Based on Volumes - - // - // Constructor ... - XCAEATriggerBlockConfiguration() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - - // - // Validating ... - minZoneLength = 0; - forceHasSwing = false; - maxZoneRangeInPoints = 0.0; - forceHasPinBarEntry = false; - forceGapBarsBreakout = false; - maxAllowedEntryDistance = 0.0; - - // - // Filtering ... - filterBasedOnSar = false; - filterBasedOnRSI = false; - filterBasedOnADX = false; - filterBasedOnTrend = false; - - // - ZeroMemory(this); - } - - // - // Preset Configurations ... - - // - // Commons Verifications which used in all - // Preset Configurations ... - void ConfigureCommons() - { - // - minZoneLength = 7; - forceHasSwing = true; - maxZoneRangeInPoints = 70; - forceHasPinBarEntry = true; - forceGapBarsBreakout = true; - maxAllowedEntryDistance = 30; - } - - // - // Cleanup Range Verifications ... - void CleanRanges() - { - // - maxZoneRangeInPoints = 0; - maxAllowedEntryDistance = 0; - } - - // - void ConfigureFullFilter() - { - // - // Apply Common Configurations ... - ConfigureCommons(); - - // - // Apply Full Filters ... - filterBasedOnSar = true; - filterBasedOnRSI = true; - filterBasedOnADX = true; - filterBasedOnTrend = true; - } - - // - void ConfigureFullFilterNoRange() - { - // - // Apply Common Configurations ... - ConfigureCommons(); - - // - // Clean Ranges ... - CleanRanges(); - - // - // Apply Full Filters ... - filterBasedOnSar = true; - filterBasedOnRSI = true; - filterBasedOnADX = true; - filterBasedOnTrend = true; - } - - // - void ConfigureSarRsiAdxFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnTrend = false; - } - - // - void ConfigureSarRsiTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnADX = false; - } - - // - void ConfigureSarAdxTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnRSI = false; - } - - // - void ConfigureRsiAdxTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnSar = false; - } - - // - void ConfigureSarRsiFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnADX = false; - filterBasedOnTrend = false; - } - - // - void ConfigureSarAdxFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnRSI = false; - filterBasedOnTrend = false; - } - - // - void ConfigureSarTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnRSI = false; - filterBasedOnADX = false; - } - - // - void ConfigureRsiAdxFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnSar = false; - filterBasedOnTrend = false; - } - - // - void ConfigureRsiTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnSar = false; - filterBasedOnADX = false; - } - - // - void ConfigureAdxTrendFilter() - { - // - ConfigureFullFilter(); - - // - filterBasedOnSar = false; - filterBasedOnRSI = false; - } - - // -}; - -// -struct XTriggerBlock -{ - // - // Props ... - XBoxZone ob; // Order Block - XBoxZone fvg; // Fair Value Gap - XOHCL swingBar; // Swing of Trigger - XBoxZone trigger; // Trigger Block - XBoxZone rLiquidity; // Reversal Liquidity - XBoxZone fLiquidity; // Following Liquidity - XCAEAConditions conditions; // Market Conditions - XCAEATriggerBlockConfiguration configuration; // Detection Configuration - - // - // Constructor ... - XTriggerBlock() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - ob.Clean(); - fvg.Clean(); - trigger.Clean(); - swingBar.Clean(); - rLiquidity.Clean(); - fLiquidity.Clean(); - conditions.Clean(); - - // - ZeroMemory(this); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = ob.IsValid() && - fvg.IsValid() && - trigger.IsValid(); - - // - return result; - } - - // -}; - -// -// Extensions ... - -/** - * Detect a Trigger Block ... - * - * @param triggerBlock: XBoxZone instance reference, The Detected Trigger Block ... - * @param conditions: XCAEAConditions instance reference, The Block Verification Conditions ... - * @param helper: XCXCAEAHelper instance pointer, Specified The Helper Class Instance which used to Detect Conditions ... - * @param config: XCAEATriggerBlockConfiguration instance reference, Specified The Trigger Block Detection Configuration ... - * @param bar_index: int, Specified The Bar Index to Start Detection ... - * @param loopback: int, Specified The Loopback Length to Detect Helper Conditions ... - * - * @return ( bool ) - */ -bool DetectTriggerBlock( - XBoxZone &triggerBlock, - XCAEAConditions &conditions, - XCXCAEAHelper *helper, - XCAEATriggerBlockConfiguration &config, - int bar_index = 0, - int loopback = 6 // -) -{ - // - bool result = false; - - // - conditions.Clean(); - triggerBlock.Clean(); - - // - // Normalize Args ... - loopback = NormalizeInt(loopback, 6); - bar_index = NormalizeInt(bar_index, 0); - - // - // Validate Args ... - result = helper != NULL; - if (!result) - { - return result; - } - - // - // Provide base Requirements ... - - // - string symbol = helper.GetSymbol(); - double points = GetPoints(symbol); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Conditions Reading Indexes ... - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - double ll = 0; - double hh = 0; - bool has = false; - ENUM_X_DIRECTION iDir; - - // - // Retrieve Current Conditions ... - result = helper.GetConditions( - conditions, - bar_index, - loopback // - ); - - // - // Retrieve Required Bars ... - - // - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - XOHCL cBar; // Current Finished Bar which Start Detecting Structures based on it ( End of Block and FVG Bar ) ... - XOHCL pBar; // Determines Block Gap Bar (all Filtering must applied and Check using this Bar and it's Next Bar) ... - XOHCL p2Bar; // Determines FVG's Start Bar in a Block ... - XOHCL p3Bar; // First Verification of Block ... - XOHCL p4Bar; // Seccond Verification of Block ... - - // - result = zBar.Init( - symbol, - period, - bar_index // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - pBar.GetPreviousBar(p2Bar); - result = - result && - p2Bar.GetPreviousBar(p3Bar); - result = - result && - p3Bar.GetPreviousBar(p4Bar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - - // - // Detect Based Order Block using CBar ... - result = - helper - .barAnalyser - .IsOB( - cBar, - triggerBlock, - true, // Force FVG Bar Type ... - true // Force Block Two Bar Checking ... - ); - - // - // Ensure a Block is Detected ... - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - - // - // Reading Some Block Based Requirements ... - - // - bool isBullish = - result && - triggerBlock.IsBullish(); - - // - bool isBearish = - result && - triggerBlock.IsBearish(); - - // - int toIDX = triggerBlock.ToIndex(); - int fromIDX = triggerBlock.FromIndex(); - - // - // Start Validating ... - - // - // Validating p2Bar and p3Bar Direction ... - if (result) - { - // - iDir = Opposit(triggerBlock.dir); - - // - result = - iDir == p3Bar.GetDirection() || - iDir == p4Bar.GetDirection(); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Using Max Range ... - result = config.maxZoneRangeInPoints > 0; - if (result) - { - // - double range = triggerBlock.GetRange(); - result = range <= config.maxZoneRangeInPoints * points; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validate Gap Endup with PinBar ... - result = config.forceHasPinBarEntry; - if (result) - { - // - bool isBullishRejected = - isBullish && - cBar.IsBullish() && - cBar.GetLowShadow() > cBar.GetHighShadow(); - - // - bool isBearishRejected = - isBearish && - cBar.IsBearish() && - cBar.GetLowShadow() < cBar.GetHighShadow(); - - // - result = isBullishRejected || - isBearishRejected; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Gap Bar must a Momentum Bar and - // Breakes out Zone's Directional Edge ... - // for Bullish: Upper - // for Bearish: Lower - result = config.forceGapBarsBreakout; - if (result) - { - // - // Gap Bar is PBar ... - - // - // Check Gap Bar is Momentum Bar ... - result = - helper - .barAnalyser - .IsMomentum( - pBar, - iDir // - ); - bool isBullishMomentum = - result && - IsBullish(iDir); - bool isBearishMomentum = - result && - IsBearish(iDir); - - // - // Check Gap Bar's Breakout ... - - // - bool isBullishBreakedout = - isBullish && - pBar.IsBullish() && - isBullishMomentum && - pBar.GetUp() > triggerBlock.upper && - pBar.GetDown() < triggerBlock.upper; - - // - bool isBearishBreakedout = - isBearish && - pBar.IsBearish() && - isBearishMomentum && - pBar.GetUp() > triggerBlock.lower && - pBar.GetDown() < triggerBlock.lower; - - // - result = isBullishBreakedout || - isBearishBreakedout; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validate Zone Has Propper Swing ... - // for Bullish: p2Bar or p3Bar must be a Swing Low ... - // for Bearish: p2Bar or p3Bar must be a Swing High ... - result = config.forceHasSwing; - if (result) - { - // - // p2Bar ... - bool isP2BarSwing = - helper - .barAnalyser - .IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarSwingLow = - isP2BarSwing && - IsBullish(iDir); - bool isP2BarSwingHigh = - isP2BarSwing && - IsBearish(iDir); - - // - // p3Bar ... - bool isP3BarSwing = - helper - .barAnalyser - .IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarSwingLow = - isP3BarSwing && - IsBullish(iDir); - bool isP3BarSwingHigh = - isP3BarSwing && - IsBearish(iDir); - - // - bool hasSwingLow = - isBullish && - (isP2BarSwingLow || - isP3BarSwingLow); - - // - bool hasSwingHigh = - isBearish && - (isP2BarSwingHigh || - isP3BarSwingHigh); - - // - result = - hasSwingLow || - hasSwingHigh; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Using Swing Length ... - result = config.minZoneLength > 0; - if (result) - { - // - XOHCL fromBar; - has = triggerBlock.FromBar(fromBar); - if (result) - { - // - // Retrieve HH and LL ... - ll = fromBar.FindLowest(config.minZoneLength, MODE_LOW); - hh = fromBar.FindHighest(config.minZoneLength, MODE_HIGH); - - // - // Validate Using HH and LL ... - - // - bool isBullishValid = - isBullish && - ll >= triggerBlock.lower; - - // - bool isBearishValid = - isBearish && - hh <= triggerBlock.upper; - - // - result = isBullishValid || - isBearishValid; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - - // - // Update Zone's From Time ... - triggerBlock.from = GetBarTime( - triggerBlock.symbol, - triggerBlock.period, - fromBar.Index() + config.minZoneLength // - ); - } - - // - fromBar.Clean(); - } - - // - // Validate Max Allowed Entry Distance ... - result = config.maxAllowedEntryDistance > 0; - if (result) - { - // - double base = - isBullish - ? triggerBlock.upper - : triggerBlock.lower; - double entryDistance = MathAbs(zBar.open - base); - result = entryDistance <= config.maxAllowedEntryDistance * points; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Here we Ensure which have a Valid Zone using Different Applied Validations ... - // from now we are Going to Filterd Validate Zones ... - - // - // Check Exists Filters or not ... - result = config.filterBasedOnSar || - config.filterBasedOnRSI || - config.filterBasedOnADX || - config.filterBasedOnTrend; - if (result) - { - // - // Do Apply Several Exists Filters ... - - // - // SAR Filter ... - if (config.filterBasedOnSar) - { - // - // Reading Conditions Values ... - - // - double zSar = conditions.sarBuffer[zIDX]; - double cSar = conditions.sarBuffer[cIDX]; - double pSar = conditions.sarBuffer[pIDX]; - double p2Sar = conditions.sarBuffer[p2IDX]; - double p3Sar = conditions.sarBuffer[p3IDX]; - double p4Sar = conditions.sarBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFilterd = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // RSI Filter ... - if (config.filterBasedOnRSI) - { - // - // Reading Conditions Values ... - - // - double rsiTrend = (conditions.rsiOBLevel + conditions.rsiOSLevel) / 2; - - // - double zRSI = conditions.rsiBuffer[zIDX]; - double cRSI = conditions.rsiBuffer[cIDX]; - double pRSI = conditions.rsiBuffer[pIDX]; - double p2RSI = conditions.rsiBuffer[p2IDX]; - double p3RSI = conditions.rsiBuffer[p3IDX]; - double p4RSI = conditions.rsiBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel && - pRSI <= conditions.rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel && - pRSI >= conditions.rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel && - pRSI > conditions.rsiOSLevel && - p2RSI <= conditions.rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel && - pRSI < conditions.rsiOBLevel && - p2RSI >= conditions.rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // ADX Filter ... - if (config.filterBasedOnADX) - { - // - // Reading Conditions Values ... - - // - // ADX ... - double zADX = conditions.adxBuffer[zIDX]; - double cADX = conditions.adxBuffer[cIDX]; - double pADX = conditions.adxBuffer[pIDX]; - double p2ADX = conditions.adxBuffer[p2IDX]; - double p3ADX = conditions.adxBuffer[p3IDX]; - double p4ADX = conditions.adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = conditions.adxpBuffer[zIDX]; - double cADXP = conditions.adxpBuffer[cIDX]; - double pADXP = conditions.adxpBuffer[pIDX]; - double p2ADXP = conditions.adxpBuffer[p2IDX]; - double p3ADXP = conditions.adxpBuffer[p3IDX]; - double p4ADXP = conditions.adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = conditions.adxnBuffer[zIDX]; - double cADXN = conditions.adxnBuffer[cIDX]; - double pADXN = conditions.adxnBuffer[pIDX]; - double p2ADXN = conditions.adxnBuffer[p2IDX]; - double p3ADXN = conditions.adxnBuffer[p3IDX]; - double p4ADXN = conditions.adxnBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > conditions.adxThreshold; - bool isZADXBearish = zADX < conditions.adxThreshold; - - // - bool isCADXBullish = cADX > conditions.adxThreshold; - bool isCADXBearish = cADX < conditions.adxThreshold; - - // - bool isPADXBullish = pADX > conditions.adxThreshold; - bool isPADXBearish = pADX < conditions.adxThreshold; - - // - bool isP2ADXBullish = p2ADX > conditions.adxThreshold; - bool isP2ADXBearish = p2ADX < conditions.adxThreshold; - - // - bool isP3ADXBullish = p3ADX > conditions.adxThreshold; - bool isP3ADXBearish = p3ADX < conditions.adxThreshold; - - // - bool isP4ADXBullish = p4ADX > conditions.adxThreshold; - bool isP4ADXBearish = p4ADX < conditions.adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // TREND Filter ... - if (config.filterBasedOnTrend) - { - // - // Reading Conditions Values ... - - // - double zTrend = conditions.trendBuffer[zIDX]; - double cTrend = conditions.trendBuffer[cIDX]; - double pTrend = conditions.trendBuffer[pIDX]; - double p2Trend = conditions.trendBuffer[p2IDX]; - double p3Trend = conditions.trendBuffer[p3IDX]; - double p4Trend = conditions.trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = conditions.trendStateBuffer[zIDX]; - double cTrendState = conditions.trendStateBuffer[cIDX]; - double pTrendState = conditions.trendStateBuffer[pIDX]; - double p2TrendState = conditions.trendStateBuffer[p2IDX]; - double p3TrendState = conditions.trendStateBuffer[p3IDX]; - double p4TrendState = conditions.trendStateBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // SCORE Filter ... - - // - // VOLUME Filter ... - } - - // - result = triggerBlock.IsValid(); - if (result) - { - // - triggerBlock.type = - isBullish - ? ToString(XCA_TRIGGER_BULL) - : ToString(XCA_TRIGGER_BEAR); - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - if (!result) - { - // - conditions.Clean(); - triggerBlock.Clean(); - } - - // - return result; -}; - -bool DetectTriggerBlock1( - XBoxZone &triggerBlock, - XCAEAConditions &conditions, - XCXCAEAHelper *helper, - XCAEATriggerBlockConfiguration &config, - int bar_index = 0, - int loopback = 6 // -) -{ - // - bool result = false; - - // - conditions.Clean(); - triggerBlock.Clean(); - - // - // Normalize Args ... - loopback = NormalizeInt(loopback, 6); - bar_index = NormalizeInt(bar_index, 0); - - // - // Validate Args ... - result = helper != NULL; - if (!result) - { - return result; - } - - // - // Provide base Requirements ... - - // - string symbol = helper.GetSymbol(); - double points = GetPoints(symbol); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - // Conditions Reading Indexes ... - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - double ll = 0; - double hh = 0; - bool has = false; - ENUM_X_DIRECTION iDir; - - // - // Retrieve Current Conditions ... - result = helper.GetConditions( - conditions, - bar_index, - loopback // - ); - - // - // Retrieve Required Bars ... - - // - XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ... - XOHCL cBar; // Current Finished Bar which Start Detecting Structures based on it ( End of Block and FVG Bar ) ... - XOHCL pBar; // Determines Block Gap Bar (all Filtering must applied and Check using this Bar and it's Next Bar) ... - XOHCL p2Bar; // Determines FVG's Start Bar in a Block ... - XOHCL p3Bar; // First Verification of Block ... - XOHCL p4Bar; // Seccond Verification of Block ... - - // - result = zBar.Init( - symbol, - period, - bar_index // - ); - result = - result && - zBar.GetPreviousBar(cBar); - result = - result && - cBar.GetPreviousBar(pBar); - result = - result && - pBar.GetPreviousBar(p2Bar); - result = - result && - p2Bar.GetPreviousBar(p3Bar); - result = - result && - p3Bar.GetPreviousBar(p4Bar); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - - // - // Detect Based Order Block using CBar ... - result = - helper - .barAnalyser - .IsOB( - cBar, - triggerBlock, - true, // Force FVG Bar Type ... - true // Force Block Two Bar Checking ... - ); - - // - // Ensure a Block is Detected ... - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - return result; - - // - // Reading Some Block Based Requirements ... - - // - bool isBullish = - result && - triggerBlock.IsBullish(); - - // - bool isBearish = - result && - triggerBlock.IsBearish(); - - // - int toIDX = triggerBlock.ToIndex(); - int fromIDX = triggerBlock.FromIndex(); - - // - // Start Validating ... - - // - // Validating p2Bar and p3Bar Direction ... - if (result) - { - // - iDir = Opposit(triggerBlock.dir); - - // - result = - iDir == p3Bar.GetDirection() || - iDir == p4Bar.GetDirection(); - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Using Max Range ... - result = config.maxZoneRangeInPoints > 0; - if (result) - { - // - double range = triggerBlock.GetRange(); - result = range <= config.maxZoneRangeInPoints * points; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validate Gap Endup with PinBar ... - result = config.forceHasPinBarEntry; - if (result) - { - // - bool isBullishRejected = - isBullish && - cBar.IsBullish() && - cBar.GetLowShadow() > cBar.GetHighShadow(); - - // - bool isBearishRejected = - isBearish && - cBar.IsBearish() && - cBar.GetLowShadow() < cBar.GetHighShadow(); - - // - result = isBullishRejected || - isBearishRejected; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Gap Bar must a Momentum Bar and - // Breakes out Zone's Directional Edge ... - // for Bullish: Upper - // for Bearish: Lower - result = config.forceGapBarsBreakout; - if (result) - { - // - // Gap Bar is PBar ... - - // - // Check Gap Bar is Momentum Bar ... - result = - helper - .barAnalyser - .IsMomentum( - pBar, - iDir // - ); - bool isBullishMomentum = - result && - IsBullish(iDir); - bool isBearishMomentum = - result && - IsBearish(iDir); - - // - // Check Gap Bar's Breakout ... - - // - bool isBullishBreakedout = - isBullish && - pBar.IsBullish() && - isBullishMomentum && - pBar.GetUp() > triggerBlock.upper && - pBar.GetDown() < triggerBlock.upper; - - // - bool isBearishBreakedout = - isBearish && - pBar.IsBearish() && - isBearishMomentum && - pBar.GetUp() > triggerBlock.lower && - pBar.GetDown() < triggerBlock.lower; - - // - result = isBullishBreakedout || - isBearishBreakedout; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validate Zone Has Propper Swing ... - // for Bullish: p2Bar or p3Bar must be a Swing Low ... - // for Bearish: p2Bar or p3Bar must be a Swing High ... - result = config.forceHasSwing; - if (result) - { - // - // p2Bar ... - bool isP2BarSwing = - helper - .barAnalyser - .IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarSwingLow = - isP2BarSwing && - IsBullish(iDir); - bool isP2BarSwingHigh = - isP2BarSwing && - IsBearish(iDir); - - // - // p3Bar ... - bool isP3BarSwing = - helper - .barAnalyser - .IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarSwingLow = - isP3BarSwing && - IsBullish(iDir); - bool isP3BarSwingHigh = - isP3BarSwing && - IsBearish(iDir); - - // - bool hasSwingLow = - isBullish && - (isP2BarSwingLow || - isP3BarSwingLow); - - // - bool hasSwingHigh = - isBearish && - (isP2BarSwingHigh || - isP3BarSwingHigh); - - // - result = - hasSwingLow || - hasSwingHigh; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Validating Using Swing Length ... - result = config.minZoneLength > 0; - if (result) - { - // - XOHCL fromBar; - has = triggerBlock.FromBar(fromBar); - if (result) - { - // - // Retrieve HH and LL ... - ll = fromBar.FindLowest(config.minZoneLength, MODE_LOW); - hh = fromBar.FindHighest(config.minZoneLength, MODE_HIGH); - - // - // Validate Using HH and LL ... - - // - bool isBullishValid = - isBullish && - ll >= triggerBlock.lower; - - // - bool isBearishValid = - isBearish && - hh <= triggerBlock.upper; - - // - result = isBullishValid || - isBearishValid; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - - // - // Update Zone's From Time ... - triggerBlock.from = GetBarTime( - triggerBlock.symbol, - triggerBlock.period, - fromBar.Index() + config.minZoneLength // - ); - } - - // - fromBar.Clean(); - } - - // - // Validate Max Allowed Entry Distance ... - result = config.maxAllowedEntryDistance > 0; - if (result) - { - // - double base = - isBullish - ? triggerBlock.upper - : triggerBlock.lower; - double entryDistance = MathAbs(zBar.open - base); - result = entryDistance <= config.maxAllowedEntryDistance * points; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // Here we Ensure which have a Valid Zone using Different Applied Validations ... - // from now we are Going to Filterd Validate Zones ... - - // - // Check Exists Filters or not ... - result = config.filterBasedOnSar || - config.filterBasedOnRSI || - config.filterBasedOnADX || - config.filterBasedOnTrend; - if (result) - { - // - // Do Apply Several Exists Filters ... - - // - // SAR Filter ... - if (config.filterBasedOnSar) - { - // - // Reading Conditions Values ... - - // - double zSar = conditions.sarBuffer[zIDX]; - double cSar = conditions.sarBuffer[cIDX]; - double pSar = conditions.sarBuffer[pIDX]; - double p2Sar = conditions.sarBuffer[p2IDX]; - double p3Sar = conditions.sarBuffer[p3IDX]; - double p4Sar = conditions.sarBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFilterd = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // RSI Filter ... - if (config.filterBasedOnRSI) - { - // - // Reading Conditions Values ... - - // - double rsiTrend = (conditions.rsiOBLevel + conditions.rsiOSLevel) / 2; - - // - double zRSI = conditions.rsiBuffer[zIDX]; - double cRSI = conditions.rsiBuffer[cIDX]; - double pRSI = conditions.rsiBuffer[pIDX]; - double p2RSI = conditions.rsiBuffer[p2IDX]; - double p3RSI = conditions.rsiBuffer[p3IDX]; - double p4RSI = conditions.rsiBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel && - pRSI <= conditions.rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel && - pRSI >= conditions.rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > conditions.rsiOSLevel && - cRSI > conditions.rsiOSLevel && - pRSI > conditions.rsiOSLevel && - p2RSI <= conditions.rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < conditions.rsiOBLevel && - cRSI < conditions.rsiOBLevel && - pRSI < conditions.rsiOBLevel && - p2RSI >= conditions.rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // ADX Filter ... - if (config.filterBasedOnADX) - { - // - // Reading Conditions Values ... - - // - // ADX ... - double zADX = conditions.adxBuffer[zIDX]; - double cADX = conditions.adxBuffer[cIDX]; - double pADX = conditions.adxBuffer[pIDX]; - double p2ADX = conditions.adxBuffer[p2IDX]; - double p3ADX = conditions.adxBuffer[p3IDX]; - double p4ADX = conditions.adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = conditions.adxpBuffer[zIDX]; - double cADXP = conditions.adxpBuffer[cIDX]; - double pADXP = conditions.adxpBuffer[pIDX]; - double p2ADXP = conditions.adxpBuffer[p2IDX]; - double p3ADXP = conditions.adxpBuffer[p3IDX]; - double p4ADXP = conditions.adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = conditions.adxnBuffer[zIDX]; - double cADXN = conditions.adxnBuffer[cIDX]; - double pADXN = conditions.adxnBuffer[pIDX]; - double p2ADXN = conditions.adxnBuffer[p2IDX]; - double p3ADXN = conditions.adxnBuffer[p3IDX]; - double p4ADXN = conditions.adxnBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > conditions.adxThreshold; - bool isZADXBearish = zADX < conditions.adxThreshold; - - // - bool isCADXBullish = cADX > conditions.adxThreshold; - bool isCADXBearish = cADX < conditions.adxThreshold; - - // - bool isPADXBullish = pADX > conditions.adxThreshold; - bool isPADXBearish = pADX < conditions.adxThreshold; - - // - bool isP2ADXBullish = p2ADX > conditions.adxThreshold; - bool isP2ADXBearish = p2ADX < conditions.adxThreshold; - - // - bool isP3ADXBullish = p3ADX > conditions.adxThreshold; - bool isP3ADXBearish = p3ADX < conditions.adxThreshold; - - // - bool isP4ADXBullish = p4ADX > conditions.adxThreshold; - bool isP4ADXBearish = p4ADX < conditions.adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // TREND Filter ... - if (config.filterBasedOnTrend) - { - // - // Reading Conditions Values ... - - // - double zTrend = conditions.trendBuffer[zIDX]; - double cTrend = conditions.trendBuffer[cIDX]; - double pTrend = conditions.trendBuffer[pIDX]; - double p2Trend = conditions.trendBuffer[p2IDX]; - double p3Trend = conditions.trendBuffer[p3IDX]; - double p4Trend = conditions.trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = conditions.trendStateBuffer[zIDX]; - double cTrendState = conditions.trendStateBuffer[cIDX]; - double pTrendState = conditions.trendStateBuffer[pIDX]; - double p2TrendState = conditions.trendStateBuffer[p2IDX]; - double p3TrendState = conditions.trendStateBuffer[p3IDX]; - double p4TrendState = conditions.trendStateBuffer[p4IDX]; - - // - // Create Required Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - result = - isBullishFilterd || - isBearishFilterd; - if (!result) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - conditions.Clean(); - triggerBlock.Clean(); - - // - return result; - } - } - - // - // SCORE Filter ... - - // - // VOLUME Filter ... - } - - // - result = triggerBlock.IsValid(); - if (result) - { - // - triggerBlock.type = - isBullish - ? ToString(XCA_TRIGGER_BULL) - : ToString(XCA_TRIGGER_BEAR); - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - - // - if (!result) - { - // - conditions.Clean(); - triggerBlock.Clean(); - } - - // - return result; -} - -/** - * Detect Trigger Block ... - * - * @param trigger: XTriggerBlock instance Reference, hold founded Trigger Block - * @param helper: XCXCAEAHelper instance Reference Pointer, XCAEA Market nalyser Helper for acc Drawer - * @param config: XCAEATriggerBlockConfiguration instance Reference, Trigger Block Detecting Configuration - * @param bar_index: int, Bar Index to Start Detecting - * @param loopback: int, Loopback Bars Count - * - * @return ( bool ) - */ -bool DetectTriggerBlock( - XTriggerBlock &trigger, - XCXCAEAHelper *helper, - XCAEATriggerBlockConfiguration &config, - int bar_index = 0, - int loopback = 10 // -) -{ - // - bool result = false; - - // - // Normalize Args ... - trigger.Clean(); - loopback = NormalizeInt(loopback, 10); - bar_index = NormalizeInt(bar_index, 0); - - // - // Validate Args ... - result = helper != NULL; - if (!result) - { - return result; - } - - // - // Extract Required Informations ... - - // - string symbol = helper.GetSymbol(); - ENUM_TIMEFRAMES period = helper.GetPeriod(); - - // - double points = GetPoints(symbol); - - // - // Retrieve Indexed Bar ... - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - result = zBar.Init( - symbol, - period, - bar_index // - ); - result = result && - zBar.GetPreviousBar(cBar); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - int p4IDX = p3IDX + 1; - - // - // Check Trigger Block Exists ... - result = - result && - helper - .barAnalyser - .IsTrigger( - cBar, - trigger.trigger, - trigger.ob, - trigger.fvg, - trigger.rLiquidity, - trigger.fLiquidity, - trigger.swingBar, - loopback, - config.maxAllowedRange, - config.minAllowedBlockEdgeLength, - config.forceOBOppositBar, - config.forceFVGBarType, - config.forceGapBarBreakout, - config.forceHasSwingBar, - config.forceHasLiquidity, - config.forceHasReversalLiquidity // - ); - - // - // Now we Have to Implement Required Validations ... - - // - bool isBullish = trigger.trigger.IsBullish(); - bool isBearish = trigger.trigger.IsBearish(); - - // - // First Reading Market Conditions ... - result = - result && - helper.GetConditions( - trigger.conditions, - bar_index, - loopback // - ); - - // - // All Custom andAdditional Validations and Filters - // Applied here ... - - // - // SAR Filter ... - if (config.filterBasedOnSar) - { - // - if (result) - { - // - // Reading Values ... - - // - double zSar = trigger.conditions.sarBuffer[zIDX]; - double cSar = trigger.conditions.sarBuffer[cIDX]; - double pSar = trigger.conditions.sarBuffer[pIDX]; - double p2Sar = trigger.conditions.sarBuffer[p2IDX]; - double p3Sar = trigger.conditions.sarBuffer[p3IDX]; - double p4Sar = trigger.conditions.sarBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isZSarBearish = zSar > zBar.high; - - // - bool isCSarBullish = cSar < cBar.low; - bool isCSarBearish = cSar > cBar.high; - - // - bool isPSarBullish = pSar < pBar.low; - bool isPSarBearish = pSar > pBar.high; - - // - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP2SarBearish = p2Sar > p2Bar.high; - - // - bool isCSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - !isPSarBullish && - cBar.IsBullish() && - cBar.GetUp() > pSar; - - // - bool isCSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - !isPSarBearish && - cBar.IsBearish() && - cBar.GetDown() < pSar; - - // - bool isPSarSwitchedToBullish = - isZSarBullish && - isCSarBullish && - isPSarBullish && - !isP2SarBullish && - pBar.IsBullish() && - pBar.GetUp() > p2Sar; - - // - bool isPSarSwitchedToBearish = - isZSarBearish && - isCSarBearish && - isPSarBearish && - !isP2SarBearish && - pBar.IsBearish() && - pBar.GetDown() < p2Sar; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - (isCSarSwitchedToBullish || - isPSarSwitchedToBullish); - - // - bool isBearishFilterd = - isBearish && - (isCSarSwitchedToBearish || - isPSarSwitchedToBearish); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // RSI Filter ... - if (config.filterBasedOnRSI) - { - // - if (result) - { - // - // Reading Values ... - - // - double rsiTrend = (trigger.conditions.rsiOBLevel + trigger.conditions.rsiOSLevel) / 2; - - // - double zRSI = trigger.conditions.rsiBuffer[zIDX]; - double cRSI = trigger.conditions.rsiBuffer[cIDX]; - double pRSI = trigger.conditions.rsiBuffer[pIDX]; - double p2RSI = trigger.conditions.rsiBuffer[p2IDX]; - double p3RSI = trigger.conditions.rsiBuffer[p3IDX]; - double p4RSI = trigger.conditions.rsiBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - bool isZRSIBullish = zRSI > rsiTrend; - bool isZRSIBearish = zRSI < rsiTrend; - - // - bool isCRSIBullish = cRSI > rsiTrend; - bool isCRSIBearish = cRSI < rsiTrend; - - // - bool isPRSIBullish = pRSI > rsiTrend; - bool isPRSIBearish = pRSI < rsiTrend; - - // - bool isP2RSIBullish = p2RSI > rsiTrend; - bool isP2RSIBearish = p2RSI < rsiTrend; - - // - bool isP3RSIBullish = p3RSI > rsiTrend; - bool isP3RSIBearish = p3RSI < rsiTrend; - - // - // Trending Conditions ... - - // - bool isCRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - !isPRSIBullish; - - // - bool isCRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - !isPRSIBearish; - - // - bool isPRSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - !isP2RSIBullish; - - // - bool isPRSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - !isP2RSIBearish; - - // - bool isP2RSISwitchedToBullish = - isZRSIBullish && - isCRSIBullish && - isPRSIBullish && - isP2RSIBullish && - !isP3RSIBullish; - - // - bool isP2RSISwitchedToBearish = - isZRSIBearish && - isCRSIBearish && - isPRSIBearish && - isP2RSIBearish && - !isP3RSIBearish; - - // - // Crosses Conditions ... - - // - bool isCBarCrossedOverOS = - zRSI > trigger.conditions.rsiOSLevel && - cRSI > trigger.conditions.rsiOSLevel && - pRSI <= trigger.conditions.rsiOSLevel; - - // - bool isCBarCrossedUnderOB = - zRSI < trigger.conditions.rsiOBLevel && - cRSI < trigger.conditions.rsiOBLevel && - pRSI >= trigger.conditions.rsiOBLevel; - - // - bool isPBarCrossedOverOS = - zRSI > trigger.conditions.rsiOSLevel && - cRSI > trigger.conditions.rsiOSLevel && - pRSI > trigger.conditions.rsiOSLevel && - p2RSI <= trigger.conditions.rsiOSLevel; - - // - bool isPBarCrossedUnderOB = - zRSI < trigger.conditions.rsiOBLevel && - cRSI < trigger.conditions.rsiOBLevel && - pRSI < trigger.conditions.rsiOBLevel && - p2RSI >= trigger.conditions.rsiOBLevel; - - // - // V Pattern Conditions ... - - // - bool isCRSIHasVBullishPattern = - zRSI >= cRSI && - cRSI > pRSI && - p2RSI > pRSI && - cRSI >= p2RSI; - - // - bool isCRSIHasVBearishPattern = - zRSI <= cRSI && - cRSI < pRSI && - p2RSI < pRSI && - cRSI <= p2RSI; - - // - // Continuation Conditions ... - - // - bool isRSIUp = - zRSI >= cRSI && - (cRSI >= pRSI || - pRSI >= p2RSI || - p2RSI >= p3RSI); - - // - bool isRSIDown = - zRSI <= cRSI && - (cRSI <= pRSI || - pRSI <= p2RSI || - p2RSI <= p3RSI); - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isRSIUp - // - || - // - // Crosses ... - (isCBarCrossedOverOS || - isPBarCrossedOverOS) - // - || - // - // V Pattern ... - isCRSIHasVBullishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBullish || - isPRSISwitchedToBullish || - isP2RSISwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isRSIDown - // - || - // - // Crosses ... - (isCBarCrossedUnderOB || - isPBarCrossedUnderOB) - // - || - // - // V Pattern ... - isCRSIHasVBearishPattern - // - || - // - // Trending ... - (isCRSISwitchedToBearish || - isPRSISwitchedToBearish || - isP2RSISwitchedToBearish) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // ADX Filter ... - if (config.filterBasedOnADX) - { - // - if (result) - { - // - // Reading Values ... - - // - // ADX ... - double zADX = trigger.conditions.adxBuffer[zIDX]; - double cADX = trigger.conditions.adxBuffer[cIDX]; - double pADX = trigger.conditions.adxBuffer[pIDX]; - double p2ADX = trigger.conditions.adxBuffer[p2IDX]; - double p3ADX = trigger.conditions.adxBuffer[p3IDX]; - double p4ADX = trigger.conditions.adxBuffer[p4IDX]; - - // - // ADX +DI ... - double zADXP = trigger.conditions.adxpBuffer[zIDX]; - double cADXP = trigger.conditions.adxpBuffer[cIDX]; - double pADXP = trigger.conditions.adxpBuffer[pIDX]; - double p2ADXP = trigger.conditions.adxpBuffer[p2IDX]; - double p3ADXP = trigger.conditions.adxpBuffer[p3IDX]; - double p4ADXP = trigger.conditions.adxpBuffer[p4IDX]; - - // - // ADX -DI ... - double zADXN = trigger.conditions.adxnBuffer[zIDX]; - double cADXN = trigger.conditions.adxnBuffer[cIDX]; - double pADXN = trigger.conditions.adxnBuffer[pIDX]; - double p2ADXN = trigger.conditions.adxnBuffer[p2IDX]; - double p3ADXN = trigger.conditions.adxnBuffer[p3IDX]; - double p4ADXN = trigger.conditions.adxnBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - // Grows ... - - // - bool isADXUp = - zADX >= cADX && - (cADX >= pADX || - pADX >= p2ADX); - - // - bool isADXDown = - zADX <= cADX && - (cADX <= pADX || - pADX <= p2ADX); - - // - // Trending ... - - // - bool isZADXBullish = zADX > trigger.conditions.adxThreshold; - bool isZADXBearish = zADX < trigger.conditions.adxThreshold; - - // - bool isCADXBullish = cADX > trigger.conditions.adxThreshold; - bool isCADXBearish = cADX < trigger.conditions.adxThreshold; - - // - bool isPADXBullish = pADX > trigger.conditions.adxThreshold; - bool isPADXBearish = pADX < trigger.conditions.adxThreshold; - - // - bool isP2ADXBullish = p2ADX > trigger.conditions.adxThreshold; - bool isP2ADXBearish = p2ADX < trigger.conditions.adxThreshold; - - // - bool isP3ADXBullish = p3ADX > trigger.conditions.adxThreshold; - bool isP3ADXBearish = p3ADX < trigger.conditions.adxThreshold; - - // - bool isP4ADXBullish = p4ADX > trigger.conditions.adxThreshold; - bool isP4ADXBearish = p4ADX < trigger.conditions.adxThreshold; - - // - bool isCADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - !isPADXBullish; - - // - bool isCADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - !isPADXBearish; - - // - bool isPADXSwitchedToBullish = - isZADXBullish && - isCADXBullish && - isPADXBullish && - !isP2ADXBullish; - - // - bool isPADXSwitchedToBearish = - isZADXBearish && - isCADXBearish && - isPADXBearish && - !isP2ADXBearish; - - // - // Powering ... - - // - bool isZADXHasBullishPower = zADXP > zADXN; - bool isZADXHasBearishPower = zADXN > zADXP; - - // - bool isCADXHasBullishPower = cADXP > cADXN; - bool isCADXHasBearishPower = cADXN > cADXP; - - // - bool isPADXHasBullishPower = pADXP > pADXN; - bool isPADXHasBearishPower = pADXN > pADXP; - - // - bool isP2ADXHasBullishPower = p2ADXP > p2ADXN; - bool isP2ADXHasBearishPower = p2ADXN > p2ADXP; - - // - bool isP3ADXHasBullishPower = p3ADXP > p3ADXN; - bool isP3ADXHasBearishPower = p3ADXN > p3ADXP; - - // - bool isP4ADXHasBullishPower = p4ADXP > p4ADXN; - bool isP4ADXHasBearishPower = p4ADXN > p4ADXP; - - // - bool isCADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - !isPADXHasBullishPower; - - // - bool isCADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - !isPADXHasBearishPower; - - // - bool isPADXSwitchedToBullishPower = - isZADXHasBullishPower && - isCADXHasBullishPower && - isPADXHasBullishPower && - !isP2ADXHasBullishPower; - - // - bool isPADXSwitchedToBearishPower = - isZADXHasBearishPower && - isCADXHasBearishPower && - isPADXHasBearishPower && - !isP2ADXHasBearishPower; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isADXUp - // - || - // - // Trending ... - (isCADXSwitchedToBullish || - isPADXSwitchedToBullish) - // - || - // - // Powering ... - (isCADXSwitchedToBullishPower || - isPADXSwitchedToBullishPower) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isADXDown - // - || - // - // Trending ... - (isCADXSwitchedToBearish || - isPADXSwitchedToBearish) - // - || - // - // Powering ... - (isCADXSwitchedToBearishPower || - isPADXSwitchedToBearishPower) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // TREND Filter ... - if (config.filterBasedOnTrend) - { - // - if (result) - { - // - // Reading Values ... - - // - double zTrend = trigger.conditions.trendBuffer[zIDX]; - double cTrend = trigger.conditions.trendBuffer[cIDX]; - double pTrend = trigger.conditions.trendBuffer[pIDX]; - double p2Trend = trigger.conditions.trendBuffer[p2IDX]; - double p3Trend = trigger.conditions.trendBuffer[p3IDX]; - double p4Trend = trigger.conditions.trendBuffer[p4IDX]; - - // - double trends[] = { - zTrend, - cTrend, - pTrend, - p2Trend, - p3Trend, - p4Trend // - }; - double trendsMin = GetMin(trends); - double trendsMax = GetMax(trends); - double trendsAVG = GetAverage(trends); - - // - double zTrendState = trigger.conditions.trendStateBuffer[zIDX]; - double cTrendState = trigger.conditions.trendStateBuffer[cIDX]; - double pTrendState = trigger.conditions.trendStateBuffer[pIDX]; - double p2TrendState = trigger.conditions.trendStateBuffer[p2IDX]; - double p3TrendState = trigger.conditions.trendStateBuffer[p3IDX]; - double p4TrendState = trigger.conditions.trendStateBuffer[p4IDX]; - - // - // Preparing Conditions ... - - // - // Grows ... - - // - bool isTrendUp = - zTrend >= cTrend && - cTrend >= trendsAVG && - cTrend > trendsMin; - - // - bool isTrendDown = - zTrend <= cTrend && - cTrend <= trendsAVG && - cTrend < trendsMax; - - // - // Stating ... - - // - bool isCTrendBullish = - zTrendState > 0 && - cTrendState > 0; - - // - bool isCTrendBearish = - zTrendState < 0 && - cTrendState < 0; - - // - bool isPTrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0; - - // - bool isPTrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0; - - // - bool isP2TrendBullish = - zTrendState > 0 && - cTrendState > 0 && - pTrendState > 0 && - p2TrendState > 0; - - // - bool isP2TrendBearish = - zTrendState < 0 && - cTrendState < 0 && - pTrendState < 0 && - p2TrendState < 0; - - // - bool isCTrendSwitchedToBullish = - isCTrendBullish && - !isPTrendBullish; - - // - bool isCTrendSwitchedToBearish = - isCTrendBearish && - !isPTrendBearish; - - // - bool isPTrendSwitchedToBullish = - isCTrendBullish && - isPTrendBullish && - !isP2TrendBullish; - - // - bool isPTrendSwitchedToBearish = - isCTrendBearish && - isPTrendBearish && - !isP2TrendBearish; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - ( - // - // Grows ... - isTrendUp - // - || - // - // Trend Stating ... - (isCTrendBullish && - isPTrendBullish) - // - || - // - // Switching ... - (isCTrendSwitchedToBullish || - isPTrendSwitchedToBullish) - // - ); - - // - bool isBearishFilterd = - isBearish && - ( - // - // Grows ... - isTrendDown - // - || - // - // Trend Stating ... - (isCTrendBearish && - isPTrendBearish) - // - || - // - // Switching ... - (isCTrendSwitchedToBearish || - isPTrendSwitchedToBearish) - // - ); - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // SCORE Filter ... - if (config.filterBasedOnScores) - { - // - if (result) - { - // - // Reading Values ... - - // - double bullishScore = 0; - double bearishScore = 0; - - // - trigger.conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - // Preparing Conditions ... - - // - bool isScoreBullish = bullishScore > bearishScore; - bool isScoreBearish = bearishScore > bullishScore; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - isScoreBullish; - - // - bool isBearishFilterd = - isBearish && - isScoreBearish; - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // VOLUME Filter ... - if (config.filterBasedOnVolumes) - { - // - if (result) - { - // - // Reading Values ... - - // - double bullishVolume = 0; - double bearishVolume = 0; - - // - helper - .barAnalyser - .CalculateRangeVolume( - zBar, - bullishVolume, - bearishVolume, - loopback // - ); - - // - // Preparing Conditions ... - - // - bool isVolumeBullish = bullishVolume > bearishVolume; - bool isVolumeBearish = bearishVolume > bullishVolume; - - // - // Summarize Filtering ... - - // - bool isBullishFilterd = - isBullish && - isVolumeBullish; - - // - bool isBearishFilterd = - isBearish && - isVolumeBearish; - - // - // Apply Result .... - - // - result = - result && - (isBullishFilterd || - isBearishFilterd); - } - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - - // - if (!result) - { - trigger.Clean(); - } - - // - // Attach Configuration if Trigger Block Founded ... - if (result) - { - trigger.configuration = config; - } - - // - return result; -} - -/** - * Draw Specified Trigger Block ... - * - * @param trigger: XTriggerBlock instance Reference, specified Trigger Block to Draw - * @param objects: CArrayObj instance Reference Pointer, Objects Array for Providing Drawn Objects - * @param helper: XCXCAEAHelper instance Reference Pointer, XCAEA Market nalyser Helper for acc Drawer - * @param to: datetime, specified Time for update Trigger parts - * - * @return ( bool ) - */ -bool DrawTriggerBlock( - XTriggerBlock &trigger, - CArrayObj *&objects, - XCXCAEAHelper *helper, - datetime to = NULL // -) -{ - // - bool result = false; - - // - // Validate Args ... - result = helper != NULL && - trigger.IsValid(); - if (!result) - { - return result; - } - - // - // Update To ... - bool canUpdateTo = IsValid(to); - if (canUpdateTo) - { - // - trigger.trigger.to = to; - trigger.rLiquidity.to = to; - trigger.fLiquidity.to = to; - } - - // - // Draw OB ... - if (trigger.ob.IsValid()) - { - // - XCBoxObject *iOBObj; - result = helper.poiDrawer.DrawBox( - trigger.ob, - iOBObj // - ); - if (result) - { - objects.Add(iOBObj); - } - ZeroMemory(iOBObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw FVG ... - if (trigger.fvg.IsValid()) - { - // - XCBoxObject *iFVGObj; - result = helper.poiDrawer.DrawBox( - trigger.fvg, - iFVGObj // - ); - if (result) - { - // - // Style Object ... - color clr = - trigger.fvg.IsBullish() - ? clrAqua - : clrMagenta; - iFVGObj.BoxWidth(2); - iFVGObj.BoxColor(clr); - iFVGObj.BoxStyle(STYLE_SOLID); - - // - // Store Object ... - objects.Add(iFVGObj); - } - ZeroMemory(iFVGObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Trigger ... - if (trigger.trigger.IsValid()) - { - // - XCBoxObject *iTriggerObj; - result = helper.poiDrawer.DrawBox( - trigger.trigger, - iTriggerObj // - ); - if (result) - { - objects.Add(iTriggerObj); - } - ZeroMemory(iTriggerObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Liquidities ... - - // - // Reversla Liquidity ... - if (trigger.rLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = helper.poiDrawer.DrawBox( - trigger.rLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Following Liquidity ... - if (trigger.fLiquidity.IsValid()) - { - // - XCBoxObject *iLiqObj; - result = helper.poiDrawer.DrawBox( - trigger.fLiquidity, - iLiqObj // - ); - if (result) - { - objects.Add(iLiqObj); - } - ZeroMemory(iLiqObj); - - // - if (!result) - { - return result; - } - } - - // - // Draw Swing Bar ... - if (trigger.swingBar.IsValid()) - { - // - color swingColor = - trigger.fvg.IsBullish() - ? clrAqua - : clrMagenta; - ENUM_X_PRICE swingPType = - trigger.fvg.IsBullish() - ? X_PRICE_LOW - : X_PRICE_HIGH; - - // - XCBarArrowObject *swingObj; - result = helper.poiDrawer.CreateBarArrow( - trigger.swingBar, - swingObj, - swingPType, - 159, - swingColor // - ); - if (result) - { - objects.Add(swingObj); - } - ZeroMemory(swingObj); - - // - if (!result) - { - return result; - } - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/BKP/xcaea.x-poi.detector.class.mq5 b/Documents/BKP/xcaea.x-poi.detector.class.mq5 deleted file mode 100644 index 92118f56..00000000 --- a/Documents/BKP/xcaea.x-poi.detector.class.mq5 +++ /dev/null @@ -1,5287 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XCXCAEAPOIDetector ... -// Description: Class for XCAEA POI Detector ... -// -// -// 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 XCAEA POI Detector" -#property strict - -// -// Imports ... -#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Helpers/xcaea.helper.mq5" - -// -// Definitions ... - -// -enum ENUM_XCA_PIVOTS -{ - XCA_NONE, // None - XCA_SWL, // Swing Low - XCA_SWH, // Swing High - XCA_PEAK, // Peak - XCA_VALE, // Vale - XCA_OB_BULL, // OBBull - XCA_OB_BEAR, // OBBear - XCA_FVG_BULL, // FVGBull - XCA_FVG_BEAR, // FVGBear - XCA_RSI_COOS, // RSICOOS - XCA_RSI_CUOB, // RSICUOB - XCA_TREND_BULL, // TrendBull - XCA_TREND_BEAR, // TrendBear - XCA_TRIGGER_BULL, // TriggerBull - XCA_TRIGGER_BEAR, // TriggerBear -}; - -// -bool IsValid(ENUM_XCA_PIVOTS value) -{ - // - bool result = false; - - // - result = value != XCA_NONE; - - // - return result; -} - -// -string ToString(ENUM_XCA_PIVOTS value) -{ - // - string result = NULL; - - // - result = EnumToString(value); - - // - return result; -} - -// -ENUM_X_DIRECTION GetDirection(ENUM_XCA_PIVOTS value) -{ - // - ENUM_X_DIRECTION result = X_DIRECTION_NONE; - - // - switch (value) - { - // - case XCA_SWL: - case XCA_VALE: - case XCA_OB_BULL: - case XCA_FVG_BULL: - case XCA_RSI_COOS: - case XCA_TREND_BULL: - case XCA_TRIGGER_BULL: - result = X_DIRECTION_BULLISH; - break; - - // - case XCA_SWH: - case XCA_PEAK: - case XCA_OB_BEAR: - case XCA_FVG_BEAR: - case XCA_RSI_CUOB: - case XCA_TREND_BEAR: - case XCA_TRIGGER_BEAR: - result = X_DIRECTION_BEARISH; - break; - } - - // - return result; -} - -// -string GetBoxType(ENUM_XCA_PIVOTS value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case XCA_SWL: - case XCA_SWH: - case XCA_VALE: - case XCA_PEAK: - case XCA_RSI_COOS: - case XCA_RSI_CUOB: - result = ToString(value); - break; - // - case XCA_OB_BULL: - case XCA_OB_BEAR: - result = "XCA_OB"; - break; - // - case XCA_FVG_BULL: - case XCA_FVG_BEAR: - result = "XCA_FVG"; - break; - - // - case XCA_TREND_BULL: - case XCA_TREND_BEAR: - result = "XCA_TREND"; - break; - - // - case XCA_TRIGGER_BULL: - case XCA_TRIGGER_BEAR: - result = "XCA_TRIGGER"; - break; - } - - // - return result; -} - -// -ENUM_XCA_PIVOTS GetPivotType(XBoxZone &value) -{ - // - ENUM_XCA_PIVOTS result = XCA_NONE; - - // - bool has = value.IsValid(); - if (!has) - { - return result; - } - - // - bool isSWL = value.type == GetBoxType(XCA_SWL) && - value.dir == GetDirection(XCA_SWL); - bool isSWH = value.type == GetBoxType(XCA_SWH) && - value.dir == GetDirection(XCA_SWH); - bool isPeak = value.type == GetBoxType(XCA_PEAK) && - value.dir == GetDirection(XCA_PEAK); - bool isVale = value.type == GetBoxType(XCA_VALE) && - value.dir == GetDirection(XCA_VALE); - bool isOBBull = value.type == GetBoxType(XCA_OB_BULL) && - value.dir == GetDirection(XCA_OB_BULL); - bool isOBBear = value.type == GetBoxType(XCA_OB_BEAR) && - value.dir == GetDirection(XCA_OB_BEAR); - bool isFVGBull = value.type == GetBoxType(XCA_FVG_BULL) && - value.dir == GetDirection(XCA_FVG_BULL); - bool isFVGBear = value.type == GetBoxType(XCA_FVG_BEAR) && - value.dir == GetDirection(XCA_FVG_BEAR); - bool isRSICrossedOverOS = value.type == GetBoxType(XCA_RSI_COOS) && - value.dir == GetDirection(XCA_RSI_COOS); - bool isRSICrossedUnderOB = value.type == GetBoxType(XCA_RSI_CUOB) && - value.dir == GetDirection(XCA_RSI_CUOB); - bool isTrendBullish = value.type == GetBoxType(XCA_TREND_BULL) && - value.dir == GetDirection(XCA_TREND_BULL); - bool isTrendBearish = value.type == GetBoxType(XCA_TREND_BEAR) && - value.dir == GetDirection(XCA_TREND_BEAR); - bool isTriggerBullish = value.type == GetBoxType(XCA_TRIGGER_BULL) && - value.dir == GetDirection(XCA_TRIGGER_BULL); - bool isTriggerBearish = value.type == GetBoxType(XCA_TRIGGER_BEAR) && - value.dir == GetDirection(XCA_TRIGGER_BEAR); - - // - if (isSWL) - { - result = XCA_SWL; - } - else if (isSWH) - { - result = XCA_SWH; - } - else if (isPeak) - { - result = XCA_PEAK; - } - else if (isVale) - { - result = XCA_VALE; - } - else if (isOBBull) - { - result = XCA_OB_BULL; - } - else if (isOBBear) - { - result = XCA_OB_BEAR; - } - else if (isFVGBull) - { - result = XCA_FVG_BULL; - } - else if (isFVGBear) - { - result = XCA_FVG_BEAR; - } - else if (isRSICrossedOverOS) - { - result = XCA_RSI_COOS; - } - else if (isRSICrossedUnderOB) - { - result = XCA_RSI_CUOB; - } - else if (isTrendBullish) - { - result = XCA_TREND_BULL; - } - else if (isTrendBearish) - { - result = XCA_TREND_BEAR; - } - else if (isTriggerBullish) - { - result = XCA_TRIGGER_BULL; - } - else if (isTriggerBearish) - { - result = XCA_TRIGGER_BEAR; - } - - // - return result; -} - -// -int ExtractPivots( - XBoxZone &extracted[], - ENUM_XCA_PIVOTS type, - XBoxZone &source[] // -) -{ - // - int result = 0; - - // - Clean(extracted); - - // - bool has = - IsValid(type) && - HasChild(source); - if (!has) - { - return result; - } - - // - int count = ArraySize(source); - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = source[i]; - - // - ENUM_XCA_PIVOTS iType = GetPivotType(iBox); - - // - has = iType == type; - if (has) - { - // - AddRef( - iBox, - extracted // - ); - } - - // - iBox.Clean(); - } - - // - result = ArraySize(extracted); - - // - return result; -} - -// -bool IsFakeBreakeout( - XBoxZone &pivot, - XCXCAEAHelper *helper, - int barIndex = 0 // -) -{ - // - bool result = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - result = pivot.IsValid(); - if (!result) - { - return result; - } - - // - int fromIDX = pivot.FromIndex(); - result = barIndex < fromIDX; - if (!result) - { - return result; - } - - // - bool isBullish = pivot.IsBullish(); - - // - // Retrieve Required Bars ... - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - XOHCL p3Bar; - result = cBar.Init( - pivot.symbol, - pivot.period, - barIndex // - ); - result = result && - cBar.GetPreviousBar(pBar); - result = result && - pBar.GetPreviousBar(p2Bar); - result = result && - p2Bar.GetPreviousBar(p3Bar); - if (!result) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; - } - // - // Bars Conditions ... - - // - ENUM_X_DIRECTION cBarDir; - - // - // Hammer ... - bool isCBarHammer = helper - .barAnalyser - .IsHammer( - cBar, - cBarDir // - ); - bool isCBarBullishHammer = - isCBarHammer && - IsBullish(cBarDir); - bool isCBarBearishHammer = - isCBarHammer && - IsBearish(cBarDir); - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - cBarDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isCBarBullishRejected = - isCBarRejected && - IsBullish(cBarDir); - bool isCBarBearishRejected = - isCBarRejected && - IsBearish(cBarDir); - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - cBarDir // - ); - bool isCBarBullishEngulfed = - isCBarEngulfed && - IsBullish(cBarDir); - bool isCBarBearishEngulfed = - isCBarEngulfed && - IsBearish(cBarDir); - - // - // Momentum ... - bool isCBarMomentum = helper - .barAnalyser - .IsMomentum( - cBar, - cBarDir, - 1 // - ); - bool isCBarBullishMomentum = - isCBarMomentum && - IsBullish(cBarDir); - bool isCBarBearishMomentum = - isCBarMomentum && - IsBearish(cBarDir); - - // - bool isCBarHasBullishPower = isCBarBullishRejected || - isCBarBullishEngulfed || - isCBarBullishMomentum; - - // - bool isCBarHasBearishPower = isCBarBearishRejected || - isCBarBearishEngulfed || - isCBarBearishMomentum; - - // - bool isBarPowerfull = - isBullish - ? isCBarHasBullishPower - : isCBarHasBearishPower; - - // - double breakPrice = - isBullish - ? pivot.lower - : pivot.upper; - - // - // CBar Must Go back InSide Box ... - bool isBarInside = - cBar.GetUp() > breakPrice && - cBar.GetDown() < breakPrice && - cBar.GetDirection() == pivot.dir; - - // - result = - // - // Bar Must Inside Pivot ... - isBarInside && - // - // Bar Must Has Required Direction Power ... - isBarPowerfull - // - ; - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - p3Bar.Clean(); - - // - return result; -} - -// -struct XCAPivot -{ - // - // Props ... - datetime to; - double value; - string symbol; - datetime from; - double reserve; - ENUM_XCA_PIVOTS type; - ENUM_TIMEFRAMES period; - - // - double values[]; - - // - // Constructor ... - XCAPivot() - { - Clean(); - } - - // - // Tools ... - - /** - * Cleanup ... - */ - void Clean() - { - // - value = 0; - to = NULL; - reserve = 0; - from = NULL; - symbol = NULL; - period = NULL; - type = XCA_NONE; - - // - Clean(values); - - // - ZeroMemory(this); - } - - /** - * Validate ... - * - * @return ( bool ) - */ - bool IsValid() - { - // - bool result = false; - - // - result = - from < to && - value != 0 && - IsValid(to) && - IsValid(from) && - IsValid(type) && - IsValid(symbol) && - IsValid(period); - - // - return result; - } - - /** - * Check a Model is Same as this or not ... - * - * @param pivot: XCAPivot ... - * - * @return ( bool ) - */ - bool IsSameAs(XCAPivot &pivot) - { - // - bool result = false; - - // - result = - IsValid() && - pivot.IsValid(); - if (!result) - { - return result; - } - - // - result = - to == pivot.to && - from == pivot.from && - type == pivot.type && - value == pivot.value && - symbol == pivot.symbol && - period == pivot.period; - - // - return result; - } - - /** - * Retrieve To Index ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int ToIndex( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - result = GetBarIndex( - symbol, - forPeriod, - to // - ); - - // - return result; - } - - /** - * Retrieve From Index ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int FromIndex( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - result = GetBarIndex( - symbol, - forPeriod, - from // - ); - - // - return result; - } - - /** - * Retrieve Age of Pivot ... - * - * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... - * - * @return ( int ) - */ - int GetAge( - ENUM_TIMEFRAMES forPeriod = NULL // - ) - { - // - int result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsValid(forPeriod)) - { - forPeriod = period; - } - - // - int toIDX = ToIndex(forPeriod); - int fromIDX = FromIndex(forPeriod); - - // - result = fromIDX - toIDX; - - // - return result; - } - - /** - * Converts Pivot to Box ... - * - * @param box: XBoxZone instance reference ... - * - * @return ( bool ) - */ - bool AsBox( - XBoxZone &box // - ) - { - // - bool result = false; - - // - box.Clean(); - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - ENUM_X_DIRECTION iDir = GetDirection(type); - - // - result = HasDirection(iDir); - if (!result) - { - return result; - } - - // - bool isBullish = - IsBullish(iDir) && - value < reserve; - - // - bool isBearish = - IsBearish(iDir) && - value > reserve; - - // - result = isBullish || - isBearish; - if (!result) - { - return result; - } - - // - box.to = to; - box.dir = iDir; - box.from = from; - box.symbol = symbol; - box.period = period; - - // - string typeStr = GetBoxType(type); - box.type = typeStr; - - // - box.upper = - isBullish - ? reserve - : value; - box.lower = - isBullish - ? value - : reserve; - - // - result = box.IsValid(); - if (!result) - { - box.Clean(); - } - - // - return result; - } - - // -}; - -// -// Implementations ... -class XCXCAEAPOIDetector : public XCBase -{ - // - // Public ... - public: - // - // Props ... - - // - // Pivot Verifications and Max Allowed Holding Items ... - int maxAllowedPivots; // Max Allowed Holding Pibots ... - int pivotVerifications; // Pivots Verifications ... - int pivotDetectionLoopbac; // Pivots Detection Loopback ... - double ticksDividerInPoints; // Ticks and Volume Detection Divider in Point ... - - // - // TREND ... - XBoxZone trendPivotP; // Prev Pivot of Market Trend ... - XBoxZone trendPivotC; // Current Pivot of Market Trend ... - ENUM_X_DIRECTION trendDir; // Trend Direction ... - - // - // Breaked Pivots ... - XBoxZone invalidPivots[]; - - // - // Constructors ... - XCXCAEAPOIDetector( - XCXCAEAHelper *_helper // - ) - { - // - helper = _helper; - drawer = new XCPOIDrawer(); - barAnalyser = new XCBarAnalyser(); - - // - Default(); - } - - // - // De Constructors ... - ~XCXCAEAPOIDetector() - { - // - CleanPivots(); - - // - ZeroMemory(helper); - ZeroMemory(drawer); - ZeroMemory(barAnalyser); - } - - // - // Properties ... - - // - // Tools ... - - // - virtual void Default() - { - // - // COMMON ... - - // - maxAllowedPivots = 50; - pivotVerifications = 5; - ticksDividerInPoints = 15; - pivotDetectionLoopbac = 100; - - // - // SWING ... - - // - maxAllowedSwingLifetime = 0; - - // - detectSWHPivots = false; - detectSWLPivots = false; - - // - // PV ... - - // - detectPeakPivots = false; - detectValePivots = false; - - // - maxAllowedPVLifetime = 0; - applySwingsOnPVPivots = false; - selectRejectedPVPivots = false; - selectEngulfedPVPivots = false; - selectPVWhichStartByFVG = false; - applySupportAndResistanceOnPVPivots = false; - - // - // FVG ... - - // - detectFVGBullishPivots = false; - detectFVGBearishPivots = false; - - // - selectSameBarFVGs = false; - maxAllowedFVGLifetime = 0; - validateFVGUsingPV = false; - applyPVToFVGBoundary = false; - selectRejectedFVGPivots = false; - selectEngulfedFVGPivots = false; - validateFVGUsingManalyser = false; - applyLastBarToFVGBoundary = false; - selectOnlyFVGWhichHasIndirectionalLastBar = false; - - // - // OB ... - maxAllowedOBLifetime = 0; - - // - detectOBBullishPivots = false; - detectOBBearishPivots = false; - - // - // TREND ... - maxAllowedTrendLifetime = 0; - - // - detectTrendBullishPivots = false; - detectTrendBearishPivots = false; - - // - // Trigger Block ... - triggerBlockSwingLength = 7; - triggerBlockMaxAllowedRange = 0; - filterTriggerBlocksBySar = true; - triggerBlockBarHasProperSwing = true; - detectTriggerBlockBullishPivots = false; - detectTriggerBlockBearishPivots = false; - triggerBlockBarPressureValidation = true; - - // - } - - // - void Detect( - int barIndex = 0 // - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - int loopback = pivotDetectionLoopbac; - loopback = NormalizeInt(loopback, 50); - - // - int idx = -1; - int count = 0; - bool has = false; - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - - // - newSWHPivotDetected = false; - newSWLPivotDetected = false; - newPeakPivotDetected = false; - newValePivotDetected = false; - newOBBullishPivotDetected = false; - newOBBearishPivotDetected = false; - newFVGBullishPivotDetected = false; - newFVGBearishPivotDetected = false; - newTrendBullishPivotDetected = false; - newTrendBearishPivotDetected = false; - newTriggerBlockBullishPivotDetected = false; - newTriggerBlockBearishPivotDetected = false; - - // - int index = barIndex; - int start = index; - int end = index + loopback; - while (start < end) - { - // - // Retrieve Conditions ... - XCAEAConditions conditions; - has = helper.GetConditions( - conditions, - start, - 10 // - ); - if (!has) - { - conditions.Clean(); - continue; - } - - // - // Retrieve Bars ... - XOHCL zBar; - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - has = zBar.Init( - conditions.symbol, - conditions.period, - start // - ); - has = - has && - zBar.GetPreviousBar(cBar); - has = - has && - cBar.GetPreviousBar(pBar); - has = - has && - pBar.GetPreviousBar(p2Bar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - conditions.Clean(); - - // - continue; - } - - // - // Handle On Time Detection Pivots ... - bool isFirstBar = start == index; - if (isFirstBar) - { - // - // TRIGGER Block ... - // Since Trigger Block Pivots Only Used on Detection Time ... - // we have to Detect only when zBar Index is Zero, means at Last Bar ... - // in this Senario we Have to Ignore LoopBacks ... - - // - // Bullish ... - if (detectTriggerBlockBullishPivots) - { - // - newTriggerBlockBullishPivotDetected = DetectTriggerBlockPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectTriggerBlockBearishPivots) - { - // - newTriggerBlockBearishPivotDetected = DetectTriggerBlockPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - } - - // - // Checking Pivots ... - - // - // SWING ... - - // - // SWH ... - if (detectSWHPivots) - { - // - newSWHPivotDetected = DetectSwingPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // SWL ... - if (detectSWLPivots) - { - // - newSWLPivotDetected = DetectSwingPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // PV ... - - // - // PEAK ... - if (detectPeakPivots) - { - // - newPeakPivotDetected = DetectPeakAndValePivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // VALE ... - if (detectValePivots) - { - // - newValePivotDetected = DetectPeakAndValePivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // FVG ... - - // - // Bullish ... - if (detectFVGBullishPivots) - { - // - newFVGBullishPivotDetected = DetectFVGPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectFVGBearishPivots) - { - // - newFVGBearishPivotDetected = DetectFVGPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // OB ... - - // - // Bullish ... - if (detectOBBullishPivots) - { - // - newOBBullishPivotDetected = DetectOBPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectOBBearishPivots) - { - // - newOBBearishPivotDetected = DetectOBPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // TREND ... - - // - // Bullish ... - if (detectTrendBullishPivots) - { - // - newTrendBullishPivotDetected = DetectTrendPivot( - barIndex, - X_DIRECTION_BULLISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Bearish ... - if (detectTrendBearishPivots) - { - // - newTrendBearishPivotDetected = DetectTrendPivot( - barIndex, - X_DIRECTION_BEARISH, - zBar, - cBar, - pBar, - p2Bar, - conditions // - ); - } - - // - // Others ... - - // - start++; - - // - zBar.Clean(); - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - conditions.Clean(); - } - - // - SortPivots(); - } - - // - void Validate( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - // Implement Validation Senarios ... - - // - // SWING ... - ValidateSwingPivots( - unavailables, - barIndex // - ); - - // - // PV ... - ValidatePeakValePivots( - unavailables, - barIndex // - ); - - // - // OB ... - ValidateOBPivots( - unavailables, - barIndex // - ); - - // - // FVG ... - ValidateFVGPivots( - unavailables, - barIndex // - ); - - // - // TREND ... - ValidateTrendPivots( - unavailables, - barIndex // - ); - - // - // TRIGGER Block ... - ValidateTriggerBlockPivots( - unavailables, - barIndex // - ); - - // - SortPivots(); - } - - // - int FillPivots( - XBoxZone &pivots[], - ENUM_X_DIRECTION forDir = X_DIRECTION_ALL // - ) - { - // - int result = 0; - - // - Clean(pivots); - - // - if (forDir == X_DIRECTION_NONE) - { - return result; - } - - // - int count = 0; - bool has = false; - - // - bool canFillBullish = - forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BULLISH; - - // - bool canFillBearish = - forDir == X_DIRECTION_ALL || - forDir == X_DIRECTION_BEARISH; - - // - // Bullish ... - if (canFillBullish) - { - // - Copy( - swlPivots, - pivots, - false // - ); - - // - Copy( - valePivots, - pivots, - false // - ); - - // - Copy( - obBullishPivots, - pivots, - false // - ); - - // - Copy( - fvgBullishPivots, - pivots, - false // - ); - - // - Copy( - trendBullishPivots, - pivots, - false // - ); - } - - // - // Bearish ... - if (canFillBearish) - { - // - Copy( - swhPivots, - pivots, - false // - ); - - // - Copy( - peakPivots, - pivots, - false // - ); - - // - Copy( - obBearishPivots, - pivots, - false // - ); - - // - Copy( - fvgBearishPivots, - pivots, - false // - ); - - // - Copy( - trendBearishPivots, - pivots, - false // - ); - } - - // - result = ArraySize(pivots); - - // - return result; - } - - // - int FillPivots( - XBoxZone &pivots[], - XBoxZone &unavailables[], - ENUM_XCA_PIVOTS &allowedTypes[], - datetime to = NULL // - ) - { - // - int result = 0; - - // - Clean(pivots); - - // - bool canUpdateTo = IsValid(to); - - // - XBoxZone tmp[]; - bool has = false; - int tmpCount = FillPivots( - tmp, - X_DIRECTION_ALL // - ); - has = IsValidSize(tmpCount); - if (!has) - { - return result; - } - - // - XBoxZone iBox; - while (HasChild(tmp)) - { - // - iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - if (canUpdateTo) - { - iBox.to = to; - } - - // - ENUM_XCA_PIVOTS iType = GetPivotType(iBox); - bool isAllowed = - !HasChild(allowedTypes) - ? true - : Contains( - iType, - allowedTypes // - ); - - // - int idx = -1; - bool isUnAvailable = FindBoxIndex( - idx, - iBox, - unavailables // - ); - - // - if (isAllowed && - !isUnAvailable) - { - // - AddRef( - iBox, - pivots // - ); - } - - // - iBox.Clean(); - } - iBox.Clean(); - - // - result = ArraySize(pivots); - - // - return result; - } - - // - int FillPivots( - XBoxZone &decision, - XBoxZone &pivots[], - XBoxZone &unavailables[], - ENUM_XCA_PIVOTS &allowedTypes[], - datetime to = NULL // - ) - { - // - int result = false; - - // - bool has = false; - has = decision.IsValid(); - if (!has) - { - return result; - } - - // - XBoxZone tmp[]; - int count = FillPivots( - tmp, - unavailables, - allowedTypes, - to // - ); - - // - for (int i = 0; i < count; i++) - { - // - XBoxZone iBox = tmp[i]; - - // - // Validate Box ... - has = - // - // Validate Time .. - iBox.from > decision.from - // - && - // - // Validate Price ... - ( - // - (iBox.upper < decision.upper && - iBox.upper > decision.lower) - // - || - // - (iBox.lower > decision.lower && - iBox.lower < decision.upper) - // - ); - if (has) - { - // - AddRef( - iBox, - pivots // - ); - } - - // - iBox.Clean(); - } - - // - Clean(tmp); - - // - result = ArraySize(pivots); - - // - return result; - } - - // - // Pivots ... - - // - // INVALID Pivots ... - - // - bool HasInvalidPivots() - { - return HasChild(invalidPivots); - } - - // - int CountInvalidPivots() - { - return ArraySize(invalidPivots); - } - - // - // SWING ... - - // - int maxAllowedSwingLifetime; // Max Allowed Swing Life ... - - // - bool DetectSwingPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectSWLPivots - : detectSWHPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // SWING High .. - double zSwingHigh = conditions.swingHighBuffer[zIDX]; - double cSwingHigh = conditions.swingHighBuffer[cIDX]; - double pSwingHigh = conditions.swingHighBuffer[pIDX]; - double p2SwingHigh = conditions.swingHighBuffer[p2IDX]; - - // - // SWING Low ... - double zSwingLow = conditions.swingLowBuffer[zIDX]; - double cSwingLow = conditions.swingLowBuffer[cIDX]; - double pSwingLow = conditions.swingLowBuffer[pIDX]; - double p2SwingLow = conditions.swingLowBuffer[p2IDX]; - - // - // Prepare Conditinal Conditions ... - - // - // SWH ... - - // - bool isSWHSameLast = cSwingHigh == pSwingHigh; - bool isSWHSameLastPrev = pSwingHigh == p2SwingHigh; - - // - bool isSWHSwitchedToSameLast = isSWHSameLast && - !isSWHSameLastPrev; - bool isSWHFinishedFromSameLast = !isSWHSameLast && - isSWHSameLastPrev; - - // - // SWL ... - - // - bool isSWLSameLast = cSwingLow == pSwingLow; - bool isSWLSameLastPrev = pSwingLow == p2SwingLow; - - // - bool isSWLSwitchedToSameLast = isSWLSameLast && - !isSWLSameLastPrev; - bool isSWLFinishedFromSameLast = !isSWLSameLast && - isSWLSameLastPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - // - forBullish - ? isSWLFinishedFromSameLast - : isSWHFinishedFromSameLast - // - ; - - // - bool hasContinuationCondition = - // - forBullish - ? isSWLSameLast - : isSWHSameLast - // - ; - - // - bool hasEndCondition = - // - forBullish - ? isSWLSwitchedToSameLast - : isSWHSwitchedToSameLast - // - ; - - // - // - // - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // SWL ... - if (forBullish) - { - // - swlPivot.Clean(); - - // - swlPivot.type = XCA_SWL; - swlPivot.symbol = symbol; - swlPivot.period = period; - - // - swlPivot.to = pBar.time; - swlPivot.from = pBar.time; - swlPivot.value = pSwingLow; - swlPivot.reserve = pVale; - } - - // - // SWH ... - if (forBearish) - { - // - swhPivot.Clean(); - - // - swhPivot.type = XCA_SWH; - swhPivot.symbol = symbol; - swhPivot.period = period; - - // - swhPivot.to = pBar.time; - swhPivot.from = pBar.time; - swhPivot.value = pSwingHigh; - swhPivot.reserve = pPeak; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // SWL ... - if (forBullish) - { - // - swlPivot.from = pBar.time; - - // - swlPivot.reserve = - swlPivot.reserve == 0 - ? pVale - : MathMin(swlPivot.reserve, pVale); - } - - // - // SWH ... - if (forBearish) - { - // - swhPivot.from = pBar.time; - - // - swhPivot.reserve = - swhPivot.reserve == 0 - ? pPeak - : MathMin(swhPivot.reserve, pPeak); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // SWL ... - if (forBullish) - { - // - result = - swlPivot.IsValid() && - swlPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = swlPivot.AsBox(iBox); - if (result) - { - // - newSWLPivotDetected = AddBox( - iBox, - swlPivots // - ); - } - - // - iBox.Clean(); - } - - // - swlPivot.Clean(); - } - - // - // SWH ... - if (forBearish) - { - // - result = - swhPivot.IsValid() && - swhPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = swhPivot.AsBox(iBox); - if (result) - { - // - newSWHPivotDetected = AddBox( - iBox, - swhPivots // - ); - } - - // - iBox.Clean(); - } - - // - swhPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidateSwingPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedSwingLifetime > 0; - - // - // SWH ... - has = HasSWHPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - swhPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - swhPivots, - maxAllowedSwingLifetime, - barIndex // - ); - } - } - - // - // SWL ... - has = HasSWLPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - swlPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - swlPivots, - maxAllowedSwingLifetime, - barIndex // - ); - } - } - } - - // - // SWL ... - - // - XCAPivot swlPivot; - bool detectSWLPivots; - XBoxZone swlPivots[]; - bool newSWLPivotDetected; - - // - bool HasSWLPivots() - { - return HasChild(swlPivots); - } - - // - int CountSWLPivots() - { - return ArraySize(swlPivots); - } - - // - // SWH ... - - // - XCAPivot swhPivot; - bool detectSWHPivots; - XBoxZone swhPivots[]; - bool newSWHPivotDetected; - - // - bool HasSWHPivots() - { - return HasChild(swhPivots); - } - - // - int CountSWHPivots() - { - return ArraySize(swhPivots); - } - - // - // PV ... - - // - int maxAllowedPVLifetime; // Max Allowed PV Life ... - bool applySwingsOnPVPivots; // Apply Swings on PV Pivots ... - bool selectRejectedPVPivots; // Select Rejected PV Pivots ... - bool selectEngulfedPVPivots; // Select Engulfed PV Pivots ... - bool selectPVWhichStartByFVG; // Select PV Pivots Which Starts by FVG ... - bool applySupportAndResistanceOnPVPivots; // Apply Support and Resistance on PV Pivots ... - - // - bool DetectPeakAndValePivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectValePivots - : detectPeakPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // PEAK Golden ... - double zPeakGolden = conditions.peakGoldenBuffer[zIDX]; - double cPeakGolden = conditions.peakGoldenBuffer[cIDX]; - double pPeakGolden = conditions.peakGoldenBuffer[pIDX]; - double p2PeakGolden = conditions.peakGoldenBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // VALE Golden ... - double zValeGolden = conditions.valeGoldenBuffer[zIDX]; - double cValeGolden = conditions.valeGoldenBuffer[cIDX]; - double pValeGolden = conditions.valeGoldenBuffer[pIDX]; - double p2ValeGolden = conditions.valeGoldenBuffer[p2IDX]; - - // - // SWING High .. - double zSwingHigh = conditions.swingHighBuffer[zIDX]; - double cSwingHigh = conditions.swingHighBuffer[cIDX]; - double pSwingHigh = conditions.swingHighBuffer[pIDX]; - double p2SwingHigh = conditions.swingHighBuffer[p2IDX]; - - // - // SWING Low ... - double zSwingLow = conditions.swingLowBuffer[zIDX]; - double cSwingLow = conditions.swingLowBuffer[cIDX]; - double pSwingLow = conditions.swingLowBuffer[pIDX]; - double p2SwingLow = conditions.swingLowBuffer[p2IDX]; - - // - // SUPPORT ... - double zSupport = conditions.supportBuffer[zIDX]; - double cSupport = conditions.supportBuffer[cIDX]; - double pSupport = conditions.supportBuffer[pIDX]; - double p2Support = conditions.supportBuffer[p2IDX]; - - // - // RESISTANCE ... - double zResistance = conditions.resistanceBuffer[zIDX]; - double cResistance = conditions.resistanceBuffer[cIDX]; - double pResistance = conditions.resistanceBuffer[pIDX]; - double p2Resistance = conditions.resistanceBuffer[p2IDX]; - - // - // Detecting Bar Conditions ... - - // - ENUM_X_DIRECTION cBarDir; - - // - // Rejected ... - bool isCBarRejected = helper - .barAnalyser - .IsRejected( - cBar, - cBarDir, - false, // Force Type ... - false // Force Fibo Pressure ... - ); - - // - bool isCBarBullishRejected = - forBullish && - isCBarRejected && - IsBullish(cBarDir); - bool isCBarBearishRejected = - forBearish && - isCBarRejected && - IsBearish(cBarDir); - - // - bool isPBarRejected = helper - .barAnalyser - .IsRejected( - pBar, - cBarDir, - false, // Force Type ... - false // Force Fibo Pressure ... - ); - bool isPBarBullishRejected = - forBullish && - isPBarRejected && - IsBullish(cBarDir); - bool isPBarBearishRejected = - forBearish && - isPBarRejected && - IsBearish(cBarDir); - - // - bool isBarBullishRejected = - forBullish && - (isCBarBullishRejected || - isPBarBullishRejected); - - // - bool isBarBearishRejected = - forBearish && - (isCBarBearishRejected || - isPBarBearishRejected); - - // - // Engulfed ... - bool isCBarEngulfed = helper - .barAnalyser - .IsEngulfed( - cBar, - cBarDir // - ); - bool isCBarBullishEngulfed = - forBullish && - isCBarEngulfed && - IsBullish(cBarDir); - bool isCBarBearishEngulfed = - forBearish && - isCBarEngulfed && - IsBearish(cBarDir); - - // - bool isPBarEngulfed = helper - .barAnalyser - .IsEngulfed( - pBar, - cBarDir // - ); - bool isPBarBullishEngulfed = - forBullish && - isPBarEngulfed && - IsBullish(cBarDir); - bool isPBarBearishEngulfed = - forBearish && - isPBarEngulfed && - IsBearish(cBarDir); - - // - bool isBarBullishEngulfed = - forBullish && - (isCBarBullishEngulfed || - isPBarBullishEngulfed); - - // - bool isBarBearishEngulfed = - forBearish && - (isCBarBearishEngulfed || - isPBarBearishEngulfed); - - // - // Prepare Conditinal Conditions ... - - // - // PEAK ... - - // - bool isPeakSameLast = cPeak == pPeak; - bool isPeakSameLastPrev = pPeak == p2Peak; - - // - if (applySwingsOnPVPivots) - { - // - isPeakSameLast = - isPeakSameLast && - cSwingHigh == cPeak && - cSwingHigh == pSwingHigh; - - // - isPeakSameLastPrev = - isPeakSameLastPrev && - pSwingHigh == pPeak && - pSwingHigh == p2SwingHigh; - } - - // - if (applySupportAndResistanceOnPVPivots) - { - // - isPeakSameLast = - isPeakSameLast && - cResistance == cPeak && - cResistance == pResistance; - - // - isPeakSameLastPrev = - isPeakSameLastPrev && - pResistance == pPeak && - pResistance == p2Resistance; - } - - // - bool isPeakSwitchedToSameLast = isPeakSameLast && - !isPeakSameLastPrev; - bool isPeakFinishedFromSameLast = !isPeakSameLast && - isPeakSameLastPrev; - - // - // VALE ... - - // - bool isValeSameLast = cVale == pVale; - bool isValeSameLastPrev = pVale == p2Vale; - - // - if (applySwingsOnPVPivots) - { - // - isValeSameLast = - isValeSameLast && - cSwingLow == cVale && - cSwingLow == pSwingLow; - - // - isValeSameLastPrev = - isValeSameLastPrev && - pSwingLow == pVale && - pSwingLow == p2SwingLow; - } - - // - if (applySupportAndResistanceOnPVPivots) - { - // - isValeSameLast = - isValeSameLast && - cSupport == cVale && - cSupport == pSupport; - - // - isValeSameLastPrev = - isValeSameLastPrev && - pSupport == pVale && - pSupport == p2Support; - } - - // - bool isValeSwitchedToSameLast = isValeSameLast && - !isValeSameLastPrev; - bool isValeFinishedFromSameLast = !isValeSameLast && - isValeSameLastPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - // - forBullish - ? isValeFinishedFromSameLast - : isPeakFinishedFromSameLast - // - ; - - // - bool hasContinuationCondition = - // - forBullish - ? isValeSameLast - : isPeakSameLast - // - ; - - // - bool hasEndCondition = - // - forBullish - ? isValeSwitchedToSameLast - : isPeakSwitchedToSameLast - // - ; - - // - // Apply Validations ... - if (hasEndCondition) - { - // - bool hasSelectionType = selectRejectedPVPivots || - selectEngulfedPVPivots; - - // - bool isPVRejected = - forBullish - ? (isBarBullishRejected && - selectRejectedPVPivots) - : (isBarBearishRejected && - selectRejectedPVPivots); - - // - bool isPVEngulfed = - forBullish - ? (isBarBullishEngulfed && - selectEngulfedPVPivots) - : (isBarBearishEngulfed && - selectEngulfedPVPivots); - - // - bool isBarPassed = - !hasSelectionType - ? true - : isPVRejected || - isPVEngulfed; - - // - hasEndCondition = - isBarPassed && - hasEndCondition; - if (!hasEndCondition) - { - // - // VALE ... - if (forBullish) - { - valePivot.Clean(); - } - - // - // PEAK ... - if (forBearish) - { - peakPivot.Clean(); - } - } - } - - // - // - // - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // VALE ... - if (forBullish) - { - // - valePivot.Clean(); - - // - valePivot.type = XCA_VALE; - valePivot.symbol = symbol; - valePivot.period = period; - - // - valePivot.to = pBar.time; - valePivot.from = pBar.time; - valePivot.value = pVale; - valePivot.reserve = pValeGolden; - } - - // - // PEAK ... - if (forBearish) - { - // - peakPivot.Clean(); - - // - peakPivot.type = XCA_PEAK; - peakPivot.symbol = symbol; - peakPivot.period = period; - - // - peakPivot.to = pBar.time; - peakPivot.from = pBar.time; - peakPivot.value = pPeak; - peakPivot.reserve = pPeakGolden; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // VALE ... - if (forBullish) - { - // - valePivot.from = pBar.time; - - // - valePivot.reserve = - valePivot.reserve == 0 - ? pValeGolden - : MathMin(valePivot.reserve, pValeGolden); - } - - // - // PEAK ... - if (forBearish) - { - // - peakPivot.from = pBar.time; - - // - peakPivot.reserve = - peakPivot.reserve == 0 - ? pPeakGolden - : MathMax(peakPivot.reserve, pPeakGolden); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // VALE ... - if (forBullish) - { - // - result = - valePivot.IsValid() && - valePivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = valePivot.AsBox(iBox); - if (result) - { - // - newValePivotDetected = AddBox( - iBox, - valePivots // - ); - } - - // - iBox.Clean(); - } - - // - valePivot.Clean(); - } - - // - // PEAK ... - if (forBearish) - { - // - result = - peakPivot.IsValid() && - peakPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = peakPivot.AsBox(iBox); - if (result) - { - // - newPeakPivotDetected = AddBox( - iBox, - peakPivots // - ); - } - - // - iBox.Clean(); - } - - // - peakPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidatePeakValePivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedPVLifetime > 0; - - // - // PEAK ... - has = HasPeakPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - peakPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - peakPivots, - maxAllowedPVLifetime, - barIndex // - ); - } - } - - // - // VALE ... - has = HasValePivots(); - if (has) - { - // - ApplyValidationOnBoxes( - valePivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - valePivots, - maxAllowedPVLifetime, - barIndex // - ); - } - } - } - - // - // PEAK ... - - // - XCAPivot peakPivot; - bool detectPeakPivots; - XBoxZone peakPivots[]; - bool newPeakPivotDetected; - - // - bool HasPeakPivots() - { - return HasChild(peakPivots); - } - - // - int CountPeakPivots() - { - return ArraySize(peakPivots); - } - - // - // VALE ... - - // - XCAPivot valePivot; - bool detectValePivots; - XBoxZone valePivots[]; - bool newValePivotDetected; - - // - bool HasValePivots() - { - return HasChild(valePivots); - } - - // - int CountValePivots() - { - return ArraySize(valePivots); - } - - // - // OB ... - int maxAllowedOBLifetime; // Max Allowed OB Life ... - - // - bool DetectOBPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectOBBullishPivots - : detectOBBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Prepare Conditinal Conditions ... - - // - // Default OB Detection ... - XBoxZone obBox; - bool isOB = barAnalyser.IsOB( - cBar, - obBox, - true, // OB FVG Bar Type ... - true // TWO Bar Verification ... - ); - bool isBullishOB = - isOB && - forBullish && - obBox.IsBullish(); - bool isBearishOB = - isOB && - forBearish && - obBox.IsBearish(); - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = false; - bool hasContinuationCondition = false; - bool hasEndCondition = isBullishOB || - isBearishOB; - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - XBoxZone iBox; - XCAPivot iPivot; - - // - iPivot.to = obBox.to; - iPivot.from = obBox.from; - iPivot.symbol = obBox.symbol; - iPivot.period = obBox.period; - iPivot.type = forBullish - ? XCA_OB_BULL - : XCA_OB_BEAR; - iPivot.value = forBullish - ? obBox.lower - : obBox.upper; - iPivot.reserve = forBullish - ? obBox.upper - : obBox.lower; - - // - result = iPivot.IsValid(); - if (result) - { - // - result = iPivot.AsBox(iBox); - if (result) - { - // - if (forBullish) - { - // - result = AddBox( - iBox, - obBullishPivots // - ); - } - else - { - // - result = AddBox( - iBox, - obBearishPivots // - ); - } - } - } - - // - iBox.Clean(); - iPivot.Clean(); - } - - // - return result; - } - - // - void ValidateOBPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedOBLifetime > 0; - - // - // Bullish ... - has = HasOBBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - obBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - obBullishPivots, - maxAllowedOBLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasOBBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - obBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - obBearishPivots, - maxAllowedOBLifetime, - barIndex // - ); - } - } - } - - // - // OB Bullish Pivots ... - - // - bool detectOBBullishPivots; - XBoxZone obBullishPivots[]; - bool newOBBullishPivotDetected; - - // - bool HasOBBullishPivots() - { - return HasChild(obBullishPivots); - } - - // - int CountOBBullishPivots() - { - return ArraySize(obBullishPivots); - } - - // - // OB Bearish Pivots ... - - // - bool detectOBBearishPivots; - XBoxZone obBearishPivots[]; - bool newOBBearishPivotDetected; - - // - bool HasOBBearishPivots() - { - return HasChild(obBearishPivots); - } - - // - int CountOBBearishPivots() - { - return ArraySize(obBearishPivots); - } - - // - // FVG ... - - // - bool selectSameBarFVGs; // Select FVGs which has Same Type Bars ... - bool validateFVGUsingPV; // Detect FVG Type Two ( Validating Using PV ) ... - int maxAllowedFVGLifetime; // Max Allowed FVG Life ... - bool applyPVToFVGBoundary; // Apply PV to FVG Boundary ... - bool selectRejectedFVGPivots; // Select Rejected FVG Pivots ... - bool selectEngulfedFVGPivots; // Select Engulfed FVG Pivots ... - bool validateFVGUsingManalyser; // Detect FVG Type One ( Validating Using MAnalyser ) ... - bool applyLastBarToFVGBoundary; // Apply Last Bar to FVG Boundary ... - bool selectOnlyFVGWhichHasIndirectionalLastBar; // Select Only FVGs which has Indirectionsl Last Bar, uses to Order Block ... - - // - bool DetectFVGPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectFVGBullishPivots - : detectFVGBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // PEAK ... - double zPeak = conditions.peakBuffer[zIDX]; - double cPeak = conditions.peakBuffer[cIDX]; - double pPeak = conditions.peakBuffer[pIDX]; - double p2Peak = conditions.peakBuffer[p2IDX]; - - // - // VALE ... - double zVale = conditions.valeBuffer[zIDX]; - double cVale = conditions.valeBuffer[cIDX]; - double pVale = conditions.valeBuffer[pIDX]; - double p2Vale = conditions.valeBuffer[p2IDX]; - - // - // MANALYSER ... - - // - // MAH ... - double zMAH = conditions.mahBuffer[zIDX]; - double cMAH = conditions.mahBuffer[cIDX]; - double pMAH = conditions.mahBuffer[pIDX]; - double p2MAH = conditions.mahBuffer[p2IDX]; - - // - // MAL ... - double zMAL = conditions.malBuffer[zIDX]; - double cMAL = conditions.malBuffer[cIDX]; - double pMAL = conditions.malBuffer[pIDX]; - double p2MAL = conditions.malBuffer[p2IDX]; - - // - // MAC ... - double zMAC = conditions.macBuffer[zIDX]; - double cMAC = conditions.macBuffer[cIDX]; - double pMAC = conditions.macBuffer[pIDX]; - double p2MAC = conditions.macBuffer[p2IDX]; - - // - // Detecting Bar Conditions ... - - // - ENUM_X_DIRECTION p2BarDir; - - // - // Rejected ... - bool isP2BarRejected = helper - .barAnalyser - .IsRejected( - p2Bar, - p2BarDir, - false, // Force Type ... - true // Force Fibo Pressure ... - ); - bool isP2BarBullishRejected = - isP2BarRejected && - IsBullish(p2BarDir); - bool isP2BarBearishRejected = - isP2BarRejected && - IsBearish(p2BarDir); - - // - // Engulfed ... - bool isP2BarEngulfed = helper - .barAnalyser - .IsEngulfed( - p2Bar, - p2BarDir // - ); - bool isP2BarBullishEngulfed = - isP2BarEngulfed && - IsBullish(p2BarDir); - bool isP2BarBearishEngulfed = - isP2BarEngulfed && - IsBearish(p2BarDir); - - // - // Prepare Conditinal Conditions ... - - // - // Default FVG Detection ... - XBoxZone fvgBox; - bool isFVG = barAnalyser.IsFVG( - cBar, - fvgBox // - ); - bool isBullishFVG = - isFVG && - forBullish && - fvgBox.IsBullish(); - bool isBearishFVG = - isFVG && - forBearish && - fvgBox.IsBearish(); - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = false; - bool hasContinuationCondition = false; - bool hasEndCondition = isBullishFVG || - isBearishFVG; - - // - // Apply all Filtering ... - if (hasEndCondition) - { - // - XOHCL p3Bar; - p2Bar.GetPreviousBar(p3Bar); - - // - bool isFVGValid = true; - - // - // Validate FVG Using Manalyser ... - bool isManalyserValid = false; - if (validateFVGUsingManalyser) - { - // - isManalyserValid = - hasEndCondition && - (forBullish - ? fvgBox.upper <= cMAL - : fvgBox.lower >= cMAH); - } - - // - // Validate FVG Using PV ... - bool isPVValid = false; - if (validateFVGUsingPV) - { - // - isPVValid = - hasEndCondition && - (forBullish - ? (p2Peak < pPeak || - pPeak < cPeak) - : (p2Vale > pVale || - pVale > cVale)); - } - - // - // Select Pure FVG ... - bool isPureFVGValid = - !validateFVGUsingPV && - !validateFVGUsingManalyser; - - // - // Summarise Validation ... - isFVGValid = - isPVValid || - isPureFVGValid || - isManalyserValid; - - // - bool isFVGBarPassed = false; - - // - // Select Same Bars FVGs ... - bool isFVGHasSameBar = true; - if (selectSameBarFVGs) - { - // - isFVGHasSameBar = - forBullish - ? (cBar.IsBullish() && - pBar.IsBullish() && - p2Bar.IsBullish()) - : (cBar.IsBearish() && - pBar.IsBearish() && - p2Bar.IsBearish()); - isFVGBarPassed = - isFVGBarPassed || - isFVGHasSameBar; - } - - // - // Select Rejected FVG ... - bool isFVGRejected = true; - if (selectRejectedFVGPivots) - { - // - isFVGRejected = - (forBullish - ? isP2BarBullishRejected - : isP2BarBearishRejected); - isFVGBarPassed = - isFVGBarPassed || - isFVGRejected; - } - - // - // Select Engulfed FVG ... - bool isFVGEngulfed = true; - if (selectEngulfedFVGPivots) - { - // - isFVGEngulfed = - (forBullish - ? isP2BarBullishEngulfed - : isP2BarBearishEngulfed); - isFVGBarPassed = - isFVGBarPassed || - isFVGEngulfed; - } - - // - // Select Only FVGs Which Has Indirectional Last Bar ... - bool isFVGHasIndirectionalStart = true; - if (selectOnlyFVGWhichHasIndirectionalLastBar) - { - // - isFVGHasIndirectionalStart = - p3Bar.IsValid() && - (forBullish - ? p3Bar.IsBearish() - : p3Bar.IsBullish()); - isFVGBarPassed = - isFVGBarPassed || - isFVGHasIndirectionalStart; - } - - // - // Summarise Bar Pass ... - isFVGBarPassed = - (selectSameBarFVGs || - selectRejectedFVGPivots || - selectEngulfedFVGPivots || - selectOnlyFVGWhichHasIndirectionalLastBar) - ? isFVGBarPassed - : true; - - // - hasEndCondition = isFVGValid && - isFVGBarPassed; - - // - // Apply Boundary ... - if (hasEndCondition) - { - // - double iValue = - forBullish - ? fvgBox.upper - : fvgBox.lower; - - // - if (applyPVToFVGBoundary) - { - // - fvgBox.upper = - forBullish - ? fvgBox.upper - : cPeak; - - // - fvgBox.lower = - forBullish - ? cVale - : fvgBox.lower; - } - - // - if (applyLastBarToFVGBoundary) - { - // - fvgBox.lower = MathMin(p3Bar.low, fvgBox.lower); - fvgBox.upper = MathMax(p3Bar.high, fvgBox.upper); - } - } - - // - p3Bar.Clean(); - } - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - XBoxZone iBox; - XCAPivot iPivot; - - // - iPivot.to = fvgBox.to; - iPivot.from = fvgBox.from; - iPivot.symbol = fvgBox.symbol; - iPivot.period = fvgBox.period; - iPivot.type = forBullish - ? XCA_FVG_BULL - : XCA_FVG_BEAR; - iPivot.value = forBullish - ? fvgBox.lower - : fvgBox.upper; - iPivot.reserve = forBullish - ? fvgBox.upper - : fvgBox.lower; - - // - result = iPivot.IsValid(); - if (result) - { - // - result = iPivot.AsBox(iBox); - if (result) - { - // - if (forBullish) - { - // - result = AddBox( - iBox, - fvgBullishPivots // - ); - } - else - { - // - result = AddBox( - iBox, - fvgBearishPivots // - ); - } - } - } - - // - iBox.Clean(); - iPivot.Clean(); - } - - // - return result; - } - - // - void ValidateFVGPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedFVGLifetime > 0; - - // - // Bullish ... - has = HasFVGBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - fvgBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - fvgBullishPivots, - maxAllowedFVGLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasFVGBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - fvgBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - fvgBearishPivots, - maxAllowedFVGLifetime, - barIndex // - ); - } - } - } - - // - // FVG Bullish Pivots ... - - // - bool detectFVGBullishPivots; - XBoxZone fvgBullishPivots[]; - bool newFVGBullishPivotDetected; - - // - bool HasFVGBullishPivots() - { - return HasChild(fvgBullishPivots); - } - - // - int CountFVGBullishPivots() - { - return ArraySize(fvgBullishPivots); - } - - // - // FVG Bearish Pivots ... - - // - bool detectFVGBearishPivots; - XBoxZone fvgBearishPivots[]; - bool newFVGBearishPivotDetected; - - // - bool HasFVGBearishPivots() - { - return HasChild(fvgBearishPivots); - } - - // - int CountFVGBearishPivots() - { - return ArraySize(fvgBearishPivots); - } - - // - // TREND ... - - // - int maxAllowedTrendLifetime; // Max Allowed Trend Life ... - - // - bool DetectTrendPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectTrendBullishPivots - : detectTrendBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // TREND ... - double zTrend = conditions.trendBuffer[zIDX]; - double cTrend = conditions.trendBuffer[cIDX]; - double pTrend = conditions.trendBuffer[pIDX]; - double p2Trend = conditions.trendBuffer[p2IDX]; - - // - // TREND State ... - double zTrendState = conditions.trendStateBuffer[zIDX]; - double cTrendState = conditions.trendStateBuffer[cIDX]; - double pTrendState = conditions.trendStateBuffer[pIDX]; - double p2TrendState = conditions.trendStateBuffer[p2IDX]; - - // - // Prepare Conditinal Conditions ... - - // - // Bullish ... - - // - bool isTrendBullish = - cTrendState > 0; - bool isTrendBullishPrev = - pTrendState > 0; - - // - bool isTrendSwitchedToBullish = isTrendBullish && - !isTrendBullishPrev; - bool isTrendFinishedFromBullish = !isTrendBullish && - isTrendBullishPrev; - - // - // Bearish ... - - // - bool isTrendBearish = - cTrendState < 0; - bool isTrendBearishPrev = - pTrendState < 0; - - // - bool isTrendSwitchedToBearish = isTrendBearish && - !isTrendBearishPrev; - bool isTrendFinishedFromBearish = !isTrendBearish && - isTrendBearishPrev; - - // - // Summarizing Conditions ... - - // - result = false; - - // - bool hasStartCondition = - forBullish - ? isTrendFinishedFromBullish - : isTrendFinishedFromBearish; - bool hasContinuationCondition = - forBullish - ? isTrendBullish - : isTrendBearish; - bool hasEndCondition = - forBullish - ? isTrendSwitchedToBullish - : isTrendSwitchedToBearish; - - // - // ReInstance Pivot ... - if (hasStartCondition) - { - // - // Bullish ... - if (forBullish) - { - // - trendBullishPivot.Clean(); - - // - trendBullishPivot.symbol = symbol; - trendBullishPivot.period = period; - trendBullishPivot.type = XCA_TREND_BULL; - - // - trendBullishPivot.to = pBar.time; - trendBullishPivot.from = pBar.time; - trendBullishPivot.value = pTrend; - trendBullishPivot.reserve = pTrend; - } - - // - // Bearish ... - if (forBearish) - { - // - trendBearishPivot.Clean(); - - // - trendBearishPivot.symbol = symbol; - trendBearishPivot.period = period; - trendBearishPivot.type = XCA_TREND_BEAR; - - // - trendBearishPivot.to = pBar.time; - trendBearishPivot.from = pBar.time; - trendBearishPivot.value = pTrend; - trendBearishPivot.reserve = pTrend; - } - } - - // - // Calculate and Fill Pivot Requirements ... - if (hasContinuationCondition) - { - // - // Bullish ... - if (forBullish) - { - // - trendBullishPivot.from = pBar.time; - - // - Add( - pTrend, - trendBullishPivot.values // - ); - Add( - pTrend, - trendBullishPivot.values // - ); - } - - // - // Bearish ... - if (forBearish) - { - // - trendBearishPivot.from = pBar.time; - - // - Add( - pTrend, - trendBearishPivot.values // - ); - Add( - pTrend, - trendBearishPivot.values // - ); - } - } - - // - // End up Pivot and Store it ... - if (hasEndCondition) - { - // - // Bullish ... - if (forBullish) - { - // - // Update Values ... - trendBullishPivot.value = GetMin(trendBullishPivot.values); - trendBullishPivot.reserve = GetMax(trendBullishPivot.values); - - // - result = - trendBullishPivot.IsValid() && - trendBullishPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = trendBullishPivot.AsBox(iBox); - if (result) - { - // - newTrendBullishPivotDetected = AddBox( - iBox, - trendBullishPivots // - ); - } - - // - iBox.Clean(); - } - - // - trendBullishPivot.Clean(); - } - - // - // Bearish ... - if (forBearish) - { - // - // Update Values ... - trendBearishPivot.value = GetMax(trendBearishPivot.values); - trendBearishPivot.reserve = GetMin(trendBearishPivot.values); - - // - result = - trendBearishPivot.IsValid() && - trendBearishPivot.GetAge() >= pivotVerifications; - if (result) - { - // - XBoxZone iBox; - result = trendBearishPivot.AsBox(iBox); - if (result) - { - // - newTrendBearishPivotDetected = AddBox( - iBox, - trendBearishPivots // - ); - } - - // - iBox.Clean(); - } - - // - trendBearishPivot.Clean(); - } - } - - // - return result; - } - - // - void ValidateTrendPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - bool applyLifetimeValidating = maxAllowedTrendLifetime > 0; - - // - // Bullish ... - has = HasTrendBullishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - trendBullishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - trendBullishPivots, - maxAllowedTrendLifetime, - barIndex // - ); - } - } - - // - // Bearish ... - has = HasTrendBearishPivots(); - if (has) - { - // - ApplyValidationOnBoxes( - trendBearishPivots, - unavailables, - barIndex // - ); - - // - if (applyLifetimeValidating) - { - // - ApplyLifeTimeValidationOnBoxes( - trendBearishPivots, - maxAllowedTrendLifetime, - barIndex // - ); - } - } - } - - // - // Bullish ... - - // - XCAPivot trendBullishPivot; - XBoxZone trendBullishPivots[]; - bool detectTrendBullishPivots; - bool newTrendBullishPivotDetected; - - // - bool HasTrendBullishPivots() - { - return HasChild(trendBullishPivots); - } - - // - int CountTrendBullishPivots() - { - return ArraySize(trendBullishPivots); - } - - // - // Bearish ... - - // - XCAPivot trendBearishPivot; - XBoxZone trendBearishPivots[]; - bool detectTrendBearishPivots; - bool newTrendBearishPivotDetected; - - // - bool HasTrendBearishPivots() - { - return HasChild(trendBearishPivots); - } - - // - int CountTrendBearishPivots() - { - return ArraySize(trendBearishPivots); - } - - // - // TRIGGER Blocks ... - - // - int triggerBlockSwingLength; - int filterTriggerBlocksBySar; - double triggerBlockMaxAllowedRange; - bool triggerBlockBarHasProperSwing; - bool triggerBlockBarPressureValidation; - - // - bool DetectTriggerBlockPivot( - int barIndex, - ENUM_X_DIRECTION forDir, - XOHCL &zBar, - XOHCL &cBar, - XOHCL &pBar, - XOHCL &p2Bar, - XCAEAConditions &conditions // - ) - { - // - bool result = false; - - // - // Checking Direction ... - result = HasDirection(forDir); - if (!result) - { - return result; - } - - // - bool forBullish = IsBullish(forDir); - bool forBearish = IsBearish(forDir); - - // - // Check Allowed ... - result = - forBullish - ? detectTriggerBlockBullishPivots - : detectTriggerBlockBearishPivots; - if (!result) - { - return result; - } - - // - // Validate Args ... - result = - // - barIndex >= 0 && - zBar.IsValid() && - cBar.IsValid() && - pBar.IsValid() && - p2Bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Define Requirements ... - - // - int zIDX = 0; - int cIDX = zIDX + 1; - int pIDX = cIDX + 1; - int p2IDX = pIDX + 1; - int p3IDX = p2IDX + 1; - - // - datetime cTime = zBar.time; - string symbol = zBar.symbol; - ENUM_TIMEFRAMES period = zBar.period; - double points = GetPoints(symbol); - - // - // Reading Conditional Values ... - - // - // Prepare Conditinal Conditions ... - - // - // Checking Base Block Exists ... - XBoxZone iBlock; - result = helper.barAnalyser.IsOB( - cBar, - iBlock, - true, // Force FVG Bar Type ... - true // Force Two Bar ... - ); - if (!result) - { - // - iBlock.Clean(); - - // - return result; - } - - // - // Bullish ... - bool isBullish = - result && - forBullish && - iBlock.IsBullish(); - - // - // Bearish ... - bool isBearish = - result && - forBearish && - iBlock.IsBearish(); - - // - // Summarizing Conditions ... - - // - result = isBullish || - isBearish; - if (!result) - { - // - iBlock.Clean(); - - // - return result; - } - - // - // Adding Pivot to Box Type ... - string iType = isBullish - ? GetBoxType(XCA_TRIGGER_BULL) - : GetBoxType(XCA_TRIGGER_BEAR); - iBlock.type = iType; - - // - // Validate TriggerBlock ... - XOHCL p3Bar; - XOHCL p4Bar; - result = - p2Bar.GetPreviousBar(p3Bar); - result = - result && - p3Bar.GetPreviousBar(p4Bar); - if (!result) - { - // - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - - // - return result; - } - ENUM_X_DIRECTION iDir; - - // - // Validating Range ... - if (triggerBlockMaxAllowedRange > 0) - { - // - double blockRange = iBlock.GetRange(); - result = blockRange <= triggerBlockMaxAllowedRange * points; - if (!result) - { - // - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - - // - return result; - } - } - - // - // Validate Using Swing Bars ... - if (triggerBlockBarHasProperSwing) - { - // - // Check Has Proper Swing ... - - // - // CBar ... - bool isCBarSimpleSwing = - barAnalyser.IsSimpleSwing( - cBar, - iDir // - ); - bool isCBarBullishSimpleSwing = - isCBarSimpleSwing && - IsBullish(iDir); - bool isCBarBearishSimpleSwing = - isCBarSimpleSwing && - IsBearish(iDir); - - // - // PBar ... - bool isPBarSimpleSwing = - barAnalyser.IsSimpleSwing( - pBar, - iDir // - ); - bool isPBarBullishSimpleSwing = - isPBarSimpleSwing && - IsBullish(iDir); - bool isPBarBearishSimpleSwing = - isPBarSimpleSwing && - IsBearish(iDir); - - // - // P2Bar ... - bool isP2BarSimpleSwing = - barAnalyser.IsSimpleSwing( - p2Bar, - iDir // - ); - bool isP2BarBullishSimpleSwing = - isP2BarSimpleSwing && - IsBullish(iDir); - bool isP2BarBearishSimpleSwing = - isP2BarSimpleSwing && - IsBearish(iDir); - - // - // P3Bar ... - bool isP3BarSimpleSwing = - barAnalyser.IsSimpleSwing( - p3Bar, - iDir // - ); - bool isP3BarBullishSimpleSwing = - isP3BarSimpleSwing && - IsBullish(iDir); - bool isP3BarBearishSimpleSwing = - isP3BarSimpleSwing && - IsBearish(iDir); - - // - // P4Bar ... - bool isP4BarSimpleSwing = - barAnalyser.IsSimpleSwing( - p4Bar, - iDir // - ); - bool isP4BarBullishSimpleSwing = - isP4BarSimpleSwing && - IsBullish(iDir); - bool isP4BarBearishSimpleSwing = - isP4BarSimpleSwing && - IsBearish(iDir); - - // - // Summarise Validation ... - - // - bool isBullishSwimpleSwing = - isBullish && - (isCBarBullishSimpleSwing || - isPBarBullishSimpleSwing || - isP2BarBullishSimpleSwing || - isP3BarBullishSimpleSwing || - isP4BarBullishSimpleSwing); - - // - bool isBearishSwimpleSwing = - isBearish && - (isCBarBearishSimpleSwing || - isPBarBearishSimpleSwing || - isP2BarBearishSimpleSwing || - isP3BarBearishSimpleSwing || - isP4BarBearishSimpleSwing); - - // - result = isBullishSwimpleSwing || - isBearishSwimpleSwing; - if (!result) - { - // - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - - // - return result; - } - } - - // - // Validating Using Bar Pressure ... - if (triggerBlockBarPressureValidation) - { - // - // Check pBar is Momentum Bar ... - // and Breakd Block Side ... - - // - bool isCBarMomentum = barAnalyser.IsMomentum( - pBar, - iDir // - ); - bool isCBarBullishMomentum = - isCBarMomentum && - IsBullish(iDir); - bool isCBarBearishMomentum = - isCBarMomentum && - IsBearish(iDir); - - // - bool isPBarMomentum = barAnalyser.IsMomentum( - pBar, - iDir // - ); - bool isPBarBullishMomentum = - isPBarMomentum && - IsBullish(iDir); - bool isPBarBearishMomentum = - isPBarMomentum && - IsBearish(iDir); - - // - bool isBullishBreakedOut = - isBullish && - forBullish && - pBar.IsBullish() && - (isCBarBullishMomentum || - isPBarBullishMomentum) && - pBar.GetUp() > iBlock.upper && - pBar.GetDown() < iBlock.upper; - - // - bool isBearishBreakedOut = - isBearish && - forBearish && - pBar.IsBearish() && - (isCBarBearishMomentum || - isPBarBearishMomentum) && - pBar.GetUp() > iBlock.lower && - pBar.GetDown() < iBlock.lower; - - // - result = - isBullishBreakedOut || - isBearishBreakedOut; - if (!result) - { - // - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - - // - return result; - } - } - - // - // Extract to and from Info ... - - // - int toIDX = iBlock.ToIndex(); - int fromIDX = iBlock.FromIndex(); - - // - XOHCL toBar; - XOHCL fromBar; - - // - result = iBlock.ToBar(toBar); - result = result && - iBlock.FromBar(fromBar); - if (!result) - { - // - toBar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - fromBar.Clean(); - - // - return result; - } - - // - // Validating Using HH and LL ... - if (triggerBlockSwingLength > 0) - { - // - double toLL = toBar.FindLowest(triggerBlockSwingLength, MODE_LOW); - double toHH = toBar.FindHighest(triggerBlockSwingLength, MODE_HIGH); - - // - double fromLL = fromBar.FindLowest(triggerBlockSwingLength, MODE_LOW); - double fromHH = fromBar.FindHighest(triggerBlockSwingLength, MODE_HIGH); - - // - double selectedLL = fromLL; // MathMin(toLL, fromLL); - double selectedHH = fromHH; // MathMax(toHH, fromHH); - - // - bool isBullishSwingPassed = - isBullish && - forBullish && - selectedLL >= iBlock.lower; - - // - bool isBearishSwingPassed = - isBearish && - forBearish && - selectedHH <= iBlock.upper; - - // - result = isBullishSwingPassed || - isBearishSwingPassed; - if (!result) - { - // - toBar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - fromBar.Clean(); - - // - return result; - } - } - - // - // Apply Filters ... - bool hasFilter = - filterTriggerBlocksBySar; - if (hasFilter) - { - // - // Sar Filtering ... - if (filterTriggerBlocksBySar) - { - // - // Reading Conditions ... - - // - double zSar = conditions.sarBuffer[zIDX]; - double cSar = conditions.sarBuffer[cIDX]; - double pSar = conditions.sarBuffer[pIDX]; - double p2Sar = conditions.sarBuffer[p2IDX]; - double p3Sar = conditions.sarBuffer[p3IDX]; - - // - // Preparing Constom Conditions ... - - // - bool isZSarBullish = zSar < zBar.low; - bool isCSarBullish = cSar < cBar.low; - bool isPSarBullish = pSar < pBar.low; - bool isP2SarBullish = p2Sar < p2Bar.low; - bool isP3SarBullish = p3Sar < p3Bar.low; - - // - bool isZSarBearish = zSar > zBar.high; - bool isCSarBearish = cSar > cBar.high; - bool isPSarBearish = pSar > pBar.high; - bool isP2SarBearish = p2Sar > p2Bar.high; - bool isP3SarBearish = p3Sar > p3Bar.high; - - // - bool isCSarSwitchedToBullish = - isCSarBullish && - !isPSarBullish; - bool isPSarSwitchedToBullish = - isPSarBullish && - !isP2SarBullish; - bool isP2SarSwitchedToBullish = - isP2SarBullish && - !isP3SarBullish; - - // - bool isCSarSwitchedToBearish = - isCSarBearish && - !isPSarBearish; - bool isPSarSwitchedToBearish = - isPSarBearish && - !isP2SarBearish; - bool isP2SarSwitchedToBearish = - isP2SarBearish && - !isP3SarBearish; - - // - // Summarize Custom Conditions ... - - // - // Bullish ... - - // - bool isCSarBullishPassed = - isZSarBullish && - isCSarSwitchedToBullish; - - // - bool isPSarBullishPassed = - isZSarBullish && - isCSarBullish && - isPSarSwitchedToBullish; - - // - bool isP2SarBullishPassed = - isZSarBullish && - isCSarBullish && - isPSarBullish && - isP2SarSwitchedToBullish; - - // - // Bearish ... - - // - bool isCSarBearishPassed = - isZSarBearish && - isCSarSwitchedToBearish; - - // - bool isPSarBearishPassed = - isZSarBearish && - isCSarBearish && - isPSarSwitchedToBearish; - - // - bool isP2SarBearishPassed = - isZSarBearish && - isCSarBearish && - isPSarBearish && - isP2SarSwitchedToBearish; - - // - // Summarize Conditions ... - - // - bool isBullishFiltered = - isBullish && - forBullish && - (isCSarBullishPassed || - isPSarBullishPassed || - isP2SarBullishPassed); - - // - bool isBearishFiltered = - isBearish && - forBearish && - (isCSarBearishPassed || - isPSarBearishPassed || - isP2SarBearishPassed); - - // - result = isBullishFiltered || - isBearishFiltered; - if (!result) - { - // - toBar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - fromBar.Clean(); - - // - return result; - } - } - } - - // - // Summarize ... - - // - isBullish = - isBullish && - forBullish && - iBlock.IsValid(); - - // - isBearish = - isBearish && - forBearish && - iBlock.IsValid(); - - // - result = isBullish || - isBearish; - if (!result) - { - iBlock.Clean(); - } - - // - // Storing Pivot ... - - // - if (isBullish) - { - // - result = AddBox( - iBlock, - triggerBlockBullishPivots // - ); - } - - // - if (isBearish) - { - // - result = AddBox( - iBlock, - triggerBlockBearishPivots // - ); - } - - // - // Cleanup Resource ... - - // - toBar.Clean(); - p3Bar.Clean(); - p4Bar.Clean(); - iBlock.Clean(); - fromBar.Clean(); - - // - return result; - } - - // - void ValidateTriggerBlockPivots( - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - // Since Trigger Blocks Doesnt Use Multiple Times, - // there is not any Validation Required for them ... - bool has = false; - - // - // bool applyLifetimeValidating = maxAllowedTriggerBlockLifetime > 0; - - // - // Bullish ... - has = HasTriggerBlockBullishPivots(); - if (has) - { - } - - // - // Bearish ... - has = HasTriggerBlockBearishPivots(); - if (has) - { - } - } - - // - // Bullish ... - - // - XBoxZone triggerBlockBullishPivots[]; - bool detectTriggerBlockBullishPivots; - bool newTriggerBlockBullishPivotDetected; - - // - bool HasTriggerBlockBullishPivots() - { - return HasChild(triggerBlockBullishPivots); - } - - // - int CountTriggerBlockBullishPivots() - { - return ArraySize(triggerBlockBullishPivots); - } - - // - // Bearish ... - - // - bool detectTriggerBlockBearishPivots; - XBoxZone triggerBlockBearishPivots[]; - bool newTriggerBlockBearishPivotDetected; - - // - bool HasTriggerBlockBearishPivots() - { - return HasChild(triggerBlockBearishPivots); - } - - // - int CountTriggerBlockBearishPivots() - { - return ArraySize(triggerBlockBearishPivots); - } - - // - // Protected ... - protected: - // - // Props ... - - // - // Prrivate ... - private: - // - // Props ... - - // - XCPOIDrawer *drawer; - XCXCAEAHelper *helper; - XCBarAnalyser *barAnalyser; - - // - bool AddBox( - XBoxZone &box, - XBoxZone &boxes[] // - ) - { - // - bool result = false; - - // - result = box.IsValid(); - if (!result) - { - return result; - } - - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - box, - boxes // - ); - result = !isExists; - if (!result) - { - return result; - } - - // - int before = ArraySize(boxes); - - // - AddRef( - box, - boxes // - ); - - // - int after = ArraySize(boxes); - - // - result = after > before; - - // - return result; - } - - // - bool ValidateBox( - XBoxZone &box, - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool result = false; - - // - // Normalize Bar Index ... - barIndex = NormalizeInt(barIndex, 0); - - // - // Ceck Input Box is Valid ... - result = box.IsValid(); - if (!result) - { - return result; - } - - // - // Check Input Box is Available ... - bool canCheckUnAvailableBoxes = HasChild(unavailables); - if (canCheckUnAvailableBoxes) - { - // - int idx = -1; - bool isUnAvailable = FindBoxIndex( - idx, - box, - unavailables // - ); - result = !isUnAvailable; - if (!result) - { - return result; - } - } - - // - // Check Input Box is Breaked or not ... - - // - // Check Bar Index must after Box To Index ... - int toIDX = box.ToIndex(); - int fromIDX = box.FromIndex(); - result = toIDX > barIndex && - fromIDX > barIndex && - fromIDX > toIDX; - if (!result) - { - return result; - } - - // - // Detect Box Applied Boundary Price ... - // For Checking Break of Box ... - bool isBullish = box.IsBullish(); - double boundary = - isBullish - ? box.lower - : box.upper; - - // - // for validating Box Break we have to wait At Least 3 Bars Close - // out of Box Boundary ... - int barsLength = 3; - - // - // Calculate Start Checking Bar Index ... - int startCheckBreaktionBarIndex = toIDX - barsLength; - bool isBarIndexValid = startCheckBreaktionBarIndex > 0 && - barIndex < startCheckBreaktionBarIndex; - result = isBarIndexValid; - if (!result) - { - // - // Assume Box is Valid if Bar Index not Valid for Checking ... - result = true; - return result; - } - - // - // Try to Check Box Validation if Everything is OK ... - XOHCL cBar; - XOHCL pBar; - XOHCL p2Bar; - bool isValid = false; - bool isBreaked = false; - for (int i = barIndex; i < startCheckBreaktionBarIndex; i++) - { - // - // Initialize Bars ... - isValid = cBar.Init( - box.symbol, - box.period, - i + 1 // - ); - isValid = - result && - cBar.GetPreviousBar(pBar); - isValid = - result && - pBar.GetPreviousBar(p2Bar); - if (!isValid) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - result = false; - - // - break; - } - - // - // Preparing Conditions ... - - // - bool isBullishBreaked = - isBullish && - cBar.close < boundary && - pBar.close < boundary && - p2Bar.close < boundary; - - // - bool isBearishBreaked = - !isBullish && - cBar.close > boundary && - pBar.close > boundary && - p2Bar.close > boundary; - - // - // Calculate Result ... - isBreaked = isBullishBreaked || - isBearishBreaked; - if (isBreaked) - { - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - result = false; - - // - break; - } - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - } - - // - result = isValid && - !isBreaked; - if (!result) - { - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - box, - invalidPivots // - ); - if (!isExists) - { - // - AddRef( - box, - invalidPivots // - ); - } - } - - // - // Cleanup Resource ... - - // - cBar.Clean(); - pBar.Clean(); - p2Bar.Clean(); - - // - return result; - } - - // - void CleanPivots() - { - // - Clean(invalidPivots); - - // - swlPivot.Clean(); - swhPivot.Clean(); - peakPivot.Clean(); - valePivot.Clean(); - trendBullishPivot.Clean(); - trendBearishPivot.Clean(); - - // - Clean(swlPivots); - Clean(swhPivots); - - // - Clean(peakPivots); - Clean(valePivots); - - // - Clean(obBullishPivots); - Clean(obBearishPivots); - - // - Clean(fvgBullishPivots); - Clean(fvgBearishPivots); - - // - Clean(trendBullishPivots); - Clean(trendBearishPivots); - - // - Clean(triggerBlockBullishPivots); - Clean(triggerBlockBearishPivots); - } - - // - void SortPivots() - { - // - bool has = false; - - // - // Invalid Pivots ... - has = HasInvalidPivots(); - if (has) - { - ApplySortOnBoxes(invalidPivots); - } - - // - // SWING ... - - // - // SWH ... - has = HasSWHPivots(); - if (has) - { - ApplySortOnBoxes(swhPivots); - } - - // - // SWL ... - has = HasSWLPivots(); - if (has) - { - ApplySortOnBoxes(swlPivots); - } - - // - // PV ... - - // - // PEAK ... - has = HasPeakPivots(); - if (has) - { - ApplySortOnBoxes(peakPivots); - } - - // - // VALE ... - has = HasValePivots(); - if (has) - { - ApplySortOnBoxes(valePivots); - } - - // - // OB ... - - // - // Bullish ... - has = HasOBBullishPivots(); - if (has) - { - ApplySortOnBoxes(obBullishPivots); - } - - // - // Bearish ... - has = HasOBBearishPivots(); - if (has) - { - ApplySortOnBoxes(obBearishPivots); - } - - // - // FVG ... - - // - // Bullish ... - has = HasFVGBullishPivots(); - if (has) - { - ApplySortOnBoxes(fvgBullishPivots); - } - - // - // Bearish ... - has = HasFVGBearishPivots(); - if (has) - { - ApplySortOnBoxes(fvgBearishPivots); - } - - // - // TREND ... - - // - // Bullish ... - has = HasTrendBullishPivots(); - if (has) - { - ApplySortOnBoxes(trendBullishPivots); - } - - // - // Bearish ... - has = HasTrendBearishPivots(); - if (has) - { - ApplySortOnBoxes(trendBearishPivots); - } - - // - // TRIGGER Block ... - - // - // Bullish ... - has = HasTriggerBlockBullishPivots(); - if (has) - { - ApplySortOnBoxes(triggerBlockBullishPivots); - } - - // - // Bearish ... - has = HasTriggerBlockBearishPivots(); - if (has) - { - ApplySortOnBoxes(triggerBlockBearishPivots); - } - } - - // - void ApplySortOnBoxes( - XBoxZone &items[] // - ) - { - // - int idx = -1; - bool has = false; - - // - has = HasChild(items); - if (!has) - { - return; - } - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - - // - while (HasChild(tmp)) - { - // - idx = GetOldest(tmp); - has = IsValidIndex(idx); - if (!has) - { - break; - } - - // - XBoxZone iBox = tmp[idx]; - ArrayRemove( - tmp, - idx, - 1 // - ); - - // - AddRef( - iBox, - items // - ); - } - - // - CleanupArray( - items, - maxAllowedPivots // - ); - - // - Clean(tmp); - } - - // - void ApplyValidationOnBoxes( - XBoxZone &items[], - XBoxZone &unavailables[], - int barIndex = 0 // - ) - { - // - bool has = false; - - // - has = HasChild(items); - if (!has) - { - return; - } - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - while (HasChild(tmp)) - { - // - XBoxZone iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - has = ValidateBox( - iBox, - unavailables, - barIndex // - ); - if (has) - { - // - AddRef( - iBox, - items // - ); - } - - // - iBox.Clean(); - // - } - - // - Clean(tmp); - } - - // - void ApplyLifeTimeValidationOnBoxes( - XBoxZone &items[], - int maxAllowedAge = 0, - int barIndex = 0 // - ) - { - // - bool has = false; - - // - barIndex = NormalizeInt(barIndex, 0); - - // - has = - maxAllowedAge > 0 && - HasChild(items); - if (!has) - { - return; - } - - // - datetime cTime = GetBarTime( - helper.GetSymbol(), - helper.GetPeriod(), - barIndex // - ); - - // - XBoxZone tmp[]; - Copy( - items, - tmp // - ); - Clean(items); - - // - while (HasChild(tmp)) - { - // - XBoxZone iBox = tmp[0]; - ArrayRemove( - tmp, - 0, - 1 // - ); - - // - datetime defTo = iBox.to; - iBox.to = cTime; - - // - int iAge = iBox.GetAge(); - has = iAge <= maxAllowedAge; - iBox.to = defTo; - if (has) - { - // - AddRef( - iBox, - items // - ); - } - else - { - // - int idx = -1; - bool isExists = FindBoxIndex( - idx, - iBox, - invalidPivots // - ); - if (!isExists) - { - // - AddRef( - iBox, - invalidPivots // - ); - } - } - - // - iBox.Clean(); - } - - // - Clean(tmp); - } - - // -}; - -// \ 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 cefd7d17..00000000 --- a/Documents/BKP/xcatb.test.ea.mq5 +++ /dev/null @@ -1,1143 +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-alert.class.mq5" -#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" -#include "../Classes/x-saherelm.x-poi.drawer.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" -#include "../Helpers/x-saherelm.x121.xcatb.helper.mq5" -#include "../XCATBEA/Classes/xcatbea.signaller.class.mq5" -#include "../XCATBEA/Classes/xcatbea.x-trade.manager.class.mq5" -#include "../XCATBEA/Libraries/xcatbea.signaller.lib.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 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 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 - -// -// 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 => (SYDNEY_02:00_14:00),(NY_19:00_23:00) -input group "Management"; -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 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 - -// -// Variables ... - -// -XCAlert *eaAlert; -XCTrade *eaTrade; -XSignal eaSignal; -string eaTag = ""; -XCVolume *eaVolume; -XTriggerBlock eaTB; -CArrayObj *eaObjects; -XCPOIDrawer *eaDrawer; -XBarTracker eaBarTraker; -X121XCatbInputs eaInputs; -XTimeTracker eaTimeTracker; -XCX121XCatbHelper *eaHelper; -XCBarAnalyser *eaBarAnalyser; -XTriggerBlockFilters eaFilters; -X121XCatbConditions eaCatbConditions; -XCXCATBEATradeManager *eaTradeManager; -XCATBEAStrategyConditions eaConditions; -XTriggerBlockValidationRules eaValidations; - -// -// 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 - - // - // eaObjects.Clear(); - - // - delete eaHelper; - ZeroMemory(eaHelper); - - // - delete eaAlert; - ZeroMemory(eaAlert); - - // - delete eaTrade; - ZeroMemory(eaTrade); - - // - delete eaDrawer; - ZeroMemory(eaDrawer); - - // - delete eaVolume; - ZeroMemory(eaVolume); - - // - delete eaBarAnalyser; - ZeroMemory(eaBarAnalyser); - - // - eaTB.Clean(); - eaSignal.Clean(); - eaSignal.Clean(); - eaFilters.Clean(); - eaBarTraker.Clean(); - eaConditions.Clean(); - eaConditions.Clean(); - eaTimeTracker.Clean(); - eaValidations.Clean(); - eaCatbConditions.Clean(); - - // - DestroyTimer(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - // Handle Tradings ... - bool tradeUsingTriggerBlock = true; - bool tradeUsingMarketConditions1 = true; - - // - HandleTimeReport(); - - // - // Handle Position Management / Protections ... - eaTradeManager.Manage(); - - // - eaTB.Clean(); - eaSignal.Clean(); - eaConditions.Clean(); - eaCatbConditions.Clean(); - - // - bool has = false; - int barIndex = 0; - int cBarIndex = 0; - - // - // Check Bar Processing ... - if (!eaBarTraker.CanProcessBar()) - { - return; - } - - // - eaHelper.Check(barIndex); - - // - // Reading Required Bars ... - XOHCL zBar; - XOHCL cBar; - has = zBar.Init( - _Symbol, - _Period, - barIndex // - ); - has = - has && - zBar.GetPreviousBar(cBar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - - // - return; - } - - // - cBarIndex = barIndex + 1; - - // - // Update All Required Buffers ... - eaHelper.Update(cBarIndex); - - // - // Check Trigger Block Detected or Not ... - if (tradeUsingTriggerBlock) - { - // - // Trigger Block Detection ... - has = DetectTriggerBlock1( - eaHelper, - eaBarAnalyser, - eaTB, - eaCatbConditions, - eaValidations, - eaFilters, - barIndex, - 10 // Loopback ... - ); - - // - if (has) - { - // - // Wait for Next Bar for anything ... - eaBarTraker.Waits(); - - // - // Prepare Target ... - double targets[]; - for (int i = 1; i <= eaSignalR2R; i++) - { - // - Add( - (double)i, - targets // - ); - } - - // - // Calculate SL Additions ... - double iATR = 0; - if (barIndex > 0 && - barIndex < ArraySize(eaHelper.atrBuffer)) - { - iATR = eaHelper.atrBuffer[barIndex]; - } - double slAdditional = eaSLAtrMultiplier * iATR; - - // - // Preparing Signal ... - has = ToSignal( - eaTB.trigger, - eaTB.signal, - targets, - slAdditional // - ); - - // - // Draw Trigger Block ... - DrawTriggerBlock( - eaTB, - eaDrawer, - eaObjects, - NULL // - ); - - // - // Attach Signal ... - eaSignal = eaTB.signal; - - // - // Check Signal Type ... - bool isLong = IsLong(eaSignal.type); - - // - // Update Entry ... - eaSignal.entry = GetEntry( - eaSignal.symbol, - eaSignal.type // - ); - - // - // Update Signal Targets ... - UpdateSignalTargets(eaSignal); - - // - // Handle Volume Management ... - double iVolume = eaVolume.CalculateVolume(eaSignal); - if (iVolume > X_MIN_VOLUME && - iVolume != eaSignal.volume) - { - eaSignal.volume = iVolume; - } - - // - eaConditions.sl = eaSignal.sl; - eaConditions.tp = eaSignal.tp; - eaConditions.pivot = eaSignal.sl; - eaConditions.time = eaSignal.time; - eaConditions.reward = eaSignalR2R; - eaConditions.point = eaSignal.entry; - eaConditions.entry = eaSignal.entry; - eaConditions.symbol = eaSignal.symbol; - eaConditions.period = eaSignal.period; - eaConditions.setupTime = eaSignal.time; - eaConditions.triggerTime = eaSignal.time; - eaConditions.decisionZone = eaTB.trigger; - eaConditions.provider = eaSignal.provider; - eaConditions.conditions = eaCatbConditions; - eaConditions.type = ToPositionType(eaSignal.type); - eaConditions.dir = - isLong - ? X_DIRECTION_BULLISH - : X_DIRECTION_BEARISH; - Copy( - eaSignal.targets, - eaConditions.targets // - ); - eaSignal.conditions = - eaCatbConditions - .GenerateSummary( - false, // Commons ... - true, // Conditions ... - true, // Scores ... - false // Ignore Falses ... - ); - - // - // Execute Signal ... - has = eaTradeManager.Execute( - eaSignal, - eaConditions // - ); - } - - // - eaTB.Clean(); - } - - // - // Trade Using Market Conditions ... - if (tradeUsingMarketConditions1) - { - // - XBoxZone signalZone; - X121XCatbConditions conditions; - has = DetectSignalZone( - eaDrawer, - eaHelper, - eaBarAnalyser, - signalZone, - conditions, - barIndex // - ); - if (has) - { - // - // Convert Box to Signal ... - } - } - - // - // Cleanup Resources ... - - // - zBar.Clean(); - cBar.Clean(); - eaTB.Clean(); - eaSignal.Clean(); - eaConditions.Clean(); - eaCatbConditions.Clean(); -} - -// -// 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() -{ - // - // Initial Bar Tracker ... - eaBarTraker.Init( - _Symbol, - _Period // - ); - - // - // 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); - - // - // Objects ... - eaObjects = new CArrayObj(); - - // - // Configure XCA ... - eaInputs.Default(); - - // - // Hide all Visible Buffers ... - eaInputs.Hide(); - - // - // we Can make Show all requirements here ... - - // - eaInputs.showPV = true; - eaInputs.showSar = true; - eaInputs.showTrend = true; - eaInputs.showATRBand = true; - eaInputs.showPVGolden = true; - - // - eaHelper = new XCX121XCatbHelper(); - bool isInited = eaHelper.Init( - _Symbol, - _Period, - eaInputs // - ); - - // - eaDrawer = new XCPOIDrawer(); - eaBarAnalyser = new XCBarAnalyser(); - - // - // 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); - - // - // Setting Trade Reports ... - eaTradeManager - .SetTradeReports( - eaReportTrades, - eaReportSignals, - eaReportProtector, - eaReportAfterTradesBalance // - ); - - // - // Setting Trade Permissions ... - eaTradeManager - .SetTradePermissions( - eaAllowTrade, - eaAllowLongs, - eaAllowShorts // - ); - - // - // Setting Trade Restrictions ... - eaTradeManager - .SetTradeRestrictions( - eaRestrictionsPeriod, - eaMaxAllowedTPs, - eaMaxAllowedSLs, - eaMaxAllowedTrades // - ); - - // - // 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]); - 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 // - ); - } - } - } - } - } - } - - // - // Fill Validations ... - eaValidations.forceHasSwing = eaForceHasSwing; - eaValidations.forceOBBarType = eaForceOBBarType; - eaValidations.minRequiredOBBar = eaMinRequiredOBBar; - eaValidations.forceFVGBarType = eaForceFVGBarType; - eaValidations.liquidityLoopback = eaLiquidityLoopback; - eaValidations.maxAllowedRange = eaMaxAllowedRange; - eaValidations.minAllowedRange = eaMinAllowedRange; - eaValidations.forceHasFLiquidity = eaForceHasFLiquidity; - eaValidations.forceHasRLiquidity = eaForceHasRLiquidity; - eaValidations.validateGapSequence = eaValidateGapSequence; - eaValidations.minAllowedBlockLength = eaMinAllowedBlockLength; - eaValidations.validateBlockEdgeBreakout = eaValidateBlockEdgeBreakout; - - // - // Fill Filters ... - - // - eaFilters.filterBasedOnPV = eaFilterBasedOnPV; - eaFilters.bosLoopback = eaBosLoopback; - - // - eaFilters.filterBasedOnSar = eaFilterBasedOnSar; - eaFilters.forceSarSwitched = eaForceSarSwitched; - eaFilters.forceSarOnBothSide = eaForceSarOnBothSide; - eaFilters.forceSarHasBreakout = eaForceSarHasBreakout; - eaFilters.forceSarHasReversalSide = eaForceSarHasReversalSide; - - // - eaFilters.filterBasedOnRSI = eaFilterBasedOnRSI; - eaFilters.forceHasRSITrending = eaForceHasRSITrending; - eaFilters.forceHasRSIVPattern = eaForceHasRSIVPattern; - eaFilters.forceHasRSICrossing = eaForceHasRSICrossing; - - // - eaFilters.filterBasedOnADX = eaFilterBasedOnADX; - eaFilters.forceHasADXTrending = eaForceHasADXTrending; - eaFilters.forceHasADXCrossing = eaForceHasADXCrossing; - - // - eaFilters.filterBasedOnATR = eaFilterBasedOnATR; - eaFilters.forceHasATRTrending = eaForceHasATRTrending; - eaFilters.forceHasATRBreakout = eaForceHasATRBreakout; - - // - eaFilters.filterBasedOnTrend = eaFilterBasedOnTrend; - eaFilters.forceHasTrendDir = eaForceHasTrendDir; - eaFilters.forceHasTrendPlace = eaForceHasTrendPlace; - eaFilters.forceHasTrendChange = eaForceHasTrendChange; - eaFilters.forceHasTrendTrending = eaForceHasTrendTrending; - eaFilters.forceHasTrendRejection = eaForceHasTrendRejection; - eaFilters.forceHasTrendLineInside = eaForceHasTrendLineInside; - eaFilters.forceHasTrendDirOnBothSide = eaForceHasTrendDirOnBothSide; - - // - eaFilters.filterBasedOnDelta = eaFilterBasedOnDelta; - eaFilters.filterBasedOnVolume = eaFilterBasedOnVolume; - eaFilters.filterBasedOnSignalBar = eaFilterBasedOnSignalBar; - eaFilters.filterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar; - - // -} - -/** - * 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 // - ); -} - -// \ No newline at end of file diff --git a/Documents/BKP/xcatb.tm.inputs.mq5 b/Documents/BKP/xcatb.tm.inputs.mq5 deleted file mode 100644 index 313c39d3..00000000 --- a/Documents/BKP/xcatb.tm.inputs.mq5 +++ /dev/null @@ -1,316 +0,0 @@ -// -// Market ... -ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period -ENUM_TIMEFRAMES scPeriod = NULL; // Short Period -ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period -ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period -ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period -ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period -ENUM_X_MARKET_CYCLES appliedCycle = X_MARKET_CYCLE_HIND; // Applied Cycle - -// -// Signal ... -int signalR2R = 4; // Risk Reward Ratio -bool drawSignals = true; // Draw Signal -double slAtrMultiplier = 1.0; // ATR Multiplier for SL - -// -// Validating ... -bool forceHasSwing = false; // Force Blocks to Have Swing -bool forceObBarType = false; // Force Block Has Reversal Bar -bool forceOBFVGBarType = false; // Force FVG Has Same Bars -bool forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -bool forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -bool validateGapSequence = false; // Validate Block's Gap Sequence -bool validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -bool filterBasedOnPV = false; // Filter Based on Peak and Vale -bool filterBasedOnSar = false; // Filter Based on Sar -bool filterBasedOnRSI = false; // Filter Based on RSI -bool filterBasedOnADX = false; // Filter Based on ADX -bool filterBasedOnATR = false; // Filter Based on ATR -bool filterBasedOnTrend = false; // Filter Based on Trend -bool filterBasedOnDelta = false; // Filter Based on Delta -bool filterBasedOnVolume = false; // Filter Based on Volume -bool filterBasedOnSignalBar = false; // Filter Based on Signal Bar -bool filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -string mAlertPrefix = ""; // Alert Prefix -bool _logAlerts = true; // Log Alerts -bool _pushAlerts = false; // Push Alerts -bool _mailAlerts = false; // Mail Alerts -bool _terminalAlerts = true; // Terminal Alerts - -// -// Presentation ... -bool showBars = true; // Show Bars -bool showPV = false; // Show PV -bool showPVGolden = false; // Show PV Golden -bool showSar = false; // Show Sar -bool showTrend = false; // Show Trend -bool showATRBand = false; // Show ATR Band -bool showTrendBars = false; // Show Trend Bars -bool showSignalBars = false; // Show Signal Bars -bool showHKSignalBars = false; // Show Hiken Ashi Signal Bars - -// -int startCalculationForLastBars = 1500; // Calculate Last n Bars - -///////////////////////////////////////////////////////////////// - -// -// Market ... -ENUM_X_PERIOD_METHOD scMethod; // How to Find Short Period -ENUM_TIMEFRAMES scPeriod; // Short Period -ENUM_X_PERIOD_METHOD mcMethod; // How to Find Medium Period -ENUM_TIMEFRAMES mcPeriod; // Medium Period -ENUM_X_PERIOD_METHOD lcMethod; // How to Find Long Period -ENUM_TIMEFRAMES lcPeriod; // Long Period -ENUM_X_PERIOD_METHOD hcMethod; // How to Find Hind Period -ENUM_TIMEFRAMES hcPeriod; // Hind Period -ENUM_X_MARKET_CYCLES appliedCycle; // Applied Cycle - -// -// Signal ... -int signalR2R; // Risk Reward Ratio -bool drawSignals; // Draw Signal -double slAtrMultiplier; // ATR Multiplier for SL - -// -// Validating ... -bool forceHasSwing; // Force Blocks to Have Swing -bool forceObBarType; // Force Block Has Reversal Bar -bool forceOBFVGBarType; // Force FVG Has Same Bars -bool forceHasFLiquidity; // Force Blocks to Have Following Liquidity -bool forceHasRLiquidity; // Force Blocks to Have Reversal Liquidity -bool validateGapSequence; // Validate Block's Gap Sequence -bool validateBlockEdgeBreakout; // Validate Block's Edge Breakout - -// -// Filtering ... -bool filterBasedOnPV; // Filter Based on Peak and Vale -bool filterBasedOnSar; // Filter Based on Sar -bool filterBasedOnRSI; // Filter Based on RSI -bool filterBasedOnADX; // Filter Based on ADX -bool filterBasedOnATR; // Filter Based on ATR -bool filterBasedOnTrend; // Filter Based on Trend -bool filterBasedOnDelta; // Filter Based on Delta -bool filterBasedOnVolume; // Filter Based on Volume -bool filterBasedOnSignalBar; // Filter Based on Signal Bar -bool filterBasedOnHKSignalBar; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -string alertPrefix; // Alert Prefix -bool logAlerts; // Log Alerts -bool pushAlerts; // Push Alerts -bool mailAlerts; // Mail Alerts -bool terminalAlerts; // Terminal Alerts - -// -// Presentation ... -bool showBars; // Show Bars -bool showPV; // Show PV -bool showPVGolden; // Show PV Golden -bool showSar; // Show Sar -bool showTrend; // Show Trend -bool showATRBand; // Show ATR Band -bool showTrendBars; // Show Trend Bars -bool showSignalBars; // Show Signal Bars -bool showHKSignalBars; // Show Hiken Ashi Signal Bars - -// -int startCalculationForLastBars; // Calculate Last n Bars - -////////////////////////////////////////////////////////////////////// - -// -// Market ... -scMethod = X_PERIOD_AUTO; // How to Find Short Period -scPeriod = NULL; // Short Period -mcMethod = X_PERIOD_AUTO; // How to Find Medium Period -mcPeriod = NULL; // Medium Period -lcMethod = X_PERIOD_AUTO; // How to Find Long Period -lcPeriod = NULL; // Long Period -hcMethod = X_PERIOD_AUTO; // How to Find Hind Period -hcPeriod = NULL; // Hind Period -appliedCycle = X_MARKET_CYCLE_HIND; // Applied Cycle - -// -// Signal ... -signalR2R = 4; // Risk Reward Ratio -drawSignals = true; // Draw Signal -slAtrMultiplier = 1.0; // ATR Multiplier for SL - -// -// Validating ... -forceHasSwing = false; // Force Blocks to Have Swing -forceObBarType = false; // Force Block Has Reversal Bar -forceOBFVGBarType = false; // Force FVG Has Same Bars -forceHasFLiquidity = false; // Force Blocks to Have Following Liquidity -forceHasRLiquidity = false; // Force Blocks to Have Reversal Liquidity -validateGapSequence = false; // Validate Block's Gap Sequence -validateBlockEdgeBreakout = false; // Validate Block's Edge Breakout - -// -// Filtering ... -filterBasedOnPV = false; // Filter Based on Peak and Vale -filterBasedOnSar = false; // Filter Based on Sar -filterBasedOnRSI = false; // Filter Based on RSI -filterBasedOnADX = false; // Filter Based on ADX -filterBasedOnATR = false; // Filter Based on ATR -filterBasedOnTrend = false; // Filter Based on Trend -filterBasedOnDelta = false; // Filter Based on Delta -filterBasedOnVolume = false; // Filter Based on Volume -filterBasedOnSignalBar = false; // Filter Based on Signal Bar -filterBasedOnHKSignalBar = false; // Filter Based on Hiken Ashi Signal Bar - -// -// Alert ... -mAlertPrefix = ""; // Alert Prefix -_logAlerts = true; // Log Alerts -_pushAlerts = false; // Push Alerts -_mailAlerts = false; // Mail Alerts -_terminalAlerts = true; // Terminal Alerts - -// -// Presentation ... -showBars = true; // Show Bars -showPV = false; // Show PV -showPVGolden = false; // Show PV Golden -showSar = false; // Show Sar -showTrend = false; // Show Trend -showATRBand = false; // Show ATR Band -showTrendBars = false; // Show Trend Bars -showSignalBars = false; // Show Signal Bars -showHKSignalBars = false; // Show Hiken Ashi Signal Bars - -// -startCalculationForLastBars = 1500; // Calculate Last n Bars - - -////////////////////////////////////////////////////////////////////////////// - - X121_XCATB_SAR_LINE - sarBuffer - - X121_XCATB_SAR_STATE_LINE - sarStateBuffer - - X121_XCATB_PEAK_LINE - peakBuffer - - X121_XCATB_VALE_LINE - valeBuffer - - X121_XCATB_PEAK_GOLDEN_LINE - peakGoldenBuffer - - X121_XCATB_VALE_GOLDEN_LINE - valeGoldenBuffer - - X121_XCATB_ATR_BAND_UPPER_LINE - atrUpperBuffer - - X121_XCATB_ATR_BAND_LOWER_LINE - atrLowerBuffer - - X121_XCATB_TREND_LINE - trendBuffer - - X121_XCATB_TREND_STATE_LINE - trendStateBuffer - - X121_XCATB_SBAR_O_LINE - sBarOpenSBuffer - - X121_XCATB_SBAR_C_LINE - sBarCloseBuffer - - X121_XCATB_HK_SBAR_O_LINE - hkSBarOpenBuffer - - X121_XCATB_HK_SBAR_C_LINE - hkSBarCloseBuffer - - X121_XCATB_S_HH_LINE - sHHBuffer - - X121_XCATB_S_LL_LINE - sLLBuffer - - X121_XCATB_M_HH_LINE - mHHBuffer - - X121_XCATB_M_LL_LINE - mLLBuffer - - X121_XCATB_L_HH_LINE - lHHBuffer - - X121_XCATB_L_LL_LINE - lLLBuffer - - X121_XCATB_H_HH_LINE - hHHBuffer - - X121_XCATB_H_LL_LINE - hLLBuffer - - X121_XCATB_RSI_LINE - rsiBuffer - - X121_XCATB_ADX_LINE - adxBuffer - - X121_XCATB_ADXP_LINE - adxpBuffer - - X121_XCATB_ADXN_LINE - adxnBuffer - - X121_XCATB_DELTA_LINE - deltaBuffer - - X121_XCATB_DELTA_SIGNAL_LINE - deltaSignalBuffer - - X121_XCATB_VOLUME_BULLISH_LINE - bullishVolumeBuffer - - X121_XCATB_VOLUME_BEARISH_LINE - bearishVolumeBuffer - - X121_XCATB_VOLUME_VOLUME_BULLISH_SIGNAL_LINE - bullishVolumeSignalBuffer - - X121_XCATB_VOLUME_VOLUME_BEARISH_SIGNAL_LINE - bearishVolumeSignalBuffer - - X121_XCATB_ATR_LINE - atrBuffer - - X121_XCATB_ATR_BAND_RAW_UPPER_LINE - atrUpperBuffer - - X121_XCATB_ATR_BAND_RAW_LOWER_LINE - atrLowerBuffer - - X121_XCATB_HK_BAR_O_LINE - hkOpenBuffer - - X121_XCATB_HK_BAR_H_LINE - hkHighBuffer - - X121_XCATB_HK_BAR_L_LINE - hkLowBuffer - - X121_XCATB_HK_BAR_C_LINE - hkCloseBuffer - diff --git a/Documents/BKP/xczone.test.ea.mq5 b/Documents/BKP/xczone.test.ea.mq5 deleted file mode 100644 index fb359b70..00000000 --- a/Documents/BKP/xczone.test.ea.mq5 +++ /dev/null @@ -1,1082 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center XCZone MQL5 Expert Advisor -// ------------------------------------------------- -// Name: XCAEA -// Description: an Exper Advisor which used XCZone -// -// 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 XCZone indicators" -#property strict - -// -// Include Common Library ... -#include "../Classes/x-saherelm.x-alert.class.mq5" -#include "../Classes/x-saherelm.x-trade.class.mq5" -#include "../Classes/x-saherelm.x-volume.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../XCAEA/Classes/xcaea.x-trade.manager.class.mq5" -#include "../XCAEA/Helpers/xcaea.helper.mq5" -#include "../XCAEA/Libraries/xcaea.trigger.block.lib.mq5" - -// -#define ShortName "XCZONEEA" - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long eaMagicNumber = 78692110; // Magic Number -input int eaSlippage = 10; // Slippgae -input string eaLogSuffix = ""; // Log Suffix - -// -// Detector ... -input group "Detector"; - -// -// Ranges ... -input double eaMaxAllowedRange = 0.0; // Maximum Allowed Range -input int eaMinAllowedBlockEdgeLength = 7; // Minimum Required Block Edge Length - -// -// Validation ... -input bool eaForceFVGBarType = true; // Force FVG to Has Same Type of Bars -input bool eaForceHasSwingBar = true; // Force Has Propper Swing -input bool eaForceOBOppositBar = true; // Force OB to Start by Opposit Bars -input bool eaForceHasLiquidity = false; // Force Has Following Liquidity Zone -input bool eaForceGapBarBreakout = true; // Force FVG's Gap Bar to Breakeout OB Edge Side -input bool eaForceHasReversalLiquidity = true; // Force Has Reversal Liquidity Zone - -// -// Filtering ... -input bool eaFilterBasedOnSar = true; // Filter Trigger Block Based on Sar -input bool eaFilterBasedOnRSI = true; // Filter Trigger Block Based on RSI -input bool eaFilterBasedOnADX = true; // Filter Trigger Block Based on ADX -input bool eaFilterBasedOnTrend = true; // Filter Trigger Block Based on Trend -input bool eaFilterBasedOnScores = true; // Filter Trigger Block Based on Scores -input bool eaFilterBasedOnVolumes = true; // Filter Trigger Block Based on Volumes - -// -// Signals ... -input group "Signals"; -input double maxAllowedR2R = 2; // Max Allowed R2R -input double eaSLAdditionalPoint = 0.0; // Additional SL in Point -input double eaSLATRMultiplier = 0.0; // Additional SL using ATR Multiplier - -// -// 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 ... -input group "Management"; -input bool eaAllowTrade = true; // Allow Trade on Signals -input bool eaAllowLongs = true; // Allow Long Trades -input bool eaAllowShorts = true; // Allow Short Trades -input ENUM_XCAEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCAEA_TRADE_RESTRICATION_NONE; // Trade Restrictions Period -input int eaMaxAllowedTPs = 0; // Max Allowed TP(s) per Day -input int eaMaxAllowedSLs = 0; // Max Allowed SL(s) per Day -input int eaMaxAllowedTrades = 0; // Max Allowed Trades per Day -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 = false; // 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 eaReportProtector = true; // Report Protector Actions -input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished - -// -// Variables ... - -// -XCAlert *eaAlert; -XCTrade *eaTrade; -XSignal eaSignal; -XCVolume *eaVolume; -XCAEAInputs eaInputs; -XCXCAEAHelper *eaHelper; -XBarTracker eaBarTraker; -XTimeTracker eaTimeTracker; -XCXCAEATradeManager *eaTradeManager; -XCAEAStrategyConditions eaConditions; - -// -XTriggerBlock eaTB; -XBoxZone eaUpperRange; -XBoxZone eaLowerRange; -XCAEATriggerBlockConfiguration eaTBConfig; - -// -CArrayObj *eaObjects; - -// -string eaTag = ""; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs and Required Parameters - // for EA to Works fine ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initial Requirements ... - InitRequirements(); - - // - // Configure Detector ... - ConfigureDetector(); - - // - // 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 - - // - // eaObjects.Clear(); - - // - delete eaHelper; - ZeroMemory(eaHelper); - - // - delete eaAlert; - ZeroMemory(eaAlert); - - // - delete eaTrade; - ZeroMemory(eaTrade); - - // - delete eaVolume; - ZeroMemory(eaVolume); - - // - eaSignal.Clean(); - eaTBConfig.Clean(); - eaBarTraker.Clean(); - eaConditions.Clean(); - eaTimeTracker.Clean(); - - // - DestroyTimer(); -} - -// -// On Tick Handler ... -void OnTick() -{ - // - HandleTimeReport(); - - // - // Handle Position Management / Protections ... - eaTradeManager.Manage(); - - // - eaSignal.Clean(); - eaConditions.Clean(); - - // - // Check Bar Processing ... - if (!eaBarTraker.CanProcessBar()) - { - return; - } - - // - bool has = false; - - // - // Retrieve Bars ... - XOHCL zBar; - XOHCL cBar; - has = zBar.Init( - _Symbol, - _Period, - 0 // - ); - has = - has && - zBar.GetPreviousBar(cBar); - if (!has) - { - // - zBar.Clean(); - cBar.Clean(); - - // - return; - } - - // - double bid = GetBid(zBar.symbol); - - // - // Detect Range Blocks ... - double mid = 0; - double range = 0; - XBoxZone upperRNGB; - XBoxZone lowerRNGB; - bool isIn = false; - has = eaHelper - .barAnalyser - .DetectRangeBlocks( - zBar, - upperRNGB, - lowerRNGB, - (288 * 5) // - ); - if (has) - { - // - // Setting Range Boxes ... - upperRNGB.to = zBar.time; - lowerRNGB.to = zBar.time; - eaUpperRange.to = zBar.time; - eaLowerRange.to = zBar.time; - - // - bool canSet = false; - - // - // Set Upper Range ... - canSet = !eaUpperRange.IsValid() - ? true - : upperRNGB.upper > eaUpperRange.upper; - if (canSet) - { - eaUpperRange = upperRNGB; - } - - // - // Set Lower Range ... - canSet = !eaLowerRange.IsValid() - ? true - : lowerRNGB.lower < eaLowerRange.lower; - if (canSet) - { - eaLowerRange = lowerRNGB; - } - } - - // - // Calculate Requirements ... - range = eaUpperRange.lower - eaLowerRange.upper; - mid = eaUpperRange.lower - (range / 2); - - // - double price = zBar.close; // bid; - - // - // Check Price in Upper Tange ... - bool isInUpperRange = - price >= eaUpperRange.lower && - price <= eaUpperRange.upper; - - // - // Check Price in Lower Range ... - bool isInLowerRange = - price >= eaLowerRange.lower && - price <= eaLowerRange.upper; - - // - isIn = isInUpperRange || - isInLowerRange; - if (isIn) - { - // - if (isInUpperRange) { - eaLowerRange = lowerRNGB; - } - - // - if (isInLowerRange) { - eaUpperRange = upperRNGB; - } - - // - Print("IsIn ..."); - } - - // - // Do Detection ... - has = DetectTriggerBlock( - eaTB, - eaHelper, - eaTBConfig, - zBar.Index(), - 10, - eaSLAdditionalPoint, - eaSLATRMultiplier // - ); - if (has) - { - // - bool isBullish = eaTB.trigger.IsBullish(); - - // - has = - isBullish - ? zBar.close < mid - : zBar.close > mid; - if (!has) - { - eaTB.Clean(); - } - } - - // - // Draws ... - - // - // Darw Ranges ... - has = eaUpperRange.IsValid() && - eaLowerRange.IsValid(); - if (has) - { - // - // Draw Ranges ... - - // - // Draw Upper Range ... - XCBoxObject *iUpperObj; - has = eaHelper.poiDrawer.DrawBox( - eaUpperRange, - iUpperObj // - ); - if (has) - { - // - // Style Object ... - - // - // Store Object ... - eaObjects.Add(iUpperObj); - } - - // - // Draw Lower Range ... - XCBoxObject *iLowerObj; - has = eaHelper.poiDrawer.DrawBox( - eaLowerRange, - iLowerObj // - ); - if (has) - { - // - // Style Object ... - - // - // Store Object ... - eaObjects.Add(iLowerObj); - } - - // - // Draw Fibonacchi ... - } - - // - // Draw Trigger Block ... - has = eaTB.IsValid(); - if (has) - { - // - if (eaTB.signal.IsValid()) - { - // - eaSignal = eaTB.signal; - - // - eaConditions.symbol = eaTB.signal.symbol; - eaConditions.period = eaTB.signal.period; - eaConditions.conditions = eaTB.conditions; - } - - // - CArrayObj *tObjects; - tObjects = new CArrayObj(); - - // - has = DrawTriggerBlock( - eaTB, - tObjects, - eaHelper, - NULL, // zBar.time, - 0 // Prevent Drawing RR Zones ... - ); - if (has) - { - AddObjects(tObjects, eaObjects); - } - } - - // - // Handle Signals ... - - // - // Check Signal Validation ... - if (eaSignal.IsValid()) - { - // - // Do What we Want ... - // When we Need Waits Until Next Bar ... - eaBarTraker.Waits(); - - // - bool isLong = IsLong(eaSignal.type); - - // - // Update Entry ... - eaSignal.entry = GetEntry( - eaSignal.symbol, - eaSignal.type // - ); - - // - // Try to Check Liquidity ... - if (eaTB.rLiquidity.IsValid()) - { - // - double irLQRange = eaTB.rLiquidity.GetRange(); - eaSignal.sl = - isLong - ? eaSignal.sl - irLQRange - : eaSignal.sl + irLQRange; - } - - // - // Apply Signal Targets ... - ApplySignalTargets(eaSignal); - - // - // Handle Volume Management ... - double iVolume = eaVolume.CalculateVolume(eaSignal); - if (iVolume > X_MIN_VOLUME && - iVolume != eaSignal.volume) - { - eaSignal.volume = iVolume; - } - - // - // Execute Signal ... - has = eaTradeManager.Execute( - eaSignal, - eaConditions // - ); - } - - // - // Cleanup Resources ... - - // - eaTB.Clean(); - zBar.Clean(); - cBar.Clean(); - eaSignal.Clean(); - eaConditions.Clean(); -} - -// -// 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; - - // - // Initial Bar Tracker ... - eaBarTraker.Init( - _Symbol, - _Period // - ); - - // - // Objects ... - eaObjects = new CArrayObj(); - - // - // Configure XCA ... - eaInputs.Default(); - - // - // Hide all Visible Buffers ... - eaInputs.Hide(); - - // - // we Can make Show all requirements here ... - eaInputs.caInputs.showSar = false; - - // - eaHelper = new XCXCAEAHelper(); - bool isInited = eaHelper.Init( - _Symbol, - _Period, - eaInputs // - ); - - // - // EA Alert ... - eaAlert = new XCAlert( - eaTag, - eaEnableAlerts, - eaLogAlerts, - eaTerminalAlerts, - eaMailAlerts, - eaPushAlerts // - ); - - // - // 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 XCXCAEATradeManager( - eaTrade // - ); - eaTradeManager.SaveTrades(true); - eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts); - eaTradeManager.SetAlertPrefix(eaTag); - eaTradeManager.SetAlertLogAlerts(eaLogAlerts); - eaTradeManager.SetAlertMailAlerts(eaMailAlerts); - eaTradeManager.SetAlertPushAlerts(eaPushAlerts); - eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts); - - // - // Setting Trade Reports ... - eaTradeManager - .SetTradeReports( - eaReportTrades, - eaReportSignals, - eaReportProtector, - eaReportAfterTradesBalance // - ); - - // - // Setting Trade Permissions ... - eaTradeManager - .SetTradePermissions( - eaAllowTrade, - eaAllowLongs, - eaAllowShorts // - ); - - // - // Setting Trade Restrictions ... - eaTradeManager - .SetTradeRestrictions( - eaRestrictionsPeriod, - eaMaxAllowedTPs, - eaMaxAllowedSLs, - eaMaxAllowedTrades // - ); -} - -// -void ConfigureDetector() -{ - // - // Configure Detector ... - - // - // Validation ... - eaTBConfig.maxAllowedRange = eaMaxAllowedRange; - eaTBConfig.minAllowedBlockEdgeLength = eaMinAllowedBlockEdgeLength; - - // - // Validation ... - eaTBConfig.forceFVGBarType = eaForceFVGBarType; - eaTBConfig.forceHasSwingBar = eaForceHasSwingBar; - eaTBConfig.forceOBOppositBar = eaForceOBOppositBar; - eaTBConfig.forceHasLiquidity = eaForceHasLiquidity; - eaTBConfig.forceGapBarBreakout = eaForceGapBarBreakout; - eaTBConfig.forceHasReversalLiquidity = eaForceHasReversalLiquidity; - - // - // Filters ... - eaTBConfig.filterBasedOnSar = eaFilterBasedOnSar; - eaTBConfig.filterBasedOnADX = eaFilterBasedOnADX; - eaTBConfig.filterBasedOnRSI = eaFilterBasedOnRSI; - eaTBConfig.filterBasedOnTrend = eaFilterBasedOnTrend; - eaTBConfig.filterBasedOnScores = eaFilterBasedOnScores; - eaTBConfig.filterBasedOnVolumes = eaFilterBasedOnVolumes; - - // - // Targets ... - double targets[] = { - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - }; - Copy( - targets, - eaTBConfig.targets // - ); -} - -/** - * Handling Time Reporting ... - */ -void HandleTimeReport() -{ - // - // 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); - } -} - -// -// Apply Signal Targets ... -void ApplySignalTargets(XSignal &signal) -{ - // - bool has = signal.IsValid(); - if (!has) - { - return; - } - - // - // Clean Signal Targets ... - Clean(signal.targets); - - // - // Calculate Requirements ... - double r2r = maxAllowedR2R > 0 - ? maxAllowedR2R - : 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 // - ); -}