/////////////////////////////////////////////////////// // // SaherElm IT Center MQL5 X121_ATRSL ATR Indicator // --------------------------------------------------- // Name: X121_ATRSL // Description: ATR StopLoss Finer // Market Analysor ... // // // Maintainer: // ------------ // Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) // ////////////////////////////////////////////////////// // // Global Properties ... #property copyright "Copyright 2023, SaherElm IT Center" #property link "https://saherelm.ir" #property version "1.00" #property description "SaherElm X121_ATRSL Indicator" #property strict // // START Constants ... // // // Indicator Short Name ... #define ShortName "X121_ATRSL" // // Available Smoothing Methods ... enum X_XATRSL_SMOOTHING_METHOD { X_ATRSL_SMOOTHING_RMA = 0, // RMA X_ATRSL_SMOOTHING_SMA = 1, // SMA X_ATRSL_SMOOTHING_EMA = 2, // EMA X_ATRSL_SMOOTHING_WMA = 3, // WMA }; // // END Constants ... // // // START Inputs ... // // input group "Market"; input int length = 14; // Length input double step = 0.02; // Increment Step input double maximum = 0.2; // Maximum input ENUM_APPLIED_PRICE highAppliedTo = PRICE_HIGH; // High Line Applied To input ENUM_APPLIED_PRICE lowAppliedTo = PRICE_LOW; // Low Line Applied To // input group "Presentation"; input bool showHigh = true; // Show High input bool showLow = true; // Show Low input bool showSar = true; // Show PSar // // END Inputs ... // // // START Includes and Imports ... // // // Includes Logging Library ... #include "../Libraries/x-saherelm.log.lib.mq5" // // Includes Common Library ... #include "../Libraries/x-saherelm.common.lib.mq5" // // END Includes and Imports ... // // // START Buffers ... // #property indicator_chart_window // #property indicator_buffers 9 #property indicator_plots 3 // // PLOTTED Buffers ... // // HIGH ... #define highBufferIndex 0 double highBuffer[]; // #property indicator_label1 "X121_ATRSL H" #property indicator_type1 DRAW_LINE #property indicator_color1 clrLightGray #property indicator_style1 STYLE_SOLID #property indicator_width1 1 // // LOW ... #define lowBufferIndex 1 double lowBuffer[]; // #property indicator_label2 "X121_ATRSL L" #property indicator_type2 DRAW_LINE #property indicator_color2 clrLightGray #property indicator_style2 STYLE_SOLID #property indicator_width2 1 // // SAR ... #define sarBufferIndex 2 double sarBuffer[]; // #property indicator_label3 "X121_ATRSL SAR" #property indicator_type3 DRAW_LINE #property indicator_color3 clrGold #property indicator_style3 STYLE_DOT #property indicator_width3 1 // // DATA Buffers ... // // RMA ... #define rmaBufferIndex 3 double rmaBuffer[]; // // WMA ... #define wmaBufferIndex 4 double wmaBuffer[]; // // WMA CALCULATIONS ... // // MA 1 ... #define ma1BufferIndex 5 double ma1Buffer[]; // // MA P ... #define maPBufferIndex 6 double maPBuffer[]; // // EMA P ... #define emaPBufferIndex 7 double emaPBuffer[]; // // ATR ... #define atrBufferIndex 8 double atrBuffer[]; // // END Buffers ... // // // START Global Definitions: Variables, Properties and etc ... // // int maxLength; // double smoothFactor; // // WMA ... int ma1Handler = INVALID_HANDLE; int maPHandler = INVALID_HANDLE; ENUM_APPLIED_PRICE wmaAppliedTo = PRICE_CLOSE; // // EMA ... int emaPHandler = INVALID_HANDLE; // // ATR ... int atrHandler = INVALID_HANDLE; // // SAR ... int sarHandler = INVALID_HANDLE; // // END Global Definitions: Variables, Properties and etc ... // // // START Event Handlers ... // // // Initialization ... int OnInit() { // // Validate Inputs ... if (!ValidateInputs()) { return INIT_PARAMETERS_INCORRECT; } // logTag = ShortName; // // 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(); // // Calculate RMA and WMA Smooth Factoir ... smoothFactor = 1.0 / length; // // Define Index Buffers ... DefineBuffers(); // // Initialize Handlers ... if (!InitialHandlers()) { return INIT_FAILED; } // // Set Indicator ShortName ... SetIndicatorName(); // // Init Succeed ... return INIT_SUCCEEDED; } // // DeInitialization ... void OnDeinit(const int reason) { // // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function // REASON_REMOVE 1 Program removed from a chart // REASON_RECOMPILE 2 Program recompiled // REASON_CHARTCHANGE 3 A symbol or a chart period is changed // REASON_CHARTCLOSE 4 Chart closed // REASON_PARAMETERS 5 Inputs changed by a user // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings // REASON_TEMPLATE 7 Another chart template applied // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value // REASON_CLOSE 9 Terminal closed // // Here we can handle De Initialization Reasons ... IndicatorRelease(sarHandler); IndicatorRelease(atrHandler); IndicatorRelease(ma1Handler); IndicatorRelease(maPHandler); IndicatorRelease(emaPHandler); } // // Calculations ... // // Calculating what we want ... int OnCalculate( // // total Candles on chart ... const int rates_total, // // total calculated Candles on charts ... const int prev_calculated, // // history of Candles Open Time ... const datetime &time[], // // history of Candles Open Price ... const double &open[], // // history of Candles High Price ... const double &high[], // // history of Candles Low Price ... const double &low[], // // history of Candles Close Price ... const double &close[], // // history of Tick Volumes on Candle ... const long &tick_volume[], // // history of Trade Volumes ... const long &volume[], // // history of Candles Spread Price ... const int &spread[]) { // // Prepare Buffers ... ArraySetAsSeries(time, true); ArraySetAsSeries(open, true); ArraySetAsSeries(high, true); ArraySetAsSeries(low, true); ArraySetAsSeries(close, true); ArraySetAsSeries(tick_volume, true); ArraySetAsSeries(volume, true); ArraySetAsSeries(spread, true); // // this counts Available Bars ... int limit; // // Check Calculated Bars ... int sarCalculatedBars = BarsCalculated(sarHandler); int atrCalculatedBars = BarsCalculated(atrHandler); int ma1CalculatedBars = BarsCalculated(ma1Handler); int maPCalculatedBars = BarsCalculated(maPHandler); int emaPCalculatedBars = BarsCalculated(emaPHandler); if (sarCalculatedBars < maxLength || atrCalculatedBars < maxLength || ma1CalculatedBars < maxLength || maPCalculatedBars < maxLength || emaPCalculatedBars < maxLength) { return prev_calculated; } // limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; // // Buffers Copy ... int copiedSars = CopyBuffer(sarHandler, 0, 0, limit, sarBuffer); int copiedAtrs = CopyBuffer(atrHandler, 0, 0, limit, atrBuffer); int copiedMa1s = CopyBuffer(ma1Handler, 0, 0, limit, ma1Buffer); int copiedMaPs = CopyBuffer(maPHandler, 0, 0, limit, maPBuffer); int copiedEMaPs = CopyBuffer(emaPHandler, 0, 0, limit, emaPBuffer); if (copiedSars <= 0 || copiedAtrs <= 0 || copiedMa1s <= 0 || copiedMaPs <= 0 || copiedEMaPs <= 0) { return prev_calculated; } // // Main Loop ... for (int i = limit - 1; i >= 0 && !IsStopped(); i--) { // // Determines First Calculation ... bool isFirstBar = ((limit == rates_total) && i == rates_total - 1); // CalculateBuffers( i, isFirstBar, limit, rates_total, prev_calculated, open, high, low, close // ); } // return rates_total; } // // END Event Handlers ... // // // START Functions ... // // // Validate Input Args for Initialization ... bool ValidateInputs() { // bool result = // // Validate Inputs ... (length > 2 && step > 0 && maximum > step) // ; // return result; } // // Retrieve all Exists Input Max Length ... // use for Start Of Drawing ... int ExtractMaxLengthOfInputs() { // int result = 0; // // Max ... result = MathMax(result, length); // return result; } // // Define Indexes and Styles ... void DefineBuffers() { // // HIGH ... ENUM_DRAW_TYPE highDrawType = showHigh ? DRAW_LINE : DRAW_NONE; ArraySetAsSeries(highBuffer, true); SetIndexBuffer(highBufferIndex, highBuffer, INDICATOR_DATA); PlotIndexSetDouble(highBufferIndex, PLOT_EMPTY_VALUE, 0.0); PlotIndexSetInteger(highBufferIndex, PLOT_SHOW_DATA, false); PlotIndexSetInteger(highBufferIndex, PLOT_DRAW_BEGIN, maxLength); PlotIndexSetInteger(highBufferIndex, PLOT_DRAW_TYPE, highDrawType); // // LOW ... ENUM_DRAW_TYPE lowDrawType = showLow ? DRAW_LINE : DRAW_NONE; ArraySetAsSeries(lowBuffer, true); SetIndexBuffer(lowBufferIndex, lowBuffer, INDICATOR_DATA); PlotIndexSetDouble(lowBufferIndex, PLOT_EMPTY_VALUE, 0.0); PlotIndexSetInteger(lowBufferIndex, PLOT_SHOW_DATA, false); PlotIndexSetInteger(lowBufferIndex, PLOT_DRAW_BEGIN, maxLength); PlotIndexSetInteger(lowBufferIndex, PLOT_DRAW_TYPE, lowDrawType); // // SAR ... ENUM_DRAW_TYPE sarDrawType = showSar ? DRAW_LINE : DRAW_NONE; ArraySetAsSeries(sarBuffer, true); SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); PlotIndexSetDouble(sarBufferIndex, PLOT_EMPTY_VALUE, 0.0); PlotIndexSetInteger(sarBufferIndex, PLOT_SHOW_DATA, false); PlotIndexSetInteger(sarBufferIndex, PLOT_DRAW_BEGIN, maxLength); PlotIndexSetInteger(sarBufferIndex, PLOT_DRAW_TYPE, sarDrawType); // // DATA Buffers ... // // RMA ... ArraySetAsSeries(rmaBuffer, true); SetIndexBuffer(rmaBufferIndex, rmaBuffer, INDICATOR_CALCULATIONS); // // MA 1 ... ArraySetAsSeries(ma1Buffer, true); SetIndexBuffer(ma1BufferIndex, ma1Buffer, INDICATOR_CALCULATIONS); // // MA P ... ArraySetAsSeries(maPBuffer, true); SetIndexBuffer(maPBufferIndex, maPBuffer, INDICATOR_CALCULATIONS); // // WMA ... ArraySetAsSeries(wmaBuffer, true); SetIndexBuffer(wmaBufferIndex, wmaBuffer, INDICATOR_DATA); // // ATR ... ArraySetAsSeries(atrBuffer, true); SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); } // // Initialize WMA Required Handlers ... bool InitialHandlers() { // bool result = false; // // MA 1 ... ma1Handler = iMA( _Symbol, _Period, 1, // Lenght of MA 1 ... 0, MODE_SMA, wmaAppliedTo); // // MA P ... maPHandler = iMA( _Symbol, _Period, length, 0, MODE_SMA, wmaAppliedTo); // // EMA P ... emaPHandler = iMA( _Symbol, _Period, length, 0, MODE_EMA, wmaAppliedTo); // // ATR ... atrHandler = iATR( _Symbol, _Period, length); // // SAR ... sarHandler = iSAR( _Symbol, _Period, step, maximum); // result = // sarHandler != INVALID_HANDLE && atrHandler != INVALID_HANDLE && ma1Handler != INVALID_HANDLE && maPHandler != INVALID_HANDLE && emaPHandler != INVALID_HANDLE // ; // // Log Error Message if Initialization Failed ... if (!result) { LogMessage("Error in Initializing Indicator ..."); } // return result; } // // Set Indicator Short Name and also we can define Buffers Labels ... void SetIndicatorName() { // string indicatorShortName = ""; StringConcatenate(indicatorShortName, ShortName, ""); // IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); } // // Calculate Buffers ... void CalculateBuffers( int bar_index, // Selected Bar Index bool isFirstBar, // Determines First Bar const int limit, // Limit Of Calculations const int ratesTotal, // Total Rates const int prevCalculated, // Prev Calculated Bars const double &open[], // Open Price Series const double &high[], // High Price Series const double &low[], // Low Price Series const double &close[] // Close Price Series ) { // // RMA Calculation ... // double closeValue = close[bar_index]; double prevRMAValue = isFirstBar ? closeValue : rmaBuffer[bar_index + 1]; // double rmaValue = (closeValue * smoothFactor) + prevRMAValue * (1.0 - smoothFactor); // rmaBuffer[bar_index] = rmaValue; // // WMA Calculations ... // double maPValue = maPBuffer[bar_index]; double ma1Value = ma1Buffer[bar_index]; // double wmaValue; if (isFirstBar) { wmaValue = maPValue; } else { wmaValue = (ma1Value - wmaBuffer[bar_index + 1]) * smoothFactor + wmaBuffer[bar_index + 1]; } // wmaBuffer[bar_index] = wmaValue; // // CALCULATE Buffers ... // double atrValue = atrBuffer[bar_index]; double highSourcePrice = GetSourcePrice( bar_index, highAppliedTo, open, high, low, close); double lowSourcePrice = GetSourcePrice( bar_index, lowAppliedTo, open, high, low, close); // // Retrieve SMoothing Value ... // double smoothingValue = GetSmoothedValue(bar_index); // double smoothedATR = atrValue; // // HIGH ... double highValue = highSourcePrice + smoothedATR; highBuffer[bar_index] = highValue; // // LOW ... double lowValue = lowSourcePrice - smoothedATR; lowBuffer[bar_index] = lowValue; } // // Retrieve Smoothed Value based on User Choice ... double GetSmoothedValue( int bar_index // Bar Index ) { // double result = EMPTY_VALUE; // // switch (smoothingMethod) // { // // // // RMA ... // case X_ATRSL_SMOOTHING_RMA: // result = rmaBuffer[bar_index]; // break; // // // // WMA ... // case X_ATRSL_SMOOTHING_WMA: // result = wmaBuffer[bar_index]; // break; // // // // EMA ... // case X_ATRSL_SMOOTHING_EMA: // result = emaPBuffer[bar_index]; // break; // // // // SMA ... // case X_ATRSL_SMOOTHING_SMA: // result = maPBuffer[bar_index]; // break; // // // default: // result = maPBuffer[bar_index]; // break; // } // return result; } // // Retrive Which Price Selected By User as Source ... double GetSourcePrice( int bar_index, // BarIndex ENUM_APPLIED_PRICE appliedPrice, // Selected Price Source const double &open[], // Open Price Series const double &high[], // High Price Series const double &low[], // Low Price Series const double &close[] // Close Price Series ) { // double result = EMPTY_VALUE; // switch (appliedPrice) { // // OPEN ... case PRICE_OPEN: result = open[bar_index]; break; // // HIGH ... case PRICE_HIGH: result = high[bar_index]; break; // // LOW ... case PRICE_LOW: result = low[bar_index]; break; // // CLOSE ... default: case PRICE_CLOSE: result = close[bar_index]; break; } // return result; } // // END Functions ... //